From ff2e1710d00437a9e6ddd099e55374f1fbcf14e8 Mon Sep 17 00:00:00 2001 From: John Niang Date: Sun, 24 Jan 2021 17:11:10 +0800 Subject: [PATCH] Refactor checkstyle (#1241) * Refactor checkstyle.xml and add .editorconfig * Optimized imports * Rearrange codes * Fix check sytle error in source codes * Reformat test codes * Fix check style error in test codes * Config checkstyle plugin * Fix merge conflicts --- .editorconfig | 510 +++++++++++++ .github/FUNDING.yml | 2 +- CHANGELOG.md | 151 +++- README.md | 1 + SECURITY.md | 12 +- build.gradle | 6 + config/checkstyle/checkstyle.xml | 412 +++++++++-- src/main/java/run/halo/app/Application.java | 2 +- .../app/annotation/DisableOnCondition.java | 7 +- .../halo/app/annotation/SensitiveConceal.java | 6 +- .../app/aspect/DisableOnConditionAspect.java | 5 +- .../app/aspect/SensitiveConcealAspect.java | 15 +- .../halo/app/cache/AbstractCacheStore.java | 37 +- .../app/cache/AbstractStringCacheStore.java | 10 +- .../java/run/halo/app/cache/CacheStore.java | 31 +- .../java/run/halo/app/cache/CacheWrapper.java | 7 +- .../halo/app/cache/InMemoryCacheStore.java | 20 +- .../run/halo/app/cache/LevelCacheStore.java | 43 +- .../run/halo/app/cache/lock/CacheLock.java | 10 +- .../app/cache/lock/CacheLockInterceptor.java | 19 +- .../run/halo/app/cache/lock/CacheParam.java | 7 +- .../halo/app/config/HaloConfiguration.java | 15 +- .../halo/app/config/HaloMvcConfiguration.java | 86 +-- .../HaloRequestMappingHandlerMapping.java | 51 +- .../halo/app/config/SwaggerConfiguration.java | 250 ++++--- .../app/config/properties/HaloProperties.java | 22 +- .../controller/admin/api/AdminController.java | 15 +- .../admin/api/AttachmentController.java | 28 +- .../admin/api/BackupController.java | 71 +- .../admin/api/CategoryController.java | 29 +- .../admin/api/InstallController.java | 105 ++- .../admin/api/JournalCommentController.java | 54 +- .../admin/api/JournalController.java | 29 +- .../controller/admin/api/LinkController.java | 22 +- .../controller/admin/api/LogController.java | 10 +- .../controller/admin/api/MailController.java | 3 +- .../controller/admin/api/MenuController.java | 54 +- .../admin/api/MigrateController.java | 5 +- .../admin/api/OptionController.java | 27 +- .../controller/admin/api/PhotoController.java | 28 +- .../admin/api/PostCommentController.java | 54 +- .../controller/admin/api/PostController.java | 79 +- .../admin/api/SheetCommentController.java | 54 +- .../controller/admin/api/SheetController.java | 62 +- .../admin/api/StaticStorageController.java | 19 +- .../controller/admin/api/TagController.java | 26 +- .../controller/admin/api/ThemeController.java | 46 +- .../controller/admin/api/UserController.java | 41 +- .../content/ContentContentController.java | 96 +-- .../content/ContentFeedController.java | 69 +- .../content/ContentIndexController.java | 13 +- .../content/ContentSearchController.java | 19 +- .../controller/content/MainController.java | 29 +- .../content/api/ArchiveController.java | 3 +- .../content/api/CategoryController.java | 28 +- .../content/api/JournalController.java | 58 +- .../content/api/LinkController.java | 7 +- .../content/api/MenuController.java | 10 +- .../content/api/OptionController.java | 19 +- .../content/api/PhotoController.java | 15 +- .../content/api/PostController.java | 110 +-- .../content/api/SheetController.java | 72 +- .../controller/content/api/TagController.java | 30 +- .../content/api/ThemeController.java | 3 +- .../content/api/UserController.java | 3 +- .../content/model/CategoryModel.java | 25 +- .../content/model/JournalModel.java | 15 +- .../controller/content/model/LinkModel.java | 2 +- .../controller/content/model/PhotoModel.java | 15 +- .../controller/content/model/PostModel.java | 61 +- .../controller/content/model/SheetModel.java | 20 +- .../controller/content/model/TagModel.java | 19 +- .../app/controller/core/CommonController.java | 43 +- .../core/CommonResultControllerAdvice.java | 27 +- .../app/core/ControllerExceptionHandler.java | 32 +- .../run/halo/app/core/ControllerLogAop.java | 38 +- .../halo/app/core/PageJacksonSerializer.java | 6 +- .../core/freemarker/method/RandomMethod.java | 3 +- .../freemarker/tag/CategoryTagDirective.java | 37 +- .../freemarker/tag/CommentTagDirective.java | 24 +- .../core/freemarker/tag/LinkTagDirective.java | 28 +- .../core/freemarker/tag/MenuTagDirective.java | 48 +- .../tag/PaginationTagDirective.java | 162 ++-- .../freemarker/tag/PhotoTagDirective.java | 28 +- .../core/freemarker/tag/PostTagDirective.java | 57 +- .../core/freemarker/tag/TagTagDirective.java | 31 +- .../core/freemarker/tag/ToolTagDirective.java | 21 +- .../app/event/StaticStorageChangedEvent.java | 5 +- .../comment/AbstractCommentBaseEvent.java | 2 +- .../app/event/comment/CommentNewEvent.java | 2 +- .../app/event/comment/CommentReplyEvent.java | 2 +- .../run/halo/app/event/logger/LogEvent.java | 2 +- .../app/event/post/AbstractVisitEvent.java | 2 +- .../halo/app/event/post/SheetVisitEvent.java | 2 +- .../factory/StringToEnumConverterFactory.java | 4 +- .../java/run/halo/app/filter/CorsFilter.java | 34 +- .../java/run/halo/app/filter/LogFilter.java | 30 +- .../app/handler/file/AliOssFileHandler.java | 85 ++- .../app/handler/file/BaiduBosFileHandler.java | 55 +- .../halo/app/handler/file/FileHandler.java | 47 +- .../halo/app/handler/file/FileHandlers.java | 27 +- .../handler/file/HuaweiObsFileHandler.java | 86 ++- .../app/handler/file/LocalFileHandler.java | 57 +- .../app/handler/file/MinioFileHandler.java | 72 +- .../app/handler/file/QiniuOssFileHandler.java | 77 +- .../app/handler/file/SmmsFileHandler.java | 65 +- .../handler/file/TencentCosFileHandler.java | 83 ++- .../app/handler/file/UpOssFileHandler.java | 48 +- .../handler/migrate/HaloMigrateHandler.java | 3 +- .../app/handler/migrate/MigrateHandlers.java | 11 +- .../theme/config/ThemeConfigResolver.java | 5 +- .../theme/config/ThemePropertyResolver.java | 3 +- .../impl/YamlThemeConfigResolverImpl.java | 17 +- .../impl/YamlThemePropertyResolver.java | 3 +- .../handler/theme/config/support/Group.java | 3 +- .../handler/theme/config/support/Item.java | 5 +- .../theme/config/support/ThemeProperty.java | 3 +- .../halo/app/listener/StartedListener.java | 46 +- .../comment/CommentEventListener.java | 113 +-- .../FreemarkerConfigAwareListener.java | 45 +- .../post/AbstractVisitEventListener.java | 18 +- .../halo/app/mail/AbstractMailService.java | 57 +- .../run/halo/app/mail/MailProperties.java | 3 +- .../run/halo/app/mail/MailSenderFactory.java | 6 +- .../java/run/halo/app/mail/MailService.java | 22 +- .../run/halo/app/mail/MailServiceImpl.java | 24 +- .../run/halo/app/model/dto/AttachmentDTO.java | 3 +- .../halo/app/model/dto/BaseCommentDTO.java | 3 +- .../run/halo/app/model/dto/BaseMetaDTO.java | 3 +- .../run/halo/app/model/dto/CategoryDTO.java | 3 +- .../run/halo/app/model/dto/JournalDTO.java | 3 +- .../java/run/halo/app/model/dto/LogDTO.java | 3 +- .../halo/app/model/dto/OptionSimpleDTO.java | 3 +- .../java/run/halo/app/model/dto/PhotoDTO.java | 3 +- .../app/model/dto/StatisticWithUserDTO.java | 3 +- .../java/run/halo/app/model/dto/TagDTO.java | 3 +- .../java/run/halo/app/model/dto/UserDTO.java | 3 +- .../app/model/dto/base/InputConverter.java | 16 +- .../app/model/dto/base/OutputConverter.java | 12 +- .../model/dto/post/BasePostMinimalDTO.java | 3 +- .../run/halo/app/model/entity/Attachment.java | 16 +- .../halo/app/model/entity/BaseComment.java | 23 +- .../run/halo/app/model/entity/BaseEntity.java | 11 +- .../run/halo/app/model/entity/BaseMeta.java | 16 +- .../run/halo/app/model/entity/BasePost.java | 26 +- .../run/halo/app/model/entity/Category.java | 16 +- .../app/model/entity/CommentBlackList.java | 21 +- .../run/halo/app/model/entity/Journal.java | 12 +- .../java/run/halo/app/model/entity/Link.java | 12 +- .../java/run/halo/app/model/entity/Log.java | 12 +- .../java/run/halo/app/model/entity/Menu.java | 16 +- .../run/halo/app/model/entity/Option.java | 12 +- .../java/run/halo/app/model/entity/Photo.java | 20 +- .../halo/app/model/entity/PostCategory.java | 22 +- .../run/halo/app/model/entity/PostMeta.java | 3 +- .../run/halo/app/model/entity/PostTag.java | 22 +- .../run/halo/app/model/entity/SheetMeta.java | 3 +- .../java/run/halo/app/model/entity/Tag.java | 12 +- .../halo/app/model/entity/ThemeSetting.java | 17 +- .../java/run/halo/app/model/entity/User.java | 12 +- .../entity/support/CustomIdGenerator.java | 3 +- .../app/model/enums/StaticDeployType.java | 3 +- .../run/halo/app/model/enums/ValueEnum.java | 15 +- .../enums/converter/AbstractConverter.java | 13 +- .../converter/AttachmentTypeConverter.java | 3 +- .../converter/CommentStatusConverter.java | 3 +- .../enums/converter/DataTypeConverter.java | 3 +- .../enums/converter/LogTypeConverter.java | 3 +- .../enums/converter/PostStatusConverter.java | 3 +- .../enums/converter/PostTypeConverter.java | 3 +- .../app/model/params/AttachmentParam.java | 5 +- .../app/model/params/BaseCommentParam.java | 14 +- .../halo/app/model/params/BaseMetaParam.java | 10 +- .../halo/app/model/params/CategoryParam.java | 5 +- .../halo/app/model/params/InstallParam.java | 3 +- .../halo/app/model/params/JournalParam.java | 3 +- .../run/halo/app/model/params/LinkParam.java | 7 +- .../run/halo/app/model/params/LogParam.java | 7 +- .../run/halo/app/model/params/LoginParam.java | 5 +- .../run/halo/app/model/params/MailParam.java | 3 +- .../run/halo/app/model/params/MenuParam.java | 7 +- .../model/params/MultiFactorAuthParam.java | 5 +- .../halo/app/model/params/OptionParam.java | 5 +- .../halo/app/model/params/PasswordParam.java | 3 +- .../run/halo/app/model/params/PhotoParam.java | 5 +- .../run/halo/app/model/params/PostParam.java | 13 +- .../app/model/params/ResetPasswordParam.java | 3 +- .../run/halo/app/model/params/SheetParam.java | 13 +- .../run/halo/app/model/params/TagParam.java | 5 +- .../run/halo/app/model/params/UserParam.java | 21 +- .../model/properties/CommentProperties.java | 3 +- .../model/properties/PermalinkProperties.java | 6 +- .../app/model/properties/PostProperties.java | 3 +- .../app/model/properties/PropertyEnum.java | 44 +- .../halo/app/model/support/BaseResponse.java | 10 +- .../halo/app/model/support/CommentPage.java | 3 +- .../run/halo/app/model/support/HaloConst.java | 58 +- .../halo/app/model/support/Pagination.java | 3 +- .../halo/app/model/support/StaticFile.java | 5 +- .../app/model/support/StaticPageFile.java | 3 +- .../run/halo/app/model/support/ThemeFile.java | 5 +- .../run/halo/app/model/vo/ArchiveMonthVO.java | 3 +- .../run/halo/app/model/vo/ArchiveYearVO.java | 5 +- .../run/halo/app/model/vo/BaseCommentVO.java | 3 +- .../run/halo/app/model/vo/CategoryVO.java | 3 +- .../run/halo/app/model/vo/LinkTeamVO.java | 3 +- .../run/halo/app/model/vo/MenuTeamVO.java | 3 +- .../java/run/halo/app/model/vo/MenuVO.java | 5 +- .../run/halo/app/model/vo/PhotoTeamVO.java | 3 +- .../run/halo/app/model/vo/PostDetailVO.java | 5 +- .../run/halo/app/model/vo/PostListVO.java | 5 +- .../run/halo/app/model/vo/SheetDetailVO.java | 5 +- .../app/repository/AttachmentRepository.java | 6 +- .../app/repository/CategoryRepository.java | 5 +- .../CommentBlackListRepository.java | 16 +- .../repository/JournalCommentRepository.java | 26 +- .../app/repository/JournalRepository.java | 7 +- .../halo/app/repository/LinkRepository.java | 3 +- .../halo/app/repository/MenuRepository.java | 5 +- .../halo/app/repository/OptionRepository.java | 6 +- .../halo/app/repository/PhotoRepository.java | 6 +- .../repository/PostCategoryRepository.java | 24 +- .../app/repository/PostCommentRepository.java | 33 +- .../halo/app/repository/PostRepository.java | 56 +- .../app/repository/PostTagRepository.java | 18 +- .../repository/SheetCommentRepository.java | 26 +- .../halo/app/repository/SheetRepository.java | 5 +- .../halo/app/repository/TagRepository.java | 3 +- .../repository/ThemeSettingRepository.java | 9 +- .../halo/app/repository/UserRepository.java | 3 +- .../base/BaseCommentRepository.java | 78 +- .../repository/base/BaseMetaRepository.java | 14 +- .../repository/base/BasePostRepository.java | 72 +- .../app/repository/base/BaseRepository.java | 21 +- .../repository/base/BaseRepositoryImpl.java | 54 +- .../app/security/context/SecurityContext.java | 3 +- .../context/SecurityContextHolder.java | 2 +- .../filter/AbstractAuthenticationFilter.java | 115 +-- .../filter/AdminAuthenticationFilter.java | 60 +- .../filter/ApiAuthenticationFilter.java | 48 +- .../app/security/filter/ContentFilter.java | 32 +- .../handler/AuthenticationFailureHandler.java | 12 +- .../ContentAuthenticationFailureHandler.java | 13 +- .../DefaultAuthenticationFailureHandler.java | 13 +- .../AuthenticationArgumentResolver.java | 14 +- .../security/service/OneTimeTokenService.java | 3 +- .../service/impl/OneTimeTokenServiceImpl.java | 5 +- .../halo/app/security/util/SecurityUtils.java | 8 +- .../halo/app/service/AttachmentService.java | 7 +- .../run/halo/app/service/BackupService.java | 9 +- .../run/halo/app/service/CategoryService.java | 3 +- .../app/service/JournalCommentService.java | 9 +- .../run/halo/app/service/JournalService.java | 9 +- .../run/halo/app/service/LinkService.java | 6 +- .../run/halo/app/service/MenuService.java | 3 +- .../run/halo/app/service/MigrateService.java | 2 +- .../run/halo/app/service/OptionService.java | 109 +-- .../run/halo/app/service/PhotoService.java | 5 +- .../halo/app/service/PostCategoryService.java | 27 +- .../halo/app/service/PostCommentService.java | 3 +- .../run/halo/app/service/PostService.java | 105 +-- .../run/halo/app/service/PostTagService.java | 19 +- .../halo/app/service/SheetCommentService.java | 6 +- .../run/halo/app/service/SheetService.java | 19 +- .../app/service/StaticStorageService.java | 13 +- .../java/run/halo/app/service/TagService.java | 3 +- .../run/halo/app/service/ThemeService.java | 38 +- .../halo/app/service/ThemeSettingService.java | 11 +- .../run/halo/app/service/UserService.java | 16 +- .../app/service/base/AbstractCrudService.java | 32 +- .../app/service/base/BaseCommentService.java | 57 +- .../app/service/base/BaseMetaService.java | 29 +- .../app/service/base/BasePostService.java | 25 +- .../halo/app/service/base/CrudService.java | 53 +- .../app/service/impl/AdminServiceImpl.java | 152 ++-- .../service/impl/AttachmentServiceImpl.java | 47 +- .../app/service/impl/BackupServiceImpl.java | 254 +++++-- .../service/impl/BaseCommentServiceImpl.java | 148 ++-- .../app/service/impl/BaseMetaServiceImpl.java | 24 +- .../app/service/impl/BasePostServiceImpl.java | 106 +-- .../app/service/impl/CategoryServiceImpl.java | 58 +- .../impl/CommentBlackListServiceImpl.java | 35 +- .../service/impl/DataProcessServiceImpl.java | 27 +- .../impl/JournalCommentServiceImpl.java | 51 +- .../app/service/impl/JournalServiceImpl.java | 47 +- .../app/service/impl/LinkServiceImpl.java | 29 +- .../halo/app/service/impl/LogServiceImpl.java | 3 +- .../app/service/impl/MenuServiceImpl.java | 22 +- .../app/service/impl/OptionServiceImpl.java | 185 +++-- .../app/service/impl/PhotoServiceImpl.java | 29 +- .../service/impl/PostCategoryServiceImpl.java | 97 ++- .../service/impl/PostCommentServiceImpl.java | 110 +-- .../app/service/impl/PostMetaServiceImpl.java | 5 +- .../app/service/impl/PostServiceImpl.java | 259 ++++--- .../app/service/impl/PostTagServiceImpl.java | 66 +- .../service/impl/SheetCommentServiceImpl.java | 82 ++- .../service/impl/SheetMetaServiceImpl.java | 7 +- .../app/service/impl/SheetServiceImpl.java | 80 +- .../impl/StaticStorageServiceImpl.java | 35 +- .../service/impl/StatisticServiceImpl.java | 36 +- .../halo/app/service/impl/TagServiceImpl.java | 28 +- .../app/service/impl/ThemeServiceImpl.java | 232 +++--- .../service/impl/ThemeSettingServiceImpl.java | 64 +- .../app/service/impl/UserServiceImpl.java | 40 +- .../app/service/support/HaloMediaType.java | 5 +- .../app/task/RecycledPostCleaningTask.java | 36 +- .../run/halo/app/theme/ThemeFileScanner.java | 13 +- .../halo/app/theme/ThemePropertyScanner.java | 58 +- .../java/run/halo/app/utils/BeanUtils.java | 35 +- .../run/halo/app/utils/DateTimeUtils.java | 124 ++-- .../java/run/halo/app/utils/DateUtils.java | 12 +- .../java/run/halo/app/utils/FileUtils.java | 128 ++-- .../run/halo/app/utils/FilenameUtils.java | 7 +- .../java/run/halo/app/utils/GitUtils.java | 67 +- .../java/run/halo/app/utils/GithubUtils.java | 32 +- .../java/run/halo/app/utils/HaloUtils.java | 25 +- .../run/halo/app/utils/HttpClientUtils.java | 47 +- .../java/run/halo/app/utils/ImageUtils.java | 21 +- .../java/run/halo/app/utils/JsonUtils.java | 79 +- .../run/halo/app/utils/MarkdownUtils.java | 17 +- .../run/halo/app/utils/ReflectionUtils.java | 25 +- .../java/run/halo/app/utils/ServiceUtils.java | 113 +-- .../java/run/halo/app/utils/ServletUtils.java | 14 +- .../java/run/halo/app/utils/SlugUtils.java | 16 +- .../halo/app/utils/TwoFactorAuthUtils.java | 693 ++++++++++-------- .../run/halo/app/utils/ValidationUtils.java | 29 +- src/main/java/run/halo/app/utils/Version.java | 37 +- src/main/resources/application-demo.yaml | 2 +- src/main/resources/application-dev.yaml | 2 +- src/main/resources/application.yaml | 2 +- .../aspect/DisableOnConditionAspectTest.java | 27 +- .../aspect/SensitiveConcealAspectTest.java | 10 +- .../run/halo/app/cache/CacheStoreTest.java | 8 +- .../app/cache/InMemoryCacheStoreTest.java | 10 +- .../run/halo/app/conf/AntPathMatcherTest.java | 6 +- .../theme/YamlThemePropertyResolverTest.java | 21 +- .../run/halo/app/model/MediaTypeTest.java | 6 +- .../model/dto/base/InputConverterTest.java | 13 +- .../model/dto/base/OutputConverterTest.java | 10 +- .../app/model/enums/AttachmentTypeTest.java | 12 +- .../halo/app/model/enums/DataTypeTest.java | 4 +- .../app/model/params/InstallParamTest.java | 17 +- .../model/properties/PropertyEnumTest.java | 3 +- .../app/repository/SheetRepositoryTest.java | 3 +- .../halo/app/security/OneTimeTokenTest.java | 28 +- .../halo/app/service/RecoveryServiceTest.java | 20 +- .../service/impl/OptionServiceImplTest.java | 26 +- .../app/service/impl/PostServiceImplTest.java | 39 +- .../service/impl/ThemeServiceImplTest.java | 54 +- .../service/support/HaloMediaTypeTest.java | 5 +- .../run/halo/app/utils/BeanUtilsTest.java | 59 +- .../run/halo/app/utils/DateTimeUtilsTest.java | 29 +- .../halo/app/utils/DirectoryAttackTest.java | 13 +- .../run/halo/app/utils/FileUtilsTest.java | 21 +- .../run/halo/app/utils/FilenameUtilsTest.java | 4 +- src/test/java/run/halo/app/utils/GitTest.java | 44 +- .../run/halo/app/utils/GithubUtilsTest.java | 21 +- .../run/halo/app/utils/HaloUtilsTest.java | 18 +- .../halo/app/utils/HttpClientUtilsTest.java | 12 +- .../run/halo/app/utils/InetAddressTest.java | 5 +- .../run/halo/app/utils/JsonUtilsTest.java | 5 +- .../run/halo/app/utils/LocalDateTimeTest.java | 5 +- .../run/halo/app/utils/MarkdownUtilsTest.java | 22 +- .../java/run/halo/app/utils/PathTest.java | 7 +- .../java/run/halo/app/utils/PathsTest.java | 9 +- .../halo/app/utils/ReflectionUtilsTest.java | 16 +- .../java/run/halo/app/utils/TimeUnitTest.java | 3 +- src/test/java/run/halo/app/utils/URITest.java | 5 +- .../halo/app/utils/ValidationUtilsTest.java | 25 +- .../java/run/halo/app/utils/VersionTest.java | 154 ++-- .../run/halo/app/utils/VersionUtilTest.java | 12 +- .../java/run/halo/app/utils/YamlTest.java | 265 ++++--- src/test/resources/application-test.yaml | 2 +- 373 files changed, 7446 insertions(+), 4917 deletions(-) create mode 100644 .editorconfig diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000000..caba5c63e7 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,510 @@ +[*] +charset = utf-8 +end_of_line = lf +indent_size = 4 +indent_style = space +insert_final_newline = false +max_line_length = 120 +tab_width = 4 +ij_continuation_indent_size = 8 +ij_formatter_off_tag = @formatter:off +ij_formatter_on_tag = @formatter:on +ij_formatter_tags_enabled = false +ij_smart_tabs = false +ij_wrap_on_typing = false + +[*.java] +max_line_length = 100 +ij_continuation_indent_size = 4 +ij_java_align_consecutive_assignments = false +ij_java_align_consecutive_variable_declarations = false +ij_java_align_group_field_declarations = false +ij_java_align_multiline_annotation_parameters = false +ij_java_align_multiline_array_initializer_expression = false +ij_java_align_multiline_assignment = false +ij_java_align_multiline_binary_operation = false +ij_java_align_multiline_chained_methods = false +ij_java_align_multiline_extends_list = false +ij_java_align_multiline_for = true +ij_java_align_multiline_method_parentheses = false +ij_java_align_multiline_parameters = false +ij_java_align_multiline_parameters_in_calls = false +ij_java_align_multiline_parenthesized_expression = false +ij_java_align_multiline_records = true +ij_java_align_multiline_resources = true +ij_java_align_multiline_ternary_operation = false +ij_java_align_multiline_text_blocks = false +ij_java_align_multiline_throws_list = false +ij_java_align_subsequent_simple_methods = false +ij_java_align_throws_keyword = false +ij_java_annotation_parameter_wrap = off +ij_java_array_initializer_new_line_after_left_brace = false +ij_java_array_initializer_right_brace_on_new_line = false +ij_java_array_initializer_wrap = normal +ij_java_assert_statement_colon_on_next_line = false +ij_java_assert_statement_wrap = normal +ij_java_assignment_wrap = normal +ij_java_binary_operation_sign_on_next_line = false +ij_java_binary_operation_wrap = normal +ij_java_blank_lines_after_anonymous_class_header = 0 +ij_java_blank_lines_after_class_header = 0 +ij_java_blank_lines_after_imports = 1 +ij_java_blank_lines_after_package = 1 +ij_java_blank_lines_around_class = 1 +ij_java_blank_lines_around_field = 0 +ij_java_blank_lines_around_field_in_interface = 0 +ij_java_blank_lines_around_initializer = 1 +ij_java_blank_lines_around_method = 1 +ij_java_blank_lines_around_method_in_interface = 1 +ij_java_blank_lines_before_class_end = 0 +ij_java_blank_lines_before_imports = 0 +ij_java_blank_lines_before_method_body = 0 +ij_java_blank_lines_before_package = 1 +ij_java_block_brace_style = end_of_line +ij_java_block_comment_at_first_column = false +ij_java_call_parameters_new_line_after_left_paren = false +ij_java_call_parameters_right_paren_on_new_line = false +ij_java_call_parameters_wrap = normal +ij_java_case_statement_on_separate_line = true +ij_java_catch_on_new_line = false +ij_java_class_annotation_wrap = split_into_lines +ij_java_class_brace_style = end_of_line +ij_java_class_count_to_use_import_on_demand = 999 +ij_java_class_names_in_javadoc = 1 +ij_java_do_not_indent_top_level_class_members = false +ij_java_do_not_wrap_after_single_annotation = false +ij_java_do_while_brace_force = always +ij_java_doc_add_blank_line_after_description = true +ij_java_doc_add_blank_line_after_param_comments = false +ij_java_doc_add_blank_line_after_return = false +ij_java_doc_add_p_tag_on_empty_lines = true +ij_java_doc_align_exception_comments = true +ij_java_doc_align_param_comments = false +ij_java_doc_do_not_wrap_if_one_line = false +ij_java_doc_enable_formatting = true +ij_java_doc_enable_leading_asterisks = true +ij_java_doc_indent_on_continuation = false +ij_java_doc_keep_empty_lines = true +ij_java_doc_keep_empty_parameter_tag = true +ij_java_doc_keep_empty_return_tag = true +ij_java_doc_keep_empty_throws_tag = true +ij_java_doc_keep_invalid_tags = true +ij_java_doc_param_description_on_new_line = false +ij_java_doc_preserve_line_breaks = false +ij_java_doc_use_throws_not_exception_tag = true +ij_java_else_on_new_line = false +ij_java_enum_constants_wrap = normal +ij_java_extends_keyword_wrap = normal +ij_java_extends_list_wrap = normal +ij_java_field_annotation_wrap = split_into_lines +ij_java_finally_on_new_line = false +ij_java_for_brace_force = always +ij_java_for_statement_new_line_after_left_paren = false +ij_java_for_statement_right_paren_on_new_line = false +ij_java_for_statement_wrap = normal +ij_java_generate_final_locals = false +ij_java_generate_final_parameters = false +ij_java_if_brace_force = always +ij_java_imports_layout = $*, |, *, |, * +ij_java_indent_case_from_switch = true +ij_java_insert_inner_class_imports = false +ij_java_insert_override_annotation = true +ij_java_keep_blank_lines_before_right_brace = 2 +ij_java_keep_blank_lines_between_package_declaration_and_header = 2 +ij_java_keep_blank_lines_in_code = 2 +ij_java_keep_blank_lines_in_declarations = 2 +ij_java_keep_control_statement_in_one_line = true +ij_java_keep_first_column_comment = true +ij_java_keep_indents_on_empty_lines = false +ij_java_keep_line_breaks = true +ij_java_keep_multiple_expressions_in_one_line = false +ij_java_keep_simple_blocks_in_one_line = false +ij_java_keep_simple_classes_in_one_line = false +ij_java_keep_simple_lambdas_in_one_line = false +ij_java_keep_simple_methods_in_one_line = false +ij_java_label_indent_absolute = false +ij_java_label_indent_size = 0 +ij_java_lambda_brace_style = end_of_line +ij_java_layout_static_imports_separately = true +ij_java_line_comment_add_space = true +ij_java_line_comment_at_first_column = false +ij_java_method_annotation_wrap = split_into_lines +ij_java_method_brace_style = end_of_line +ij_java_method_call_chain_wrap = normal +ij_java_method_parameters_new_line_after_left_paren = false +ij_java_method_parameters_right_paren_on_new_line = false +ij_java_method_parameters_wrap = normal +ij_java_modifier_list_wrap = false +ij_java_names_count_to_use_import_on_demand = 999 +ij_java_new_line_after_lparen_in_record_header = false +ij_java_parameter_annotation_wrap = normal +ij_java_parentheses_expression_new_line_after_left_paren = false +ij_java_parentheses_expression_right_paren_on_new_line = false +ij_java_place_assignment_sign_on_next_line = false +ij_java_prefer_longer_names = true +ij_java_prefer_parameters_wrap = false +ij_java_record_components_wrap = normal +ij_java_repeat_synchronized = true +ij_java_replace_instanceof_and_cast = false +ij_java_replace_null_check = true +ij_java_replace_sum_lambda_with_method_ref = true +ij_java_resource_list_new_line_after_left_paren = false +ij_java_resource_list_right_paren_on_new_line = false +ij_java_resource_list_wrap = normal +ij_java_rparen_on_new_line_in_record_header = false +ij_java_space_after_closing_angle_bracket_in_type_argument = false +ij_java_space_after_colon = true +ij_java_space_after_comma = true +ij_java_space_after_comma_in_type_arguments = true +ij_java_space_after_for_semicolon = true +ij_java_space_after_quest = true +ij_java_space_after_type_cast = true +ij_java_space_before_annotation_array_initializer_left_brace = false +ij_java_space_before_annotation_parameter_list = false +ij_java_space_before_array_initializer_left_brace = true +ij_java_space_before_catch_keyword = true +ij_java_space_before_catch_left_brace = true +ij_java_space_before_catch_parentheses = true +ij_java_space_before_class_left_brace = true +ij_java_space_before_colon = true +ij_java_space_before_colon_in_foreach = true +ij_java_space_before_comma = false +ij_java_space_before_do_left_brace = true +ij_java_space_before_else_keyword = true +ij_java_space_before_else_left_brace = true +ij_java_space_before_finally_keyword = true +ij_java_space_before_finally_left_brace = true +ij_java_space_before_for_left_brace = true +ij_java_space_before_for_parentheses = true +ij_java_space_before_for_semicolon = false +ij_java_space_before_if_left_brace = true +ij_java_space_before_if_parentheses = true +ij_java_space_before_method_call_parentheses = false +ij_java_space_before_method_left_brace = true +ij_java_space_before_method_parentheses = false +ij_java_space_before_opening_angle_bracket_in_type_parameter = false +ij_java_space_before_quest = true +ij_java_space_before_switch_left_brace = true +ij_java_space_before_switch_parentheses = true +ij_java_space_before_synchronized_left_brace = true +ij_java_space_before_synchronized_parentheses = true +ij_java_space_before_try_left_brace = true +ij_java_space_before_try_parentheses = true +ij_java_space_before_type_parameter_list = false +ij_java_space_before_while_keyword = true +ij_java_space_before_while_left_brace = true +ij_java_space_before_while_parentheses = true +ij_java_space_inside_one_line_enum_braces = false +ij_java_space_within_empty_array_initializer_braces = false +ij_java_space_within_empty_method_call_parentheses = false +ij_java_space_within_empty_method_parentheses = false +ij_java_spaces_around_additive_operators = true +ij_java_spaces_around_assignment_operators = true +ij_java_spaces_around_bitwise_operators = true +ij_java_spaces_around_equality_operators = true +ij_java_spaces_around_lambda_arrow = true +ij_java_spaces_around_logical_operators = true +ij_java_spaces_around_method_ref_dbl_colon = false +ij_java_spaces_around_multiplicative_operators = true +ij_java_spaces_around_relational_operators = true +ij_java_spaces_around_shift_operators = true +ij_java_spaces_around_type_bounds_in_type_parameters = true +ij_java_spaces_around_unary_operator = false +ij_java_spaces_within_angle_brackets = false +ij_java_spaces_within_annotation_parentheses = false +ij_java_spaces_within_array_initializer_braces = false +ij_java_spaces_within_braces = false +ij_java_spaces_within_brackets = false +ij_java_spaces_within_cast_parentheses = false +ij_java_spaces_within_catch_parentheses = false +ij_java_spaces_within_for_parentheses = false +ij_java_spaces_within_if_parentheses = false +ij_java_spaces_within_method_call_parentheses = false +ij_java_spaces_within_method_parentheses = false +ij_java_spaces_within_parentheses = false +ij_java_spaces_within_switch_parentheses = false +ij_java_spaces_within_synchronized_parentheses = false +ij_java_spaces_within_try_parentheses = false +ij_java_spaces_within_while_parentheses = false +ij_java_special_else_if_treatment = true +ij_java_subclass_name_suffix = Impl +ij_java_ternary_operation_signs_on_next_line = false +ij_java_ternary_operation_wrap = normal +ij_java_test_name_suffix = Test +ij_java_throws_keyword_wrap = normal +ij_java_throws_list_wrap = normal +ij_java_use_external_annotations = false +ij_java_use_fq_class_names = false +ij_java_use_relative_indents = false +ij_java_use_single_class_imports = true +ij_java_variable_annotation_wrap = normal +ij_java_visibility = public +ij_java_while_brace_force = always +ij_java_while_on_new_line = false +ij_java_wrap_comments = false +ij_java_wrap_first_method_in_call_chain = false +ij_java_wrap_long_lines = true + +[*.properties] +ij_properties_align_group_field_declarations = false +ij_properties_keep_blank_lines = false +ij_properties_key_value_delimiter = equals +ij_properties_spaces_around_key_value_delimiter = false + +[.editorconfig] +ij_editorconfig_align_group_field_declarations = false +ij_editorconfig_space_after_colon = false +ij_editorconfig_space_after_comma = true +ij_editorconfig_space_before_colon = false +ij_editorconfig_space_before_comma = false +ij_editorconfig_spaces_around_assignment_operators = true + +[{*.ant, *.fxml, *.jhm, *.jnlp, *.jrxml, *.jspx, *.pom, *.rng, *.tagx, *.tld, *.wsdl, *.xml, *.xsd, *.xsl, *.xslt, *.xul}] +ij_xml_align_attributes = true +ij_xml_align_text = false +ij_xml_attribute_wrap = normal +ij_xml_block_comment_at_first_column = true +ij_xml_keep_blank_lines = 2 +ij_xml_keep_indents_on_empty_lines = false +ij_xml_keep_line_breaks = true +ij_xml_keep_line_breaks_in_text = true +ij_xml_keep_whitespaces = false +ij_xml_keep_whitespaces_around_cdata = preserve +ij_xml_keep_whitespaces_inside_cdata = false +ij_xml_line_comment_at_first_column = true +ij_xml_space_after_tag_name = false +ij_xml_space_around_equals_in_attribute = false +ij_xml_space_inside_empty_tag = false +ij_xml_text_wrap = normal + +[{*.bash, *.sh, *.zsh}] +indent_size = 2 +tab_width = 2 +ij_shell_binary_ops_start_line = false +ij_shell_keep_column_alignment_padding = false +ij_shell_minify_program = false +ij_shell_redirect_followed_by_space = false +ij_shell_switch_cases_indented = false + +[{*.gant, *.gradle, *.groovy, *.gy}] +ij_groovy_align_group_field_declarations = false +ij_groovy_align_multiline_array_initializer_expression = false +ij_groovy_align_multiline_assignment = false +ij_groovy_align_multiline_binary_operation = false +ij_groovy_align_multiline_chained_methods = false +ij_groovy_align_multiline_extends_list = false +ij_groovy_align_multiline_for = true +ij_groovy_align_multiline_list_or_map = true +ij_groovy_align_multiline_method_parentheses = false +ij_groovy_align_multiline_parameters = true +ij_groovy_align_multiline_parameters_in_calls = false +ij_groovy_align_multiline_resources = true +ij_groovy_align_multiline_ternary_operation = false +ij_groovy_align_multiline_throws_list = false +ij_groovy_align_named_args_in_map = true +ij_groovy_align_throws_keyword = false +ij_groovy_array_initializer_new_line_after_left_brace = false +ij_groovy_array_initializer_right_brace_on_new_line = false +ij_groovy_array_initializer_wrap = off +ij_groovy_assert_statement_wrap = off +ij_groovy_assignment_wrap = off +ij_groovy_binary_operation_wrap = off +ij_groovy_blank_lines_after_class_header = 0 +ij_groovy_blank_lines_after_imports = 1 +ij_groovy_blank_lines_after_package = 1 +ij_groovy_blank_lines_around_class = 1 +ij_groovy_blank_lines_around_field = 0 +ij_groovy_blank_lines_around_field_in_interface = 0 +ij_groovy_blank_lines_around_method = 1 +ij_groovy_blank_lines_around_method_in_interface = 1 +ij_groovy_blank_lines_before_imports = 1 +ij_groovy_blank_lines_before_method_body = 0 +ij_groovy_blank_lines_before_package = 0 +ij_groovy_block_brace_style = end_of_line +ij_groovy_block_comment_at_first_column = true +ij_groovy_call_parameters_new_line_after_left_paren = false +ij_groovy_call_parameters_right_paren_on_new_line = false +ij_groovy_call_parameters_wrap = off +ij_groovy_catch_on_new_line = false +ij_groovy_class_annotation_wrap = split_into_lines +ij_groovy_class_brace_style = end_of_line +ij_groovy_class_count_to_use_import_on_demand = 5 +ij_groovy_do_while_brace_force = never +ij_groovy_else_on_new_line = false +ij_groovy_enum_constants_wrap = off +ij_groovy_extends_keyword_wrap = off +ij_groovy_extends_list_wrap = off +ij_groovy_field_annotation_wrap = split_into_lines +ij_groovy_finally_on_new_line = false +ij_groovy_for_brace_force = never +ij_groovy_for_statement_new_line_after_left_paren = false +ij_groovy_for_statement_right_paren_on_new_line = false +ij_groovy_for_statement_wrap = off +ij_groovy_if_brace_force = never +ij_groovy_import_annotation_wrap = 2 +ij_groovy_indent_case_from_switch = true +ij_groovy_indent_label_blocks = true +ij_groovy_insert_inner_class_imports = false +ij_groovy_keep_blank_lines_before_right_brace = 2 +ij_groovy_keep_blank_lines_in_code = 2 +ij_groovy_keep_blank_lines_in_declarations = 2 +ij_groovy_keep_control_statement_in_one_line = true +ij_groovy_keep_first_column_comment = true +ij_groovy_keep_indents_on_empty_lines = false +ij_groovy_keep_line_breaks = true +ij_groovy_keep_multiple_expressions_in_one_line = false +ij_groovy_keep_simple_blocks_in_one_line = false +ij_groovy_keep_simple_classes_in_one_line = true +ij_groovy_keep_simple_lambdas_in_one_line = true +ij_groovy_keep_simple_methods_in_one_line = true +ij_groovy_label_indent_absolute = false +ij_groovy_label_indent_size = 0 +ij_groovy_lambda_brace_style = end_of_line +ij_groovy_layout_static_imports_separately = true +ij_groovy_line_comment_add_space = false +ij_groovy_line_comment_at_first_column = true +ij_groovy_method_annotation_wrap = split_into_lines +ij_groovy_method_brace_style = end_of_line +ij_groovy_method_call_chain_wrap = off +ij_groovy_method_parameters_new_line_after_left_paren = false +ij_groovy_method_parameters_right_paren_on_new_line = false +ij_groovy_method_parameters_wrap = off +ij_groovy_modifier_list_wrap = false +ij_groovy_names_count_to_use_import_on_demand = 3 +ij_groovy_parameter_annotation_wrap = off +ij_groovy_parentheses_expression_new_line_after_left_paren = false +ij_groovy_parentheses_expression_right_paren_on_new_line = false +ij_groovy_prefer_parameters_wrap = false +ij_groovy_resource_list_new_line_after_left_paren = false +ij_groovy_resource_list_right_paren_on_new_line = false +ij_groovy_resource_list_wrap = off +ij_groovy_space_after_assert_separator = true +ij_groovy_space_after_colon = true +ij_groovy_space_after_comma = true +ij_groovy_space_after_comma_in_type_arguments = true +ij_groovy_space_after_for_semicolon = true +ij_groovy_space_after_quest = true +ij_groovy_space_after_type_cast = true +ij_groovy_space_before_annotation_parameter_list = false +ij_groovy_space_before_array_initializer_left_brace = false +ij_groovy_space_before_assert_separator = false +ij_groovy_space_before_catch_keyword = true +ij_groovy_space_before_catch_left_brace = true +ij_groovy_space_before_catch_parentheses = true +ij_groovy_space_before_class_left_brace = true +ij_groovy_space_before_closure_left_brace = true +ij_groovy_space_before_colon = true +ij_groovy_space_before_comma = false +ij_groovy_space_before_do_left_brace = true +ij_groovy_space_before_else_keyword = true +ij_groovy_space_before_else_left_brace = true +ij_groovy_space_before_finally_keyword = true +ij_groovy_space_before_finally_left_brace = true +ij_groovy_space_before_for_left_brace = true +ij_groovy_space_before_for_parentheses = true +ij_groovy_space_before_for_semicolon = false +ij_groovy_space_before_if_left_brace = true +ij_groovy_space_before_if_parentheses = true +ij_groovy_space_before_method_call_parentheses = false +ij_groovy_space_before_method_left_brace = true +ij_groovy_space_before_method_parentheses = false +ij_groovy_space_before_quest = true +ij_groovy_space_before_switch_left_brace = true +ij_groovy_space_before_switch_parentheses = true +ij_groovy_space_before_synchronized_left_brace = true +ij_groovy_space_before_synchronized_parentheses = true +ij_groovy_space_before_try_left_brace = true +ij_groovy_space_before_try_parentheses = true +ij_groovy_space_before_while_keyword = true +ij_groovy_space_before_while_left_brace = true +ij_groovy_space_before_while_parentheses = true +ij_groovy_space_in_named_argument = true +ij_groovy_space_in_named_argument_before_colon = false +ij_groovy_space_within_empty_array_initializer_braces = false +ij_groovy_space_within_empty_method_call_parentheses = false +ij_groovy_spaces_around_additive_operators = true +ij_groovy_spaces_around_assignment_operators = true +ij_groovy_spaces_around_bitwise_operators = true +ij_groovy_spaces_around_equality_operators = true +ij_groovy_spaces_around_lambda_arrow = true +ij_groovy_spaces_around_logical_operators = true +ij_groovy_spaces_around_multiplicative_operators = true +ij_groovy_spaces_around_regex_operators = true +ij_groovy_spaces_around_relational_operators = true +ij_groovy_spaces_around_shift_operators = true +ij_groovy_spaces_within_annotation_parentheses = false +ij_groovy_spaces_within_array_initializer_braces = false +ij_groovy_spaces_within_braces = true +ij_groovy_spaces_within_brackets = false +ij_groovy_spaces_within_cast_parentheses = false +ij_groovy_spaces_within_catch_parentheses = false +ij_groovy_spaces_within_for_parentheses = false +ij_groovy_spaces_within_gstring_injection_braces = false +ij_groovy_spaces_within_if_parentheses = false +ij_groovy_spaces_within_list_or_map = false +ij_groovy_spaces_within_method_call_parentheses = false +ij_groovy_spaces_within_method_parentheses = false +ij_groovy_spaces_within_parentheses = false +ij_groovy_spaces_within_switch_parentheses = false +ij_groovy_spaces_within_synchronized_parentheses = false +ij_groovy_spaces_within_try_parentheses = false +ij_groovy_spaces_within_tuple_expression = false +ij_groovy_spaces_within_while_parentheses = false +ij_groovy_special_else_if_treatment = true +ij_groovy_ternary_operation_wrap = off +ij_groovy_throws_keyword_wrap = off +ij_groovy_throws_list_wrap = off +ij_groovy_use_flying_geese_braces = false +ij_groovy_use_fq_class_names = false +ij_groovy_use_fq_class_names_in_javadoc = true +ij_groovy_use_relative_indents = false +ij_groovy_use_single_class_imports = true +ij_groovy_variable_annotation_wrap = off +ij_groovy_while_brace_force = never +ij_groovy_while_on_new_line = false +ij_groovy_wrap_long_lines = false + +[{*.har, *.json}] +indent_size = 2 +ij_json_keep_blank_lines_in_code = 0 +ij_json_keep_indents_on_empty_lines = false +ij_json_keep_line_breaks = true +ij_json_space_after_colon = true +ij_json_space_after_comma = true +ij_json_space_before_colon = true +ij_json_space_before_comma = false +ij_json_spaces_within_braces = false +ij_json_spaces_within_brackets = false +ij_json_wrap_long_lines = false + +[{*.htm, *.html, *.sht, *.shtm, *.shtml}] +ij_html_add_new_line_before_tags = body, div, p, form, h1, h2, h3 +ij_html_align_attributes = true +ij_html_align_text = false +ij_html_attribute_wrap = normal +ij_html_block_comment_at_first_column = true +ij_html_do_not_align_children_of_min_lines = 0 +ij_html_do_not_break_if_inline_tags = title, h1, h2, h3, h4, h5, h6, p +ij_html_do_not_indent_children_of_tags = html, body, thead, tbody, tfoot +ij_html_enforce_quotes = false +ij_html_inline_tags = a, abbr, acronym, b, basefont, bdo, big, br, cite, cite, code, dfn, em, font, i, img, input, kbd, label, q, s, samp, select, small, span, strike, strong, sub, sup, textarea, tt, u, var +ij_html_keep_blank_lines = 2 +ij_html_keep_indents_on_empty_lines = false +ij_html_keep_line_breaks = true +ij_html_keep_line_breaks_in_text = true +ij_html_keep_whitespaces = false +ij_html_keep_whitespaces_inside = span, pre, textarea +ij_html_line_comment_at_first_column = true +ij_html_new_line_after_last_attribute = never +ij_html_new_line_before_first_attribute = never +ij_html_quote_style = double +ij_html_remove_new_line_before_tags = br +ij_html_space_after_tag_name = false +ij_html_space_around_equality_in_attribute = false +ij_html_space_inside_empty_tag = false +ij_html_text_wrap = normal + +[{*.yaml, *.yml}] +indent_size = 2 +ij_yaml_keep_indents_on_empty_lines = false +ij_yaml_keep_line_breaks = true diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml index b2216762b8..752176bfbc 100644 --- a/.github/FUNDING.yml +++ b/.github/FUNDING.yml @@ -5,4 +5,4 @@ patreon: halo_dev open_collective: # Replace with a single Open Collective username ko_fi: # Replace with a single Ko-fi username tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel -custom: ['https://afdian.net/@halo-dev','https://sponsor.halo.run'] +custom: [ 'https://afdian.net/@halo-dev','https://sponsor.halo.run' ] diff --git a/CHANGELOG.md b/CHANGELOG.md index 8da6bfb95e..ed7e34f7ac 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -247,6 +247,7 @@ # 1.2.0 ## Feature + - 支持自定义后台管理页面的地址,详细操作参见下方注意事项。 - 图库支持分页查询。#361 - 支持博客备份。 @@ -264,9 +265,11 @@ - 自定义页面支持设置摘要。 ## Change + - 移除 CDN 加速的设置选项。 ## Fixed + - 修复文章路径包含特殊字符时,访问文章 404 的问题。 - 修复文章路径包含中文时,预览地址不正确的问题。 - 修复上传 ico 后缀文件错误的问题。 @@ -279,7 +282,8 @@ ## 其他 ### 升级注意 -1. 如果你之前更新过 `1.2.0-beta.x`,更新到此版本需要先去数据库清空 `flyway_schema_history` 表,然后再进行升级操作。 + +1. 如果你之前更新过 `1.2.0-beta.x`,更新到此版本需要先去数据库清空 `flyway_schema_history` 表,然后再进行升级操作。 2. 更新完毕后请在关于 Halo 页面查看版本号,如 Admin 版本不是最新,请手动点击右上角更新 Admin。 3. 如果有使用 CDN 全站加速,请更新完毕后,刷新全站缓存,并清空浏览器缓存。 4. 如果 Github 中的安装包下载太慢,请到 下载。 @@ -337,16 +341,21 @@ halo: 第二步,点击 `设置`,关闭开发者选项的按钮并保存。 # 1.1.1 + ## New features + - 支持友情链接排序。@mrdong916 ## Fixed + - 修复安全漏洞。#311 # 1.1.0 + ## New features -- 编辑器支持图片上传功能,包括截图粘贴上传(可以把刀拿开了么?🌚)。 @guqing -- 文章编辑支持自定义发布时间(刀拿开了么?🌚)。@guqing + +- 编辑器支持图片上传功能,包括截图粘贴上传(可以把刀拿开了么?🌚)。 @guqing +- 文章编辑支持自定义发布时间(刀拿开了么?🌚)。@guqing - 支持选择分类或者页面添加到菜单。 - 新增百度云 BOS 云存储。@secondarycoder - 新增腾讯云 COS 云存储。@secondarycoder @@ -370,35 +379,42 @@ halo: - 支持文章加密,即私密文章。 ## Changes + - 文章列表改为从创建时间排序。 - 从附件库选择或复制附件链接进行编码处理,否则可能会导致附件访问不到的情况。 -- 编辑器从 [mavonEditor](https://github.com/hinesboy/mavonEditor) 改为 [halo-editor](https://github.com/halo-dev/halo-editor),基于 mavonEditor 开发,非常感谢 @hinesboy 做出的贡献。 +- 编辑器从 [mavonEditor](https://github.com/hinesboy/mavonEditor) + 改为 [halo-editor](https://github.com/halo-dev/halo-editor),基于 mavonEditor 开发,非常感谢 @hinesboy 做出的贡献。 - 抽离 PostSetting 组件,解决打开掉帧的问题。 -- 废弃自动保存文章的功能,由于该功能导致了大量的性能消耗,且可能会导致很多错误,所以暂时废弃。代替方案为:支持 Ctrl+S(windows or linux),Command+S(macOS)快捷键保存为草稿,以防止正在编辑的文章被丢失。 +- 废弃自动保存文章的功能,由于该功能导致了大量的性能消耗,且可能会导致很多错误,所以暂时废弃。代替方案为:支持 Ctrl+S(windows or linux),Command+S(macOS) + 快捷键保存为草稿,以防止正在编辑的文章被丢失。 - 后台发表文章之后跳转到文章列表。 - 重构上传组件,支持设定同时上传数与同时并行上传数,减少出错率。 -- 重构附件上传生成缩略图的代码,修复内存占用导致的异常。@JohnNiang +- 重构附件上传生成缩略图的代码,修复内存占用导致的异常。@JohnNiang - 优化后台部分 UI。 ## Fixed + - 修复文章选择缩略图显示异常的问题(没有处理路径转码)。 - 修复第一次安装报【该博客还没初始化】的错误提示。 - 修复文章选择缩略图显示异常的问题。 - 修复多级菜单删除父菜单,会导致子菜单无法显示的问题。 - 修复删除又拍云附件失败的问题。@Darkcolth - 修复迁移服务器之后不会恢复默认主题的问题。@jinqilin721 -- 修复文章路径中包含 & 字符会导致站点地图出现错误。 #264 @JohnNiang +- 修复文章路径中包含 & 字符会导致站点地图出现错误。 #264 @JohnNiang - 修复编辑主题模板的报错。 - 修复文章路径带英文逗号不能访问的问题。#280 - 修复文章标签和分类无法修改的问题。#279 ## 升级注意 + - 因为支持了更好的设置选项组件,请在更新 Halo 之后,同时更新主题。 - 更新完毕后请在关于 Halo 页面查看版本号,是否都为 1.1.0,如 Admin 版本有异常,请手动点击右上角更新 Admin。 - 如果有使用 CDN 全站加速,请更新完毕后,刷新全站缓存。 # 1.1.0-beta.3 + ## New features + - 后台新增首屏加载动画。 - 后台布局补充更多选项。 - 支持在后台登录页重置密码,呼出方式:SHIFT+ALT+H。#208 @@ -407,30 +423,40 @@ halo: - 支持文章加密,即私密文章。 ## Changes + - 后台文章发表之后跳转到文章列表。 ## Fixed + - 修复日志管理的部分问题。 - 修复文章路径带英文逗号不能访问的问题。#280 - 修复文章标签和分类无法修改的问题。#279 - 修复 Docker 的构建问题。 # 1.1.0-beta.2 + ## New features + - 文章设置支持设置首页文章排序规则。 - 支持设置文章置顶。 - 主题设置支持 预览模式,实现边设置边预览(仅对当前激活的主题有效)。 - 编辑主题支持选择主题进行编辑。 + ## Changes + - 移除无用代码和依赖,优化打包体积。 - 优化文章列表的评论数和点击量的样式。 + ## Fixed + - 修复编辑主题模板的报错。 # 1.1.0-beta.1 + ## New features -- 编辑器支持图片上传功能,包括截图粘贴上传(可以把刀拿开了么?🌚)。 @guqing -- 文章编辑支持自定义发布时间(刀拿开了么?🌚)。@guqing + +- 编辑器支持图片上传功能,包括截图粘贴上传(可以把刀拿开了么?🌚)。 @guqing +- 文章编辑支持自定义发布时间(刀拿开了么?🌚)。@guqing - 支持选择分类或者页面添加到菜单。 - 新增百度云 BOS 云存储。@secondarycoder - 新增腾讯云 COS 云存储。@secondarycoder @@ -444,23 +470,29 @@ halo: - 支持菜单分组,即支持多菜单。 ## Changes + - 文章列表改为从创建时间排序。 - 从附件库选择或复制附件链接进行编码处理,否则可能会导致附件访问不到的情况。 -- 编辑器从 [mavonEditor](https://github.com/hinesboy/mavonEditor) 改为 [halo-editor](https://github.com/halo-dev/halo-editor),基于 mavonEditor 开发,非常感谢 @hinesboy 做出的贡献。 +- 编辑器从 [mavonEditor](https://github.com/hinesboy/mavonEditor) + 改为 [halo-editor](https://github.com/halo-dev/halo-editor),基于 mavonEditor 开发,非常感谢 @hinesboy 做出的贡献。 - 抽离 PostSetting 组件,解决打开掉帧的问题。 -- 废弃自动保存文章的功能,由于该功能导致了大量的性能消耗,且可能会导致很多错误,所以暂时废弃。代替方案为:支持 Ctrl+S(windows or linux),Command+S(macOS)快捷键保存为草稿,以防止正在编辑的文章被丢失。 +- 废弃自动保存文章的功能,由于该功能导致了大量的性能消耗,且可能会导致很多错误,所以暂时废弃。代替方案为:支持 Ctrl+S(windows or linux),Command+S(macOS) + 快捷键保存为草稿,以防止正在编辑的文章被丢失。 ## Fixed + - 修复文章选择缩略图显示异常的问题(没有处理路径转码)。 - 修复第一次安装报【该博客还没初始化】的错误提示。 - 修复文章选择缩略图显示异常的问题。 - 修复多级菜单删除父菜单,会导致子菜单无法显示的问题。 - 修复删除又拍云附件失败的问题。@Darkcolth - 修复迁移服务器之后不会恢复默认主题的问题。@jinqilin721 -- 修复文章路径中包含 & 字符会导致站点地图出现错误。 #264 @JohnNiang +- 修复文章路径中包含 & 字符会导致站点地图出现错误。 #264 @JohnNiang # 1.0.3 + ## New features + - 首次安装自动设置头像为 [Gravatar](http://cn.gravatar.com) 头像。 - 主题列表默认将已启用的主题放在第一位。 - 关于页面支持复制环境信息。 @@ -474,12 +506,15 @@ halo: - 支持映射自定义静态资源,需要手动在 `~/.halo/static` 中添加文件。 ## Changes + - 修改拼写错误,Gavatar -> Gravatar - 将文章默认标题改为时间戳。@johnniang - 移除站点验证的设置选项(百度,Google,360,必应的站点验证)。 -- 更换 Markdown 解析器 [commonmark-java](https://github.com/atlassian/commonmark-java) 为 [flexmark](https://github.com/vsch/flexmark-java)。 +- 更换 Markdown 解析器 [commonmark-java](https://github.com/atlassian/commonmark-java) + 为 [flexmark](https://github.com/vsch/flexmark-java)。 ## Fixed + - 修复附件链接包含中文时,图片无法正常显示的问题。 - 修复回复页面的评论会失败的问题。 - 修复页面评论列表的标题列无法显示的问题。@johnniang @@ -490,6 +525,7 @@ halo: - 修复评论模块头像显示不正常的问题,需要同时更新主题。 ## 升级注意 + - 由于此次更新删除了百度,Google,360,必应的站点验证设置选项,所以更新前请备份你之前的设置,更新之后你可以在博客设置中的其他设置里面,将原先的内容放在自定义 head 中。 - 此次更新修改了 Gravatar 的拼写错误,更新之后请重新在博客设置里面设置默认头像。 - 请在更新 Halo 之后,同时更新主题。 @@ -497,30 +533,38 @@ halo: - 如果有使用 CDN 全站加速,请更新完毕后,刷新全站缓存。 # 1.0.2 + ## New features + - 支持打包成 War,部署到外部容器。 - 支持自定义博客的 head 信息。 - 提供在线更新 [halo-admin](https://github.com/halo-dev/halo-admin) 的接口。@johnniang ## Fixed -- 修复 404 请求被重定向至 /404。#186 + +- 修复 404 请求被重定向至 /404。#186 - 修复导入 Markdown 文档时,标签判断完没有加break,导致标签会继续走分类的逻辑。@wuzhi1234 - 修复导入 Markdown 文件时,slug 为空时初始化赋值。@wuzhi1234 # 1.0.2-beta.1 + - 主要修复在 `Windows` 上无法删除主题的 bug 以及其他小 bug; - 脱敏日志(密码); - 更新 Lombok 插件。 # 1.0.1 + ## Changes + - 修改 `Content api` 的参数 `api_token` 为 `api_access_key`。 ## Fixed + - 修复文章无评论时一直转圈圈的问题。 - 修复使用 MySQL 启动时索引创建失败的问题。 # 1.0.0 + ## 🎉 Halo v1.0 发布啦。 ## Features @@ -541,39 +585,54 @@ halo: 14. 还有… # 0.4.4 + ## Fixed + - 修复导出博客数据的问题。 ## Tips + > 此版本为 0.x 最后一个版本,不支持直接升级到 v1.0 版本。如需从 0.x 升级为 v1.0,请参考 https://halo.run/archives/install-migrate-from-044 # 0.4.3 + ## New features + - 支持备份全站数据,包括设置项,文章,分类,标签,评论等。 ## Tips + > 重要版本,请尽快升级。 # 0.4.2 + ## Changes + - 修改rss/sitemap的渲染方式,新增html形式的sitemap以及atom格式的feed。 -- 重构 Service 层的代码。 by @JohnNiang -- 重构 Api 的代码。 by @JohnNiang +- 重构 Service 层的代码。 by @JohnNiang +- 重构 Api 的代码。 by @JohnNiang - 文章缩略图统一改为绝对路径。 ## Fixed + - 修复附件删除失败的问题 - 修复图库删除图片导致页面报错的问题。#97 - 修复 Material 主题文章页面链接错误的问题。 # 0.4.1 + ## New features + - 支持文章加密 ## Changes -- 更换 Markdown 编辑器为 [EasyMDE](https://github.com/Ionaru/easy-markdown-editor),这是 [SimpleMDE](https://github.com/sparksuite/simplemde-markdown-editor/) 的一个分支,在继续维护。 + +- 更换 Markdown + 编辑器为 [EasyMDE](https://github.com/Ionaru/easy-markdown-editor),这是 [SimpleMDE](https://github.com/sparksuite/simplemde-markdown-editor/) + 的一个分支,在继续维护。 ## Fixed + - 修复使用 MySQL 导致时区不正确的问题。 - 修复 Docker 自动构建的镜像,主题无法使用的问题。 - 修复搜索框的 XSS 漏洞。 @@ -581,52 +640,70 @@ halo: - 修复使用oss时,选择图片路径不正确的问题 # 0.4.0 + ## New features + - 支持后台管理界面的盒子布局背景自定义。 - 支持文章备份带上元数据,也就是说,在某天你要抛弃 Halo 的时候,你可以导出文章直接放到 Hexo 等博客,并且带有文章分类信息,标签信息,发布时间,更新时间,文章标题等数据。 - Material 主题支持文章搜索,MathJax,以及代码高亮。 -- 发布新主题 [Pinghsu](https://github.com/ruibaby/pinghsu-halo),非常感谢该主题的作者 [chakhsu](https://github.com/chakhsu) 制作出如此优秀的主题。需要注意的是,使用该主题,必须升级到当前版本。 +- 发布新主题 [Pinghsu](https://github.com/ruibaby/pinghsu-halo),非常感谢该主题的作者 [chakhsu](https://github.com/chakhsu) + 制作出如此优秀的主题。需要注意的是,使用该主题,必须升级到当前版本。 ## Changes + - 升级 AdminLTE 的版本。 ## Fixed + - 修复若干Bug。 # 0.3.0 + ## :tada:2019,Happy New Year! ## New features + - Docker 部署支持自定义 `H2Database` 数据库用户名和密码。 ## Changes + - 后台管理的 pjax 插件更换为 MoOx Pjax,体验更加顺畅。 ## Fixed + - 修复若干Bug。 > 祝大家新年快乐。 # 0.2.2 + ## Fixed + - 修复后台菜单管理的问题。 # 0.2.1 + ## Fixed + - 修复后台菜单管理的排序问题。 - 修复安全问题。 # 0.2.0 + ## New features + - 支持 Markdown 文档(Hexo/Jekyll)导入 ## Changes + - 修改 `static` 目录的文件结构。 ## Fixed + - 修复多文件上传失败的问题,以及图片选择框翻页之后无法选择的问题。 ## 注意: + > 本次更新修改了静态资源路径,更新到该版本需要到数据库执行下面两条 SQL 语句,如果某些静态资源还是无法访问,重启 Halo 即可。 ```sql @@ -636,38 +713,47 @@ UPDATE HALO_COMMENT SET COMMENT_CONTENT = replace(COMMENT_CONTENT, '/static/plug ``` # 0.1.1 + ## New features + - 新增后台管理切换页面的过渡动画。 - 支持又拍云/七牛云图片上传(感谢[@ywms](https://github.com/ywms))。 - Markdown 编辑器支持数学公式渲染。 - 支持 Docker Compose 部署,真正意义上的一键部署。自动配置好 Nginx 反向代理,SSL证书。 ## Changes + - 仪表盘最新文章/最新评论的时间格式改为几...前,如:1天前,36分钟前。 - Markdown 文章渲染改为由后端渲染,使用的库为 [commonmark-java](https://github.com/atlassian/commonmark-java)。 - 支持文章修改发布时间。 - 取消自动备份功能。 ## Fixed + - 修复安装主题之后不关闭弹窗的问题。 - 修复使用 MySQL 时,报时区错误的问题。 - 修复使用 Docker 部署时,时间不正常的问题。 - 修复修改标签/分类目录时,文章信息没有刷新缓存的问题。 # 0.1 + ## New features + - 支持Docker部署。 - 新增Api Token验证,防止接口被恶意调用。 - 支持自定义页面选择指定模板渲染,模板文件名格式`page_xxx.ftl`。 ## Changes + - 后台管理页面代码结构优化。 - 更换数据库连接池为性能更好的[HikariCP](https://github.com/brettwooldridge/HikariCP),更新的时候需要修改配置文件。 ## Fixed + - 解决文章备份失败的问题。 ## 注意 + 因为更换了数据库连接池,所以需要修改配置文件(老版本升级,新部署不需要),否则会启动失败。 ```yaml @@ -678,10 +764,13 @@ spring: ``` # 0.0.9 + ## New features + - 评论支持换行显示。 ## Changes + - 弃用`Apache common Lang3`的相关方法,使用`hutool`代替。 - 后台管理主题列表中的主题名改为仅首字母大写,如`ANATOLE`改为`Anatole`。 - 新增自动备份的开关。 @@ -694,28 +783,35 @@ spring: - 更改主题设置页面的代码结构,封装`theme_option_marco`,方便调用。 ## Fixed + - 修复网站名称为空时,页面的错误。 # 0.0.8 + ## New features + - 发布文章的时候,没有缩略图会自动添加一张。 - 支持i18n,并带有英文语言包,后台可自行切换语言。 - 新增各大搜索平台验证代码的入口,需要主题支持。 - 全局美化checkbox和radio。 ## Changes + - 后台Favicon更新。 - 更改附件目录为用户目录下的`halo/upload`,需要将原来的附件目录`upload`移动到用户目录下的`halo`文件夹。 - 更换编辑器,由editor.md更换为simplemde,支持图片拖动上传。 - 下载的主题不需要再更改为指定文件夹名才能上传。 ## Fixed + - 修复评论框在某些主题下样式错乱的问题。 - 修复编辑文章的时候,分类目录不回显的问题。 - 修复Material主题第一次使用样式混乱的问题。 ## 注意 + 因为支持了i18n,所以更新的时候需要修改`application.yaml`配置文件。 + ```yaml server: port: 8090 @@ -774,18 +870,23 @@ spring: logging: file: ./logs/log.log ``` + 如上代码,修改的地方有: + 1. expose-spring-macro-helpers: false(原),现为true。 2. 在`freemarker`添加了`settings:auto_import: /spring.ftl as spring`(注意按照上面的格式)。 3. 在`spring`节点添加了`messages:basename: i18n/messages`(注意按照上面的格式)。 ### 修改方法 + 1. 将原有的`application.yaml`备份(重命名)。 2. 复制新的`application.yaml`文件到`resources`下。 3. 按照原来的配置文件修改`application.yaml`文件,需要修改端口号,数据库配置等。 # 0.0.7 + ## New features + - 新增可选是否需要审核评论的选项。 - 新增一键脚本部署方式。 - 新增NexT主题和Story主题。 @@ -796,11 +897,13 @@ logging: - 新增主题在线安装和在线更新的功能(需要安装Git)。 ## Changes + - 使用枚举方式替换大量重复字符串。 - 更改Anatole社交账号的填写方式,现在只需要填写相关账号。 - 暂时下线文章自动保存的功能,但是可以使用Ctrl+S进行保存。 ## Fixed + - 修复文章页面会出现横向滚动条的问题。 - 修复自定义页面不显示评论条数的问题。 - 修复后台评论管理样式混乱的问题。 @@ -810,7 +913,9 @@ logging: - 修复删除主题再上传相同主题时,会出现又删除上传的主题的问题。 # 0.0.6 + ## New features + - 使用Ehcache缓存。 - Anatole可在主题设置中添加自定义css。 - 新增Anatole主题的表格样式。 @@ -818,6 +923,7 @@ logging: - 新增评论的时候可以选择表情。 ## Changes + - 删除Editor.md插件中一些无用的资源。 - 规范后台界面的部分命名。 - 压缩后台的代码。 @@ -826,13 +932,16 @@ logging: - 修改评论的展示方式,改变为盖楼(嵌套)的方式。 ## Fixed + - 修复文章状态不为发布的时候也可以通过链接访问的问题。 - 修复使用MySQL初始化博客失败的问题。 - 修复前台标签下可现实草稿文章的问题。 - 修复附件的大小和尺寸显示不正确的问题。 # 0.0.5 + ## New features + - 使用[Hutool](https://github.com/looly/hutool)的encode方法来防止xss攻击。 - 新增备份功能,支持备份resources目录,数据库,以及导出文章。并且可以提供下载和发送到邮箱。 - 新增自动备份功能,每天凌晨一点会自动备份一次,超过10个备份将删除之前的备份并新建一个备份。 @@ -843,18 +952,21 @@ logging: - 后台登录支持保存登录名。 ## Changes + - 优化后台登录逻辑,登录失败超过5次,将10分钟不能登录。 - 后台管理页面支持高亮菜单。 - 压缩了Anatole主题的资源文件。 - 修改上传附件时候的压缩方式,这种方式更加完美,平均压缩之后只有几k到十几k。 ## Fixed + - 修复后台favicon获取不到的问题,会导致每刷新一次就获取一次,拖慢速度。 - 修复后台登录的xss漏洞。 - 修复上传主题之后会产生`__MACOSX`目录的问题。 - 修复附件的大小和尺寸显示不正确的问题。 # 0.0.4 + 更新汇总: 1. 修复第一次安装完成启动后首页报错的bug @@ -869,16 +981,19 @@ logging: 10. 更换web容器为undertow # 0.0.3 + 完整包:[halo-0.0.3.zip](https://pan.baidu.com/s/1kqNKwSlveqC4gS6TIF5mGQ) 更新包:[halo-0.0.3-update.zip](https://pan.baidu.com/s/1S6CNlFaZ5hvNEqQ2a50mNg) # 0.0.2 + 完整包:[halo-0.0.2.zip](http://io.ryanc.cc/index.php?share/file&user=1&sid=ecShv8rB) 更新包:[halo-0.0.2-update.zip](http://io.ryanc.cc/index.php?share/file&user=1&sid=a2zx3v6I) > 注意:为了防止配置文件被覆盖,更新包里面的配置文件被改成了application.template.yaml。如果更新之后只能进入安装页面的话,请手动在数据表`HALO_OPTIONS`里面添加`is_install`字段,值为`true`。 # 0.0.1 + [网盘下载地址](http://io.ryanc.cc/index.php?share/file&user=1&sid=YUHisTCV) 注:第一次发布版本,所以把依赖jar包也压缩进去了,以后发布的版本会有两个,一个是完整版(带有依赖),一个是增量版(不带有依赖,直接上传覆盖就可以更新)。 安装教程请看:[https://halo-doc.ryanc.cc](https://halo-doc.ryanc.cc)和[https://ryanc.cc](https://ryanc.cc) \ No newline at end of file diff --git a/README.md b/README.md index c815a59554..81f7be32e9 100755 --- a/README.md +++ b/README.md @@ -60,6 +60,7 @@ java -jar halo-latest.jar > Halo 使用 GPL-v3.0 协议开源,请尽量遵守开源协议。 ## 贡献 + 参考 [CONTRIBUTING](./CONTRIBUTING.md)。 ## 捐赠 diff --git a/SECURITY.md b/SECURITY.md index ef9cfb1204..980836e857 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -3,7 +3,9 @@ ## Supported Versions Halo currently supports the versions listed below, where as: -- :white_check_mark: indicates an active development roadmap, is therefore maintaining, and **will** receive Security Vulnerability Report. + +- :white_check_mark: indicates an active development roadmap, is therefore maintaining, and **will** receive Security + Vulnerability Report. - :x: indicates such version has already deprecated and **will not** be receiving Security Vulnerability Report. | Version | Supported | @@ -11,14 +13,16 @@ Halo currently supports the versions listed below, where as: | 0.x | :x: | | 1.x | :white_check_mark: | - ## Reporting a Vulnerability -We first appreciate and are very thankful that you've found a vulnerability issue in Halo! By disclosing such issue to Halo development team you are helping Halo to become a much more safer project than before! ;) +We first appreciate and are very thankful that you've found a vulnerability issue in Halo! By disclosing such issue to +Halo development team you are helping Halo to become a much more safer project than before! ;) -To protect the existing users of Halo, we kindly ask you to not disclose the vulnerability to anyone except the Halo development team before a fix has been rolled out. +To protect the existing users of Halo, we kindly ask you to not disclose the vulnerability to anyone except the Halo +development team before a fix has been rolled out. To Report a Vulnerability, please complete the form below, and send such report by email to `hi@halo.run`. + ``` Vulnerability has been observed in... - Docker? [n/y]: diff --git a/build.gradle b/build.gradle index 862e5e765e..f1a3639edf 100644 --- a/build.gradle +++ b/build.gradle @@ -14,6 +14,12 @@ java { sourceCompatibility = JavaVersion.VERSION_11 } +checkstyle { + toolVersion = "8.39" + showViolations = false + ignoreFailures = false +} + repositories { mavenLocal() maven { diff --git a/config/checkstyle/checkstyle.xml b/config/checkstyle/checkstyle.xml index 2d0bbc4aec..81221f5251 100644 --- a/config/checkstyle/checkstyle.xml +++ b/config/checkstyle/checkstyle.xml @@ -1,100 +1,364 @@ - - + - + + + + - + - - + + + + + + + + + + + - - - + + + + - - + + + + - - - - - - + + + + + + - - + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + - - - + + + - - + + - - - + + - - + + + + + + + + + + + + + + + + - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - diff --git a/src/main/java/run/halo/app/Application.java b/src/main/java/run/halo/app/Application.java index d200080f2b..ba8420eb68 100755 --- a/src/main/java/run/halo/app/Application.java +++ b/src/main/java/run/halo/app/Application.java @@ -15,7 +15,7 @@ public class Application { public static void main(String[] args) { // Customize the spring config location System.setProperty("spring.config.additional-location", - "optional:file:${user.home}/.halo/,optional:file:${user.home}/halo-dev/"); + "optional:file:${user.home}/.halo/,optional:file:${user.home}/halo-dev/"); // Run application SpringApplication.run(Application.class, args); diff --git a/src/main/java/run/halo/app/annotation/DisableOnCondition.java b/src/main/java/run/halo/app/annotation/DisableOnCondition.java index 5505ceb1bd..86aaccca57 100644 --- a/src/main/java/run/halo/app/annotation/DisableOnCondition.java +++ b/src/main/java/run/halo/app/annotation/DisableOnCondition.java @@ -1,10 +1,13 @@ package run.halo.app.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 org.springframework.core.annotation.AliasFor; import run.halo.app.model.enums.Mode; -import java.lang.annotation.*; - /** * 该注解可以限制某些条件下禁止访问api * diff --git a/src/main/java/run/halo/app/annotation/SensitiveConceal.java b/src/main/java/run/halo/app/annotation/SensitiveConceal.java index 2df8ea2e92..27d3bfa978 100644 --- a/src/main/java/run/halo/app/annotation/SensitiveConceal.java +++ b/src/main/java/run/halo/app/annotation/SensitiveConceal.java @@ -1,7 +1,11 @@ package run.halo.app.annotation; -import java.lang.annotation.*; +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 giveup diff --git a/src/main/java/run/halo/app/aspect/DisableOnConditionAspect.java b/src/main/java/run/halo/app/aspect/DisableOnConditionAspect.java index 817d153940..d38b9c004c 100644 --- a/src/main/java/run/halo/app/aspect/DisableOnConditionAspect.java +++ b/src/main/java/run/halo/app/aspect/DisableOnConditionAspect.java @@ -28,13 +28,14 @@ public DisableOnConditionAspect(HaloProperties haloProperties) { this.haloProperties = haloProperties; } - @Pointcut("execution(* run.halo.app.controller.*.*(..)) && @annotation(run.halo.app.annotation.DisableOnCondition)") + @Pointcut("execution(* run.halo.app.controller.*.*(..)) " + + "&& @annotation(run.halo.app.annotation.DisableOnCondition)") public void pointcut() { } @Around("pointcut() && @annotation(disableApi)") public Object around(ProceedingJoinPoint joinPoint, - DisableOnCondition disableApi) throws Throwable { + DisableOnCondition disableApi) throws Throwable { Mode mode = disableApi.mode(); if (haloProperties.getMode().equals(mode)) { throw new ForbiddenException("禁止访问"); diff --git a/src/main/java/run/halo/app/aspect/SensitiveConcealAspect.java b/src/main/java/run/halo/app/aspect/SensitiveConcealAspect.java index 0649312d51..021a268d40 100644 --- a/src/main/java/run/halo/app/aspect/SensitiveConcealAspect.java +++ b/src/main/java/run/halo/app/aspect/SensitiveConcealAspect.java @@ -19,7 +19,8 @@ public class SensitiveConcealAspect { - @Pointcut("execution(* run.halo.app.repository.*.*(..)) && @annotation(run.halo.app.annotation.SensitiveConceal)") + @Pointcut("execution(* run.halo.app.repository.*.*(..)) " + + "&& @annotation(run.halo.app.annotation.SensitiveConceal)") public void pointCut() { } @@ -31,27 +32,15 @@ private Object sensitiveMask(Object comment) { return comment; } - @Around("pointCut()") public Object mask(ProceedingJoinPoint joinPoint) throws Throwable { - Object result = joinPoint.proceed(); - if (SecurityContextHolder.getContext().isAuthenticated()) { - return result; - } - if (result instanceof Iterable) { - ((Iterable) result).forEach(this::sensitiveMask); - } - return sensitiveMask(result); - } - - } diff --git a/src/main/java/run/halo/app/cache/AbstractCacheStore.java b/src/main/java/run/halo/app/cache/AbstractCacheStore.java index c5e0b377ba..207132fd8d 100644 --- a/src/main/java/run/halo/app/cache/AbstractCacheStore.java +++ b/src/main/java/run/halo/app/cache/AbstractCacheStore.java @@ -1,5 +1,8 @@ package run.halo.app.cache; +import java.util.Date; +import java.util.Optional; +import java.util.concurrent.TimeUnit; import lombok.extern.slf4j.Slf4j; import org.springframework.lang.NonNull; import org.springframework.lang.Nullable; @@ -7,10 +10,6 @@ import run.halo.app.config.properties.HaloProperties; import run.halo.app.utils.DateUtils; -import java.util.Date; -import java.util.Optional; -import java.util.concurrent.TimeUnit; - /** * Abstract cache store. * @@ -34,7 +33,7 @@ public abstract class AbstractCacheStore implements CacheStore { /** * Puts the cache wrapper. * - * @param key key must not be null + * @param key key must not be null * @param cacheWrapper cache wrapper must not be null */ abstract void putInternal(@NonNull K key, @NonNull CacheWrapper cacheWrapper); @@ -42,19 +41,21 @@ public abstract class AbstractCacheStore implements CacheStore { /** * Puts the cache wrapper if the key is absent. * - * @param key key must not be null + * @param key key must not be null * @param cacheWrapper cache wrapper must not be null - * @return true if the key is absent and the value is set, false if the key is present before, or null if any other reason + * @return true if the key is absent and the value is set, false if the key is present + * before, or null if any other reason */ abstract Boolean putInternalIfAbsent(@NonNull K key, @NonNull CacheWrapper cacheWrapper); @Override - public @NonNull Optional get(@NonNull K key) { + public Optional get(K key) { Assert.notNull(key, "Cache key must not be blank"); return getInternal(key).map(cacheWrapper -> { // Check expiration - if (cacheWrapper.getExpireAt() != null && cacheWrapper.getExpireAt().before(run.halo.app.utils.DateUtils.now())) { + if (cacheWrapper.getExpireAt() != null + && cacheWrapper.getExpireAt().before(run.halo.app.utils.DateUtils.now())) { // Expired then delete it log.warn("Cache key: [{}] has been expired", key); @@ -70,30 +71,32 @@ public abstract class AbstractCacheStore implements CacheStore { } @Override - public void put(@NonNull K key, @NonNull V value, long timeout, @NonNull TimeUnit timeUnit) { + public void put(K key, V value, long timeout, TimeUnit timeUnit) { putInternal(key, buildCacheWrapper(value, timeout, timeUnit)); } @Override - public Boolean putIfAbsent(@NonNull K key, @NonNull V value, long timeout, @NonNull TimeUnit timeUnit) { - return putInternalIfAbsent(key, buildCacheWrapper(value, timeout, timeUnit)); + public void put(K key, V value) { + putInternal(key, buildCacheWrapper(value, 0, null)); } @Override - public void put(@NonNull K key, @NonNull V value) { - putInternal(key, buildCacheWrapper(value, 0, null)); + public Boolean putIfAbsent(K key, V value, long timeout, TimeUnit timeUnit) { + return putInternalIfAbsent(key, buildCacheWrapper(value, timeout, timeUnit)); } /** * Builds cache wrapper. * - * @param value cache value must not be null - * @param timeout the key expiry time, if the expiry time is less than 1, the cache won't be expired + * @param value cache value must not be null + * @param timeout the key expiry time, if the expiry time is less than 1, the cache won't be + * expired * @param timeUnit timeout unit must * @return cache wrapper */ @NonNull - private CacheWrapper buildCacheWrapper(@NonNull V value, long timeout, @Nullable TimeUnit timeUnit) { + private CacheWrapper buildCacheWrapper(@NonNull V value, long timeout, + @Nullable TimeUnit timeUnit) { Assert.notNull(value, "Cache value must not be null"); Assert.isTrue(timeout >= 0, "Cache expiration timeout must not be less than 1"); diff --git a/src/main/java/run/halo/app/cache/AbstractStringCacheStore.java b/src/main/java/run/halo/app/cache/AbstractStringCacheStore.java index 8497e5fc40..3c870bc51d 100644 --- a/src/main/java/run/halo/app/cache/AbstractStringCacheStore.java +++ b/src/main/java/run/halo/app/cache/AbstractStringCacheStore.java @@ -1,16 +1,15 @@ package run.halo.app.cache; import com.fasterxml.jackson.core.JsonProcessingException; +import java.io.IOException; +import java.util.Optional; +import java.util.concurrent.TimeUnit; import lombok.extern.slf4j.Slf4j; import org.springframework.lang.NonNull; import org.springframework.util.Assert; import run.halo.app.exception.ServiceException; import run.halo.app.utils.JsonUtils; -import java.io.IOException; -import java.util.Optional; -import java.util.concurrent.TimeUnit; - /** * String cache store. * @@ -38,7 +37,8 @@ public void putAny(String key, T value) { } } - public void putAny(@NonNull String key, @NonNull T value, long timeout, @NonNull TimeUnit timeUnit) { + public void putAny(@NonNull String key, @NonNull T value, long timeout, + @NonNull TimeUnit timeUnit) { try { put(key, JsonUtils.objectToJson(value), timeout, timeUnit); } catch (JsonProcessingException e) { diff --git a/src/main/java/run/halo/app/cache/CacheStore.java b/src/main/java/run/halo/app/cache/CacheStore.java index 34f0fa921e..0e65cf9841 100644 --- a/src/main/java/run/halo/app/cache/CacheStore.java +++ b/src/main/java/run/halo/app/cache/CacheStore.java @@ -1,9 +1,8 @@ package run.halo.app.cache; -import org.springframework.lang.NonNull; - import java.util.Optional; import java.util.concurrent.TimeUnit; +import org.springframework.lang.NonNull; /** * Cache store interface. @@ -27,31 +26,33 @@ public interface CacheStore { /** * Puts a cache which will be expired. * - * @param key cache key must not be null - * @param value cache value must not be null - * @param timeout the key expiration must not be less than 1 + * @param key cache key must not be null + * @param value cache value must not be null + * @param timeout the key expiration must not be less than 1 * @param timeUnit timeout unit */ void put(@NonNull K key, @NonNull V value, long timeout, @NonNull TimeUnit timeUnit); + /** - * Puts a cache which will be expired if the key is absent. + * Puts a non-expired cache. * - * @param key cache key must not be null - * @param value cache value must not be null - * @param timeout the key expiration must not be less than 1 - * @param timeUnit timeout unit must not be null - * @return true if the key is absent and the value is set, false if the key is present before, or null if any other reason + * @param key cache key must not be null + * @param value cache value must not be null */ - Boolean putIfAbsent(@NonNull K key, @NonNull V value, long timeout, @NonNull TimeUnit timeUnit); + void put(@NonNull K key, @NonNull V value); /** - * Puts a non-expired cache. + * Puts a cache which will be expired if the key is absent. * - * @param key cache key must not be null + * @param key cache key must not be null * @param value cache value must not be null + * @param timeout the key expiration must not be less than 1 + * @param timeUnit timeout unit must not be null + * @return true if the key is absent and the value is set, false if the key is present + * before, or null if any other reason */ - void put(@NonNull K key, @NonNull V value); + Boolean putIfAbsent(@NonNull K key, @NonNull V value, long timeout, @NonNull TimeUnit timeUnit); /** * Delete a key. diff --git a/src/main/java/run/halo/app/cache/CacheWrapper.java b/src/main/java/run/halo/app/cache/CacheWrapper.java index 66d7b16cbc..066b50438d 100644 --- a/src/main/java/run/halo/app/cache/CacheWrapper.java +++ b/src/main/java/run/halo/app/cache/CacheWrapper.java @@ -1,9 +1,12 @@ package run.halo.app.cache; -import lombok.*; - import java.io.Serializable; import java.util.Date; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.NoArgsConstructor; +import lombok.ToString; /** * Cache wrapper. diff --git a/src/main/java/run/halo/app/cache/InMemoryCacheStore.java b/src/main/java/run/halo/app/cache/InMemoryCacheStore.java index c4ff2ff75b..2b5bcad761 100644 --- a/src/main/java/run/halo/app/cache/InMemoryCacheStore.java +++ b/src/main/java/run/halo/app/cache/InMemoryCacheStore.java @@ -1,16 +1,15 @@ package run.halo.app.cache; -import lombok.extern.slf4j.Slf4j; -import org.springframework.lang.NonNull; -import org.springframework.util.Assert; - -import javax.annotation.PreDestroy; import java.util.Optional; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; +import javax.annotation.PreDestroy; +import lombok.extern.slf4j.Slf4j; +import org.springframework.lang.NonNull; +import org.springframework.util.Assert; /** * In-memory cache store. @@ -23,12 +22,13 @@ public class InMemoryCacheStore extends AbstractStringCacheStore { /** * Cleaner schedule period. (ms) */ - private final static long PERIOD = 60 * 1000; + private static final long PERIOD = 60 * 1000; /** * Cache container. */ - private final static ConcurrentHashMap> CACHE_CONTAINER = new ConcurrentHashMap<>(); + private static final ConcurrentHashMap> CACHE_CONTAINER = + new ConcurrentHashMap<>(); private final Timer timer; @@ -59,7 +59,8 @@ void putInternal(@NonNull String key, @NonNull CacheWrapper cacheWrapper // Put the cache wrapper CacheWrapper putCacheWrapper = CACHE_CONTAINER.put(key, cacheWrapper); - log.debug("Put [{}] cache result: [{}], original cache wrapper: [{}]", key, putCacheWrapper, cacheWrapper); + log.debug("Put [{}] cache result: [{}], original cache wrapper: [{}]", key, putCacheWrapper, + cacheWrapper); } @Override @@ -75,7 +76,8 @@ Boolean putInternalIfAbsent(@NonNull String key, @NonNull CacheWrapper c Optional valueOptional = get(key); if (valueOptional.isPresent()) { - log.warn("Failed to put the cache, because the key: [{}] has been present already", key); + log.warn("Failed to put the cache, because the key: [{}] has been present already", + key); return false; } diff --git a/src/main/java/run/halo/app/cache/LevelCacheStore.java b/src/main/java/run/halo/app/cache/LevelCacheStore.java index 8ca40b9d29..1df727040c 100644 --- a/src/main/java/run/halo/app/cache/LevelCacheStore.java +++ b/src/main/java/run/halo/app/cache/LevelCacheStore.java @@ -1,8 +1,22 @@ package run.halo.app.cache; import com.fasterxml.jackson.core.JsonProcessingException; +import java.io.File; +import java.io.IOException; +import java.nio.charset.Charset; +import java.util.Date; +import java.util.Map; +import java.util.Optional; +import java.util.Timer; +import java.util.TimerTask; +import javax.annotation.PostConstruct; +import javax.annotation.PreDestroy; import lombok.extern.slf4j.Slf4j; -import org.iq80.leveldb.*; +import org.iq80.leveldb.DB; +import org.iq80.leveldb.DBFactory; +import org.iq80.leveldb.DBIterator; +import org.iq80.leveldb.Options; +import org.iq80.leveldb.WriteBatch; import org.iq80.leveldb.impl.Iq80DBFactory; import org.springframework.lang.NonNull; import org.springframework.util.Assert; @@ -10,13 +24,6 @@ import run.halo.app.config.properties.HaloProperties; import run.halo.app.utils.JsonUtils; -import javax.annotation.PostConstruct; -import javax.annotation.PreDestroy; -import java.io.File; -import java.io.IOException; -import java.nio.charset.Charset; -import java.util.*; - /** * level-db cache store * Create by Pencilso on 2020/1/9 7:20 下午 @@ -26,7 +33,7 @@ public class LevelCacheStore extends AbstractStringCacheStore { /** * Cleaner schedule period. (ms) */ - private final static long PERIOD = 60 * 1000; + private static final long PERIOD = 60 * 1000; private static DB LEVEL_DB; @@ -76,7 +83,8 @@ Optional> getInternal(@NonNull String key) { byte[] bytes = LEVEL_DB.get(stringToBytes(key)); if (bytes != null) { String valueJson = bytesToString(bytes); - return StringUtils.isEmpty(valueJson) ? Optional.empty() : jsonToCacheWrapper(valueJson); + return StringUtils.isEmpty(valueJson) ? Optional.empty() : + jsonToCacheWrapper(valueJson); } return Optional.empty(); } @@ -92,8 +100,8 @@ Boolean putInternalIfAbsent(@NonNull String key, @NonNull CacheWrapper c Assert.notNull(cacheWrapper, "Cache wrapper must not be null"); try { LEVEL_DB.put( - stringToBytes(key), - stringToBytes(JsonUtils.objectToJson(cacheWrapper)) + stringToBytes(key), + stringToBytes(JsonUtils.objectToJson(cacheWrapper)) ); return true; } catch (JsonProcessingException e) { @@ -134,16 +142,19 @@ public void run() { } String valueJson = bytesToString(next.getValue()); - Optional> stringCacheWrapper = StringUtils.isEmpty(valueJson) ? Optional.empty() : jsonToCacheWrapper(valueJson); + Optional> stringCacheWrapper = + StringUtils.isEmpty(valueJson) ? Optional.empty() : + jsonToCacheWrapper(valueJson); if (stringCacheWrapper.isPresent()) { //get expireat time long expireAtTime = stringCacheWrapper.map(CacheWrapper::getExpireAt) - .map(Date::getTime) - .orElse(0L); + .map(Date::getTime) + .orElse(0L); //if expire if (expireAtTime != 0 && currentTimeMillis > expireAtTime) { writeBatch.delete(next.getKey()); - log.debug("deleted the cache: [{}] for expiration", bytesToString(next.getKey())); + log.debug("deleted the cache: [{}] for expiration", + bytesToString(next.getKey())); } } } diff --git a/src/main/java/run/halo/app/cache/lock/CacheLock.java b/src/main/java/run/halo/app/cache/lock/CacheLock.java index c30892cfa9..392a0afb51 100644 --- a/src/main/java/run/halo/app/cache/lock/CacheLock.java +++ b/src/main/java/run/halo/app/cache/lock/CacheLock.java @@ -1,9 +1,13 @@ package run.halo.app.cache.lock; -import org.springframework.core.annotation.AliasFor; - -import java.lang.annotation.*; +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Inherited; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; import java.util.concurrent.TimeUnit; +import org.springframework.core.annotation.AliasFor; /** * Cache lock annotation. diff --git a/src/main/java/run/halo/app/cache/lock/CacheLockInterceptor.java b/src/main/java/run/halo/app/cache/lock/CacheLockInterceptor.java index 347cd1e3ba..158cd1fb52 100644 --- a/src/main/java/run/halo/app/cache/lock/CacheLockInterceptor.java +++ b/src/main/java/run/halo/app/cache/lock/CacheLockInterceptor.java @@ -1,5 +1,6 @@ package run.halo.app.cache.lock; +import java.lang.annotation.Annotation; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.aspectj.lang.ProceedingJoinPoint; @@ -14,8 +15,6 @@ import run.halo.app.exception.ServiceException; import run.halo.app.utils.ServletUtils; -import java.lang.annotation.Annotation; - /** * Interceptor for cache lock annotation. * @@ -27,9 +26,9 @@ @Configuration public class CacheLockInterceptor { - private final static String CACHE_LOCK_PREFOX = "cache_lock_"; + private static final String CACHE_LOCK_PREFIX = "cache_lock_"; - private final static String CACHE_LOCK_VALUE = "locked"; + private static final String CACHE_LOCK_VALUE = "locked"; private final AbstractStringCacheStore cacheStore; @@ -55,10 +54,13 @@ public Object interceptCacheLock(ProceedingJoinPoint joinPoint) throws Throwable try { // Get from cache - Boolean cacheResult = cacheStore.putIfAbsent(cacheLockKey, CACHE_LOCK_VALUE, cacheLock.expired(), cacheLock.timeUnit()); + Boolean cacheResult = cacheStore + .putIfAbsent(cacheLockKey, CACHE_LOCK_VALUE, cacheLock.expired(), + cacheLock.timeUnit()); if (cacheResult == null) { - throw new ServiceException("Unknown reason of cache " + cacheLockKey).setErrorData(cacheLockKey); + throw new ServiceException("Unknown reason of cache " + cacheLockKey) + .setErrorData(cacheLockKey); } if (!cacheResult) { @@ -76,7 +78,8 @@ public Object interceptCacheLock(ProceedingJoinPoint joinPoint) throws Throwable } } - private String buildCacheLockKey(@NonNull CacheLock cacheLock, @NonNull ProceedingJoinPoint joinPoint) { + private String buildCacheLockKey(@NonNull CacheLock cacheLock, + @NonNull ProceedingJoinPoint joinPoint) { Assert.notNull(cacheLock, "Cache lock must not be null"); Assert.notNull(joinPoint, "Proceeding join point must not be null"); @@ -84,7 +87,7 @@ private String buildCacheLockKey(@NonNull CacheLock cacheLock, @NonNull Proceedi MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature(); // Build the cache lock key - StringBuilder cacheKeyBuilder = new StringBuilder(CACHE_LOCK_PREFOX); + StringBuilder cacheKeyBuilder = new StringBuilder(CACHE_LOCK_PREFIX); String delimiter = cacheLock.delimiter(); diff --git a/src/main/java/run/halo/app/cache/lock/CacheParam.java b/src/main/java/run/halo/app/cache/lock/CacheParam.java index 64c5451850..2f0ff0913f 100644 --- a/src/main/java/run/halo/app/cache/lock/CacheParam.java +++ b/src/main/java/run/halo/app/cache/lock/CacheParam.java @@ -1,6 +1,11 @@ package run.halo.app.cache.lock; -import java.lang.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; /** * Cache parameter annotation. diff --git a/src/main/java/run/halo/app/config/HaloConfiguration.java b/src/main/java/run/halo/app/config/HaloConfiguration.java index a59bd7456f..106004f4d1 100644 --- a/src/main/java/run/halo/app/config/HaloConfiguration.java +++ b/src/main/java/run/halo/app/config/HaloConfiguration.java @@ -1,6 +1,9 @@ package run.halo.app.config; import com.fasterxml.jackson.databind.ObjectMapper; +import java.security.KeyManagementException; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; @@ -21,10 +24,6 @@ import run.halo.app.repository.base.BaseRepositoryImpl; import run.halo.app.utils.HttpClientUtils; -import java.security.KeyManagementException; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; - /** * Halo configuration. * @@ -35,7 +34,8 @@ @EnableScheduling @Configuration(proxyBeanMethods = false) @EnableConfigurationProperties(HaloProperties.class) -@EnableJpaRepositories(basePackages = "run.halo.app.repository", repositoryBaseClass = BaseRepositoryImpl.class) +@EnableJpaRepositories(basePackages = "run.halo.app.repository", repositoryBaseClass = + BaseRepositoryImpl.class) public class HaloConfiguration { @Autowired @@ -49,9 +49,10 @@ public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder builder) { @Bean public RestTemplate httpsRestTemplate(RestTemplateBuilder builder) - throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException { + throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException { RestTemplate httpsRestTemplate = builder.build(); - httpsRestTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory(HttpClientUtils.createHttpsClient( + httpsRestTemplate.setRequestFactory( + new HttpComponentsClientHttpRequestFactory(HttpClientUtils.createHttpsClient( (int) haloProperties.getDownloadTimeout().toMillis()))); return httpsRestTemplate; } diff --git a/src/main/java/run/halo/app/config/HaloMvcConfiguration.java b/src/main/java/run/halo/app/config/HaloMvcConfiguration.java index 2d680eb447..3ec8f239d3 100644 --- a/src/main/java/run/halo/app/config/HaloMvcConfiguration.java +++ b/src/main/java/run/halo/app/config/HaloMvcConfiguration.java @@ -1,9 +1,19 @@ package run.halo.app.config; +import static run.halo.app.model.support.HaloConst.FILE_SEPARATOR; +import static run.halo.app.utils.HaloUtils.URL_SEPARATOR; +import static run.halo.app.utils.HaloUtils.ensureBoth; +import static run.halo.app.utils.HaloUtils.ensureSuffix; + import com.fasterxml.jackson.databind.ObjectMapper; import freemarker.core.TemplateClassResolver; import freemarker.template.TemplateException; import freemarker.template.TemplateExceptionHandler; +import java.io.IOException; +import java.util.List; +import java.util.Properties; +import java.util.concurrent.TimeUnit; +import javax.servlet.MultipartConfigElement; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.ImportAutoConfiguration; @@ -38,15 +48,6 @@ import run.halo.app.model.support.HaloConst; import run.halo.app.security.resolver.AuthenticationArgumentResolver; -import javax.servlet.MultipartConfigElement; -import java.io.IOException; -import java.util.List; -import java.util.Properties; -import java.util.concurrent.TimeUnit; - -import static run.halo.app.model.support.HaloConst.FILE_SEPARATOR; -import static run.halo.app.utils.HaloUtils.*; - /** * Halo mvc configuration. * @@ -60,19 +61,15 @@ public class HaloMvcConfiguration implements WebMvcConfigurer { private static final String FILE_PROTOCOL = "file:///"; - - @Value("${springfox.documentation.swagger-ui.base-url:}") - private String swaggerBaseUrl; - private final PageableHandlerMethodArgumentResolver pageableResolver; - private final SortHandlerMethodArgumentResolver sortResolver; - private final HaloProperties haloProperties; + @Value("${springfox.documentation.swagger-ui.base-url:}") + private String swaggerBaseUrl; public HaloMvcConfiguration(PageableHandlerMethodArgumentResolver pageableResolver, - SortHandlerMethodArgumentResolver sortResolver, - HaloProperties haloProperties) { + SortHandlerMethodArgumentResolver sortResolver, + HaloProperties haloProperties) { this.pageableResolver = pageableResolver; this.sortResolver = sortResolver; this.haloProperties = haloProperties; @@ -84,13 +81,17 @@ public HaloMvcConfiguration(PageableHandlerMethodArgumentResolver pageableResolv * @return new FreeMarkerConfigurer */ @Bean - FreeMarkerConfigurer freemarkerConfig(HaloProperties haloProperties) throws IOException, TemplateException { + FreeMarkerConfigurer freemarkerConfig(HaloProperties haloProperties) + throws IOException, TemplateException { FreeMarkerConfigurer configurer = new FreeMarkerConfigurer(); - configurer.setTemplateLoaderPaths(FILE_PROTOCOL + haloProperties.getWorkDir() + "templates/", "classpath:/templates/"); + configurer + .setTemplateLoaderPaths(FILE_PROTOCOL + haloProperties.getWorkDir() + "templates/", + "classpath:/templates/"); configurer.setDefaultEncoding("UTF-8"); Properties properties = new Properties(); - properties.setProperty("auto_import", "/common/macro/common_macro.ftl as common,/common/macro/global_macro.ftl as global"); + properties.setProperty("auto_import", + "/common/macro/common_macro.ftl as common,/common/macro/global_macro.ftl as global"); configurer.setFreemarkerSettings(properties); @@ -122,7 +123,8 @@ MultipartResolver multipartResolver(MultipartProperties multipartProperties) { resolver.setMaxUploadSize(multipartConfigElement.getMaxRequestSize()); resolver.setMaxUploadSizePerFile(multipartConfigElement.getMaxFileSize()); - //lazy multipart parsing, throwing parse exceptions once the application attempts to obtain multipart files + //lazy multipart parsing, throwing parse exceptions once the application attempts to + // obtain multipart files resolver.setResolveLazily(true); return resolver; @@ -141,16 +143,17 @@ public RequestMappingHandlerMapping getRequestMappingHandlerMapping() { @Override public void extendMessageConverters(List> converters) { converters.stream() - .filter(c -> c instanceof MappingJackson2HttpMessageConverter) - .findFirst() - .ifPresent(converter -> { - MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = (MappingJackson2HttpMessageConverter) converter; - Jackson2ObjectMapperBuilder builder = Jackson2ObjectMapperBuilder.json(); - JsonComponentModule module = new JsonComponentModule(); - module.addSerializer(PageImpl.class, new PageJacksonSerializer()); - ObjectMapper objectMapper = builder.modules(module).build(); - mappingJackson2HttpMessageConverter.setObjectMapper(objectMapper); - }); + .filter(c -> c instanceof MappingJackson2HttpMessageConverter) + .findFirst() + .ifPresent(converter -> { + MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = + (MappingJackson2HttpMessageConverter) converter; + Jackson2ObjectMapperBuilder builder = Jackson2ObjectMapperBuilder.json(); + JsonComponentModule module = new JsonComponentModule(); + module.addSerializer(PageImpl.class, new PageJacksonSerializer()); + ObjectMapper objectMapper = builder.modules(module).build(); + mappingJackson2HttpMessageConverter.setObjectMapper(objectMapper); + }); } @Override @@ -164,7 +167,7 @@ public void addArgumentResolvers(List resolvers) public void addViewControllers(ViewControllerRegistry registry) { // for backward compatibility registry.addViewController("/swagger-ui.html") - .setViewName("redirect:" + swaggerBaseUrl + "/swagger-ui/"); + .setViewName("redirect:" + swaggerBaseUrl + "/swagger-ui/"); } /** @@ -178,27 +181,28 @@ public void addResourceHandlers(ResourceHandlerRegistry registry) { // register /** resource handler. registry.addResourceHandler("/**") - .addResourceLocations("classpath:/admin/") - .addResourceLocations(workDir + "static/"); + .addResourceLocations("classpath:/admin/") + .addResourceLocations(workDir + "static/"); // register /themes/** resource handler. registry.addResourceHandler("/themes/**") - .addResourceLocations(workDir + "templates/themes/"); + .addResourceLocations(workDir + "templates/themes/"); - String uploadUrlPattern = ensureBoth(haloProperties.getUploadUrlPrefix(), URL_SEPARATOR) + "**"; + String uploadUrlPattern = + ensureBoth(haloProperties.getUploadUrlPrefix(), URL_SEPARATOR) + "**"; String adminPathPattern = ensureSuffix(haloProperties.getAdminPath(), URL_SEPARATOR) + "**"; registry.addResourceHandler(uploadUrlPattern) - .setCacheControl(CacheControl.maxAge(7L, TimeUnit.DAYS)) - .addResourceLocations(workDir + "upload/"); + .setCacheControl(CacheControl.maxAge(7L, TimeUnit.DAYS)) + .addResourceLocations(workDir + "upload/"); registry.addResourceHandler(adminPathPattern) - .addResourceLocations("classpath:/admin/"); + .addResourceLocations("classpath:/admin/"); // If doc is enable registry.addResourceHandler("swagger-ui.html") - .addResourceLocations("classpath:/META-INF/resources/"); + .addResourceLocations("classpath:/META-INF/resources/"); registry.addResourceHandler("/webjars/**") - .addResourceLocations("classpath:/META-INF/resources/webjars/"); + .addResourceLocations("classpath:/META-INF/resources/webjars/"); } diff --git a/src/main/java/run/halo/app/config/HaloRequestMappingHandlerMapping.java b/src/main/java/run/halo/app/config/HaloRequestMappingHandlerMapping.java index 5a18a93847..d63c29f277 100644 --- a/src/main/java/run/halo/app/config/HaloRequestMappingHandlerMapping.java +++ b/src/main/java/run/halo/app/config/HaloRequestMappingHandlerMapping.java @@ -1,5 +1,15 @@ package run.halo.app.config; +import static run.halo.app.utils.HaloUtils.URL_SEPARATOR; +import static run.halo.app.utils.HaloUtils.ensureBoth; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.HashSet; +import java.util.Set; +import java.util.stream.Stream; +import javax.servlet.http.HttpServletRequest; import lombok.extern.slf4j.Slf4j; import org.springframework.context.ApplicationListener; import org.springframework.util.AntPathMatcher; @@ -9,24 +19,13 @@ import run.halo.app.config.properties.HaloProperties; import run.halo.app.event.StaticStorageChangedEvent; -import javax.servlet.http.HttpServletRequest; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.HashSet; -import java.util.Set; -import java.util.stream.Stream; - -import static run.halo.app.utils.HaloUtils.URL_SEPARATOR; -import static run.halo.app.utils.HaloUtils.ensureBoth; - /** * @author ryanwang * @date 2020-03-24 */ @Slf4j public class HaloRequestMappingHandlerMapping extends RequestMappingHandlerMapping - implements ApplicationListener { + implements ApplicationListener { private final Set blackPatterns = new HashSet<>(16); @@ -41,7 +40,8 @@ public HaloRequestMappingHandlerMapping(HaloProperties haloProperties) { } @Override - protected HandlerMethod lookupHandlerMethod(String lookupPath, HttpServletRequest request) throws Exception { + protected HandlerMethod lookupHandlerMethod(String lookupPath, HttpServletRequest request) + throws Exception { log.debug("Looking path: [{}]", lookupPath); for (String blackPattern : blackPatterns) { if (this.pathMatcher.match(blackPattern, lookupPath)) { @@ -53,8 +53,10 @@ protected HandlerMethod lookupHandlerMethod(String lookupPath, HttpServletReques } private void initBlackPatterns() { - String uploadUrlPattern = ensureBoth(haloProperties.getUploadUrlPrefix(), URL_SEPARATOR) + "**"; - String adminPathPattern = ensureBoth(haloProperties.getAdminPath(), URL_SEPARATOR) + "?*/**"; + String uploadUrlPattern = + ensureBoth(haloProperties.getUploadUrlPrefix(), URL_SEPARATOR) + "**"; + String adminPathPattern = + ensureBoth(haloProperties.getAdminPath(), URL_SEPARATOR) + "?*/**"; blackPatterns.add("/themes/**"); blackPatterns.add("/js/**"); @@ -79,16 +81,17 @@ public void onApplicationEvent(StaticStorageChangedEvent event) { blackPatterns.clear(); initBlackPatterns(); rootPathStream.forEach(rootPath -> { - if (Files.isDirectory(rootPath)) { - String directoryPattern = "/" + rootPath.getFileName().toString() + "/**"; - blackPatterns.add(directoryPattern); - log.debug("Exclude for folder path pattern: [{}]", directoryPattern); - } else { - String pathPattern = "/" + rootPath.getFileName().toString(); - blackPatterns.add(pathPattern); - log.debug("Exclude for file path pattern: [{}]", pathPattern); - } + if (Files.isDirectory(rootPath)) { + String directoryPattern = "/" + rootPath.getFileName().toString() + + "/**"; + blackPatterns.add(directoryPattern); + log.debug("Exclude for folder path pattern: [{}]", directoryPattern); + } else { + String pathPattern = "/" + rootPath.getFileName().toString(); + blackPatterns.add(pathPattern); + log.debug("Exclude for file path pattern: [{}]", pathPattern); } + } ); } } catch (IOException e) { diff --git a/src/main/java/run/halo/app/config/SwaggerConfiguration.java b/src/main/java/run/halo/app/config/SwaggerConfiguration.java index e97d00df61..d4cdb9c117 100644 --- a/src/main/java/run/halo/app/config/SwaggerConfiguration.java +++ b/src/main/java/run/halo/app/config/SwaggerConfiguration.java @@ -1,7 +1,19 @@ package run.halo.app.config; +import static run.halo.app.model.support.HaloConst.ADMIN_TOKEN_HEADER_NAME; +import static run.halo.app.model.support.HaloConst.ADMIN_TOKEN_QUERY_NAME; +import static run.halo.app.model.support.HaloConst.API_ACCESS_KEY_HEADER_NAME; +import static run.halo.app.model.support.HaloConst.API_ACCESS_KEY_QUERY_NAME; +import static run.halo.app.model.support.HaloConst.HALO_VERSION; +import static springfox.documentation.schema.AlternateTypeRules.newRule; + import com.fasterxml.classmate.TypeResolver; import io.swagger.models.auth.In; +import java.lang.reflect.Type; +import java.time.temporal.Temporal; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; import lombok.extern.slf4j.Slf4j; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; @@ -15,23 +27,32 @@ import run.halo.app.config.properties.HaloProperties; import run.halo.app.model.entity.User; import run.halo.app.security.support.UserDetail; -import springfox.documentation.builders.*; +import springfox.documentation.builders.AlternateTypeBuilder; +import springfox.documentation.builders.AlternateTypePropertyBuilder; +import springfox.documentation.builders.ApiInfoBuilder; +import springfox.documentation.builders.PathSelectors; +import springfox.documentation.builders.RequestHandlerSelectors; +import springfox.documentation.builders.ResponseMessageBuilder; import springfox.documentation.schema.AlternateTypeRule; import springfox.documentation.schema.AlternateTypeRuleConvention; -import springfox.documentation.service.*; +import springfox.documentation.service.ApiInfo; +import springfox.documentation.service.ApiKey; +import springfox.documentation.service.AuthorizationScope; +import springfox.documentation.service.Contact; +import springfox.documentation.service.ResponseMessage; +import springfox.documentation.service.SecurityReference; +import springfox.documentation.service.SecurityScheme; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spi.service.contexts.SecurityContext; import springfox.documentation.spring.web.plugins.Docket; -import springfox.documentation.swagger.web.*; - -import java.lang.reflect.Type; -import java.time.temporal.Temporal; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -import static run.halo.app.model.support.HaloConst.*; -import static springfox.documentation.schema.AlternateTypeRules.newRule; +import springfox.documentation.swagger.web.DocExpansion; +import springfox.documentation.swagger.web.ModelRendering; +import springfox.documentation.swagger.web.OperationsSorter; +import springfox.documentation.swagger.web.SecurityConfiguration; +import springfox.documentation.swagger.web.SecurityConfigurationBuilder; +import springfox.documentation.swagger.web.TagsSorter; +import springfox.documentation.swagger.web.UiConfiguration; +import springfox.documentation.swagger.web.UiConfigurationBuilder; /** * Swagger configuration. @@ -41,20 +62,20 @@ @Slf4j @Configuration @ConditionalOnProperty( - value = "springfox.documentation.enabled", - havingValue = "true", - matchIfMissing = true) + value = "springfox.documentation.enabled", + havingValue = "true", + matchIfMissing = true) public class SwaggerConfiguration { private final HaloProperties haloProperties; private final List globalResponses = Arrays.asList( - new ResponseMessageBuilder().code(200).message("Success").build(), - new ResponseMessageBuilder().code(400).message("Bad request").build(), - new ResponseMessageBuilder().code(401).message("Unauthorized").build(), - new ResponseMessageBuilder().code(403).message("Forbidden").build(), - new ResponseMessageBuilder().code(404).message("Not found").build(), - new ResponseMessageBuilder().code(500).message("Internal server error").build()); + new ResponseMessageBuilder().code(200).message("Success").build(), + new ResponseMessageBuilder().code(400).message("Bad request").build(), + new ResponseMessageBuilder().code(401).message("Unauthorized").build(), + new ResponseMessageBuilder().code(403).message("Forbidden").build(), + new ResponseMessageBuilder().code(404).message("Not found").build(), + new ResponseMessageBuilder().code(500).message("Internal server error").build()); public SwaggerConfiguration(HaloProperties haloProperties) { this.haloProperties = haloProperties; @@ -63,10 +84,10 @@ public SwaggerConfiguration(HaloProperties haloProperties) { @Bean public Docket haloDefaultApi() { return buildApiDocket("run.halo.app.content.api", - "run.halo.app.controller.content.api", - "/api/content/**") - .securitySchemes(contentApiKeys()) - .securityContexts(contentSecurityContext()); + "run.halo.app.controller.content.api", + "/api/content/**") + .securitySchemes(contentApiKeys()) + .securityContexts(contentSecurityContext()); } @Bean @@ -76,120 +97,124 @@ public Docket haloAdminApi() { } return buildApiDocket("run.halo.app.admin.api", - "run.halo.app.controller.admin", - "/api/admin/**") - .securitySchemes(adminApiKeys()) - .securityContexts(adminSecurityContext()); + "run.halo.app.controller.admin", + "/api/admin/**") + .securitySchemes(adminApiKeys()) + .securityContexts(adminSecurityContext()); } @Bean SecurityConfiguration security() { return SecurityConfigurationBuilder.builder() - .clientId("halo-app-client-id") - .clientSecret("halo-app-client-secret") - .realm("halo-app-realm") - .appName("halo-app") - .scopeSeparator(",") - .additionalQueryStringParams(null) - .useBasicAuthenticationWithAccessCodeGrant(false) - .build(); + .clientId("halo-app-client-id") + .clientSecret("halo-app-client-secret") + .realm("halo-app-realm") + .appName("halo-app") + .scopeSeparator(",") + .additionalQueryStringParams(null) + .useBasicAuthenticationWithAccessCodeGrant(false) + .build(); } @Bean UiConfiguration uiConfig() { return UiConfigurationBuilder.builder() - .deepLinking(true) - .displayOperationId(false) - .defaultModelsExpandDepth(1) - .defaultModelExpandDepth(1) - .defaultModelRendering(ModelRendering.EXAMPLE) - .displayRequestDuration(false) - .docExpansion(DocExpansion.NONE) - .filter(false) - .maxDisplayedTags(null) - .operationsSorter(OperationsSorter.ALPHA) - .showExtensions(false) - .showCommonExtensions(false) - .tagsSorter(TagsSorter.ALPHA) - .supportedSubmitMethods(UiConfiguration.Constants.DEFAULT_SUBMIT_METHODS) - .validatorUrl(null) - .build(); - } - - private Docket buildApiDocket(@NonNull String groupName, @NonNull String basePackage, @NonNull String antPattern) { + .deepLinking(true) + .displayOperationId(false) + .defaultModelsExpandDepth(1) + .defaultModelExpandDepth(1) + .defaultModelRendering(ModelRendering.EXAMPLE) + .displayRequestDuration(false) + .docExpansion(DocExpansion.NONE) + .filter(false) + .maxDisplayedTags(null) + .operationsSorter(OperationsSorter.ALPHA) + .showExtensions(false) + .showCommonExtensions(false) + .tagsSorter(TagsSorter.ALPHA) + .supportedSubmitMethods(UiConfiguration.Constants.DEFAULT_SUBMIT_METHODS) + .validatorUrl(null) + .build(); + } + + private Docket buildApiDocket(@NonNull String groupName, @NonNull String basePackage, + @NonNull String antPattern) { Assert.hasText(groupName, "Group name must not be blank"); Assert.hasText(basePackage, "Base package must not be blank"); Assert.hasText(antPattern, "Ant pattern must not be blank"); return new Docket(DocumentationType.SWAGGER_2) - .groupName(groupName) - .select() - .apis(RequestHandlerSelectors.basePackage(basePackage)) - .paths(PathSelectors.ant(antPattern)) - .build() - .apiInfo(apiInfo()) - .useDefaultResponseMessages(false) - .globalResponseMessage(RequestMethod.GET, globalResponses) - .globalResponseMessage(RequestMethod.POST, globalResponses) - .globalResponseMessage(RequestMethod.DELETE, globalResponses) - .globalResponseMessage(RequestMethod.PUT, globalResponses) - .directModelSubstitute(Temporal.class, String.class); + .groupName(groupName) + .select() + .apis(RequestHandlerSelectors.basePackage(basePackage)) + .paths(PathSelectors.ant(antPattern)) + .build() + .apiInfo(apiInfo()) + .useDefaultResponseMessages(false) + .globalResponseMessage(RequestMethod.GET, globalResponses) + .globalResponseMessage(RequestMethod.POST, globalResponses) + .globalResponseMessage(RequestMethod.DELETE, globalResponses) + .globalResponseMessage(RequestMethod.PUT, globalResponses) + .directModelSubstitute(Temporal.class, String.class); } private List adminApiKeys() { return Arrays.asList( - new ApiKey("Token from header", ADMIN_TOKEN_HEADER_NAME, In.HEADER.name()), - new ApiKey("Token from query", ADMIN_TOKEN_QUERY_NAME, In.QUERY.name()) + new ApiKey("Token from header", ADMIN_TOKEN_HEADER_NAME, In.HEADER.name()), + new ApiKey("Token from query", ADMIN_TOKEN_QUERY_NAME, In.QUERY.name()) ); } private List adminSecurityContext() { return Collections.singletonList( - SecurityContext.builder() - .securityReferences(defaultAuth()) - .forPaths(PathSelectors.regex("/api/admin/.*")) - .build() + SecurityContext.builder() + .securityReferences(defaultAuth()) + .forPaths(PathSelectors.regex("/api/admin/.*")) + .build() ); } private List contentApiKeys() { return Arrays.asList( - new ApiKey("Access key from header", API_ACCESS_KEY_HEADER_NAME, In.HEADER.name()), - new ApiKey("Access key from query", API_ACCESS_KEY_QUERY_NAME, In.QUERY.name()) + new ApiKey("Access key from header", API_ACCESS_KEY_HEADER_NAME, In.HEADER.name()), + new ApiKey("Access key from query", API_ACCESS_KEY_QUERY_NAME, In.QUERY.name()) ); } private List contentSecurityContext() { return Collections.singletonList( - SecurityContext.builder() - .securityReferences(contentApiAuth()) - .forPaths(PathSelectors.regex("/api/content/.*")) - .build() + SecurityContext.builder() + .securityReferences(contentApiAuth()) + .forPaths(PathSelectors.regex("/api/content/.*")) + .build() ); } private List defaultAuth() { - AuthorizationScope[] authorizationScopes = {new AuthorizationScope("Admin api", "Access admin api")}; + AuthorizationScope[] authorizationScopes = + {new AuthorizationScope("Admin api", "Access admin api")}; return Arrays.asList(new SecurityReference("Token from header", authorizationScopes), - new SecurityReference("Token from query", authorizationScopes)); + new SecurityReference("Token from query", authorizationScopes)); } private List contentApiAuth() { - AuthorizationScope[] authorizationScopes = {new AuthorizationScope("content api", "Access content api")}; + AuthorizationScope[] authorizationScopes = + {new AuthorizationScope("content api", "Access content api")}; return Arrays.asList(new SecurityReference("Access key from header", authorizationScopes), - new SecurityReference("Access key from query", authorizationScopes)); + new SecurityReference("Access key from query", authorizationScopes)); } private ApiInfo apiInfo() { return new ApiInfoBuilder() - .title("Halo API Documentation") - .description("Documentation for Halo API") - .version(HALO_VERSION) - .termsOfServiceUrl("https://github.com/halo-dev") - .contact(new Contact("halo-dev", "https://github.com/halo-dev/halo/issues", "hi@halo.run")) - .license("GNU General Public License v3.0") - .licenseUrl("https://github.com/halo-dev/halo/blob/master/LICENSE") - .build(); + .title("Halo API Documentation") + .description("Documentation for Halo API") + .version(HALO_VERSION) + .termsOfServiceUrl("https://github.com/halo-dev") + .contact( + new Contact("halo-dev", "https://github.com/halo-dev/halo/issues", "hi@halo.run")) + .license("GNU General Public License v3.0") + .licenseUrl("https://github.com/halo-dev/halo/blob/master/LICENSE") + .build(); } @Bean @@ -203,10 +228,10 @@ public int getOrder() { @Override public List rules() { return Arrays.asList( - newRule(User.class, emptyMixin(User.class)), - newRule(UserDetail.class, emptyMixin(UserDetail.class)), - newRule(resolver.resolve(Pageable.class), resolver.resolve(pageableMixin())), - newRule(resolver.resolve(Sort.class), resolver.resolve(sortMixin()))); + newRule(User.class, emptyMixin(User.class)), + newRule(UserDetail.class, emptyMixin(UserDetail.class)), + newRule(resolver.resolve(Pageable.class), resolver.resolve(pageableMixin())), + newRule(resolver.resolve(Sort.class), resolver.resolve(sortMixin()))); } }; } @@ -221,31 +246,38 @@ private Type emptyMixin(Class clazz) { Assert.notNull(clazz, "class type must not be null"); return new AlternateTypeBuilder() - .fullyQualifiedClassName(String.format("%s.generated.%s", clazz.getPackage().getName(), clazz.getSimpleName())) - .withProperties(Collections.emptyList()) - .build(); + .fullyQualifiedClassName(String + .format("%s.generated.%s", clazz.getPackage().getName(), clazz.getSimpleName())) + .withProperties(Collections.emptyList()) + .build(); } private Type sortMixin() { return new AlternateTypeBuilder() - .fullyQualifiedClassName(String.format("%s.generated.%s", Sort.class.getPackage().getName(), Sort.class.getSimpleName())) - .withProperties(Collections.singletonList(property(String[].class, "sort"))) - .build(); + .fullyQualifiedClassName(String + .format("%s.generated.%s", Sort.class.getPackage().getName(), + Sort.class.getSimpleName())) + .withProperties(Collections.singletonList(property(String[].class, "sort"))) + .build(); } private Type pageableMixin() { return new AlternateTypeBuilder() - .fullyQualifiedClassName(String.format("%s.generated.%s", Pageable.class.getPackage().getName(), Pageable.class.getSimpleName())) - .withProperties(Arrays.asList(property(Integer.class, "page"), property(Integer.class, "size"), property(String[].class, "sort"))) - .build(); + .fullyQualifiedClassName(String + .format("%s.generated.%s", Pageable.class.getPackage().getName(), + Pageable.class.getSimpleName())) + .withProperties(Arrays + .asList(property(Integer.class, "page"), property(Integer.class, "size"), + property(String[].class, "sort"))) + .build(); } private AlternateTypePropertyBuilder property(Class type, String name) { return new AlternateTypePropertyBuilder() - .withName(name) - .withType(type) - .withCanRead(true) - .withCanWrite(true); + .withName(name) + .withType(type) + .withCanRead(true) + .withCanWrite(true); } } diff --git a/src/main/java/run/halo/app/config/properties/HaloProperties.java b/src/main/java/run/halo/app/config/properties/HaloProperties.java index e69c772a72..ee3a1be6e3 100644 --- a/src/main/java/run/halo/app/config/properties/HaloProperties.java +++ b/src/main/java/run/halo/app/config/properties/HaloProperties.java @@ -1,14 +1,17 @@ package run.halo.app.config.properties; +import static run.halo.app.model.support.HaloConst.FILE_SEPARATOR; +import static run.halo.app.model.support.HaloConst.TEMP_DIR; +import static run.halo.app.model.support.HaloConst.USER_HOME; +import static run.halo.app.utils.HaloUtils.ensureSuffix; + +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import run.halo.app.model.enums.Mode; -import java.time.Duration; - -import static run.halo.app.model.support.HaloConst.*; -import static run.halo.app.utils.HaloUtils.ensureSuffix; - /** * Halo configuration properties. @@ -54,17 +57,20 @@ public class HaloProperties { /** * Halo backup directory.(Not recommended to modify this config); */ - private String backupDir = ensureSuffix(TEMP_DIR, FILE_SEPARATOR) + "halo-backup" + FILE_SEPARATOR; + private String backupDir = + ensureSuffix(TEMP_DIR, FILE_SEPARATOR) + "halo-backup" + FILE_SEPARATOR; /** * Halo backup markdown directory.(Not recommended to modify this config); */ - private String backupMarkdownDir = ensureSuffix(TEMP_DIR, FILE_SEPARATOR) + "halo-backup-markdown" + FILE_SEPARATOR; + private String backupMarkdownDir = + ensureSuffix(TEMP_DIR, FILE_SEPARATOR) + "halo-backup-markdown" + FILE_SEPARATOR; /** * Halo data export directory. */ - private String dataExportDir = ensureSuffix(TEMP_DIR, FILE_SEPARATOR) + "halo-data-export" + FILE_SEPARATOR; + private String dataExportDir = + ensureSuffix(TEMP_DIR, FILE_SEPARATOR) + "halo-data-export" + FILE_SEPARATOR; /** * Upload prefix. diff --git a/src/main/java/run/halo/app/controller/admin/api/AdminController.java b/src/main/java/run/halo/app/controller/admin/api/AdminController.java index 893a2ebbb3..974e93cf06 100644 --- a/src/main/java/run/halo/app/controller/admin/api/AdminController.java +++ b/src/main/java/run/halo/app/controller/admin/api/AdminController.java @@ -1,9 +1,17 @@ package run.halo.app.controller.admin.api; import io.swagger.annotations.ApiOperation; +import javax.validation.Valid; import lombok.extern.slf4j.Slf4j; import org.springframework.http.HttpStatus; -import org.springframework.web.bind.annotation.*; +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 run.halo.app.annotation.DisableOnCondition; import run.halo.app.cache.lock.CacheLock; import run.halo.app.model.dto.EnvironmentDTO; @@ -19,8 +27,6 @@ import run.halo.app.service.AdminService; import run.halo.app.service.OptionService; -import javax.validation.Valid; - /** * Admin controller. * @@ -45,7 +51,8 @@ public AdminController(AdminService adminService, OptionService optionService) { @GetMapping(value = "/is_installed") @ApiOperation("Checks Installation status") public boolean isInstall() { - return optionService.getByPropertyOrDefault(PrimaryProperties.IS_INSTALLED, Boolean.class, false); + return optionService + .getByPropertyOrDefault(PrimaryProperties.IS_INSTALLED, Boolean.class, false); } @PostMapping("login/precheck") diff --git a/src/main/java/run/halo/app/controller/admin/api/AttachmentController.java b/src/main/java/run/halo/app/controller/admin/api/AttachmentController.java index 3fe9ca7ba0..a32ef67509 100644 --- a/src/main/java/run/halo/app/controller/admin/api/AttachmentController.java +++ b/src/main/java/run/halo/app/controller/admin/api/AttachmentController.java @@ -1,11 +1,24 @@ package run.halo.app.controller.admin.api; +import static org.springframework.data.domain.Sort.Direction.DESC; + import io.swagger.annotations.ApiOperation; +import java.util.LinkedList; +import java.util.List; +import javax.validation.Valid; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.web.PageableDefault; import org.springframework.http.MediaType; -import org.springframework.web.bind.annotation.*; +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.RequestPart; +import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import run.halo.app.model.dto.AttachmentDTO; import run.halo.app.model.entity.Attachment; @@ -14,12 +27,6 @@ import run.halo.app.model.params.AttachmentQuery; import run.halo.app.service.AttachmentService; -import javax.validation.Valid; -import java.util.LinkedList; -import java.util.List; - -import static org.springframework.data.domain.Sort.Direction.DESC; - /** * Attachment controller. * @@ -37,8 +44,9 @@ public AttachmentController(AttachmentService attachmentService) { } @GetMapping - public Page pageBy(@PageableDefault(sort = "createTime", direction = DESC) Pageable pageable, - AttachmentQuery attachmentQuery) { + public Page pageBy( + @PageableDefault(sort = "createTime", direction = DESC) Pageable pageable, + AttachmentQuery attachmentQuery) { return attachmentService.pageDtosBy(pageable, attachmentQuery); } @@ -52,7 +60,7 @@ public AttachmentDTO getBy(@PathVariable("id") Integer id) { @PutMapping("{attachmentId:\\d+}") @ApiOperation("Updates a attachment") public AttachmentDTO updateBy(@PathVariable("attachmentId") Integer attachmentId, - @RequestBody @Valid AttachmentParam attachmentParam) { + @RequestBody @Valid AttachmentParam attachmentParam) { Attachment attachment = attachmentService.getById(attachmentId); attachmentParam.update(attachment); return new AttachmentDTO().convertFrom(attachmentService.update(attachment)); diff --git a/src/main/java/run/halo/app/controller/admin/api/BackupController.java b/src/main/java/run/halo/app/controller/admin/api/BackupController.java index 87b15492f3..7e0321affb 100644 --- a/src/main/java/run/halo/app/controller/admin/api/BackupController.java +++ b/src/main/java/run/halo/app/controller/admin/api/BackupController.java @@ -1,12 +1,23 @@ package run.halo.app.controller.admin.api; import io.swagger.annotations.ApiOperation; +import java.io.IOException; +import java.util.List; +import javax.servlet.http.HttpServletRequest; import lombok.extern.slf4j.Slf4j; import org.springframework.core.io.Resource; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.*; +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.RequestParam; +import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import run.halo.app.annotation.DisableOnCondition; import run.halo.app.config.properties.HaloProperties; @@ -15,10 +26,6 @@ import run.halo.app.model.params.PostMarkdownParam; import run.halo.app.service.BackupService; -import javax.servlet.http.HttpServletRequest; -import java.io.IOException; -import java.util.List; - /** * Backup controller * @@ -57,25 +64,29 @@ public List listBackups() { @GetMapping("work-dir/{fileName:.+}") @ApiOperation("Downloads a work directory backup file") @DisableOnCondition - public ResponseEntity downloadBackup(@PathVariable("fileName") String fileName, HttpServletRequest request) { + public ResponseEntity downloadBackup(@PathVariable("fileName") String fileName, + HttpServletRequest request) { log.info("Try to download backup file: [{}]", fileName); // Load file as resource - Resource backupResource = backupService.loadFileAsResource(haloProperties.getBackupDir(), fileName); + Resource backupResource = + backupService.loadFileAsResource(haloProperties.getBackupDir(), fileName); String contentType = MediaType.APPLICATION_OCTET_STREAM_VALUE; // Try to determine file's content type try { - contentType = request.getServletContext().getMimeType(backupResource.getFile().getAbsolutePath()); + contentType = + request.getServletContext().getMimeType(backupResource.getFile().getAbsolutePath()); } catch (IOException e) { log.warn("Could not determine file type", e); // Ignore this error } return ResponseEntity.ok() - .contentType(MediaType.parseMediaType(contentType)) - .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + backupResource.getFilename() + "\"") - .body(backupResource); + .contentType(MediaType.parseMediaType(contentType)) + .header(HttpHeaders.CONTENT_DISPOSITION, + "attachment; filename=\"" + backupResource.getFilename() + "\"") + .body(backupResource); } @DeleteMapping("work-dir") @@ -87,7 +98,8 @@ public void deleteBackup(@RequestParam("filename") String filename) { @PostMapping("markdown/import") @ApiOperation("Imports markdown") - public BasePostDetailDTO backupMarkdowns(@RequestPart("file") MultipartFile file) throws IOException { + public BasePostDetailDTO backupMarkdowns(@RequestPart("file") MultipartFile file) + throws IOException { return backupService.importMarkdown(file); } @@ -114,30 +126,35 @@ public void deleteExportedData(@RequestParam("filename") String filename) { @GetMapping("data/{fileName:.+}") @ApiOperation("Downloads a exported data") @DisableOnCondition - public ResponseEntity downloadExportedData(@PathVariable("fileName") String fileName, HttpServletRequest request) { + public ResponseEntity downloadExportedData(@PathVariable("fileName") String fileName, + HttpServletRequest request) { log.info("Try to download exported data file: [{}]", fileName); // Load exported data as resource - Resource exportDataResource = backupService.loadFileAsResource(haloProperties.getDataExportDir(), fileName); + Resource exportDataResource = + backupService.loadFileAsResource(haloProperties.getDataExportDir(), fileName); String contentType = MediaType.APPLICATION_OCTET_STREAM_VALUE; // Try to determine file's content type try { - contentType = request.getServletContext().getMimeType(exportDataResource.getFile().getAbsolutePath()); + contentType = request.getServletContext() + .getMimeType(exportDataResource.getFile().getAbsolutePath()); } catch (IOException e) { log.warn("Could not determine file type", e); } return ResponseEntity.ok() - .contentType(MediaType.parseMediaType(contentType)) - .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + exportDataResource.getFilename() + "\"") - .body(exportDataResource); + .contentType(MediaType.parseMediaType(contentType)) + .header(HttpHeaders.CONTENT_DISPOSITION, + "attachment; filename=\"" + exportDataResource.getFilename() + "\"") + .body(exportDataResource); } @PostMapping("markdown/export") @ApiOperation("Exports markdowns") @DisableOnCondition - public BackupDTO exportMarkdowns(@RequestBody PostMarkdownParam postMarkdownParam) throws IOException { + public BackupDTO exportMarkdowns(@RequestBody PostMarkdownParam postMarkdownParam) + throws IOException { return backupService.exportMarkdowns(postMarkdownParam); } @@ -157,25 +174,29 @@ public void deleteMarkdown(@RequestParam("filename") String filename) { @GetMapping("markdown/export/{fileName:.+}") @ApiOperation("Downloads a work markdown backup file") @DisableOnCondition - public ResponseEntity downloadMarkdown(@PathVariable("fileName") String fileName, HttpServletRequest request) { + public ResponseEntity downloadMarkdown(@PathVariable("fileName") String fileName, + HttpServletRequest request) { log.info("Try to download markdown backup file: [{}]", fileName); // Load file as resource - Resource backupResource = backupService.loadFileAsResource(haloProperties.getBackupMarkdownDir(), fileName); + Resource backupResource = + backupService.loadFileAsResource(haloProperties.getBackupMarkdownDir(), fileName); String contentType = MediaType.APPLICATION_OCTET_STREAM_VALUE; // Try to determine file's content type try { - contentType = request.getServletContext().getMimeType(backupResource.getFile().getAbsolutePath()); + contentType = + request.getServletContext().getMimeType(backupResource.getFile().getAbsolutePath()); } catch (IOException e) { log.warn("Could not determine file type", e); // Ignore this error } return ResponseEntity.ok() - .contentType(MediaType.parseMediaType(contentType)) - .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + backupResource.getFilename() + "\"") - .body(backupResource); + .contentType(MediaType.parseMediaType(contentType)) + .header(HttpHeaders.CONTENT_DISPOSITION, + "attachment; filename=\"" + backupResource.getFilename() + "\"") + .body(backupResource); } diff --git a/src/main/java/run/halo/app/controller/admin/api/CategoryController.java b/src/main/java/run/halo/app/controller/admin/api/CategoryController.java index 568b743f1e..01dbcdc1bd 100644 --- a/src/main/java/run/halo/app/controller/admin/api/CategoryController.java +++ b/src/main/java/run/halo/app/controller/admin/api/CategoryController.java @@ -1,9 +1,22 @@ package run.halo.app.controller.admin.api; +import static org.springframework.data.domain.Sort.Direction.ASC; +import static org.springframework.data.domain.Sort.Direction.DESC; + import io.swagger.annotations.ApiOperation; +import java.util.List; +import javax.validation.Valid; import org.springframework.data.domain.Sort; import org.springframework.data.web.SortDefault; -import org.springframework.web.bind.annotation.*; +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 run.halo.app.model.dto.CategoryDTO; import run.halo.app.model.entity.Category; import run.halo.app.model.params.CategoryParam; @@ -11,12 +24,6 @@ import run.halo.app.service.CategoryService; import run.halo.app.service.PostCategoryService; -import javax.validation.Valid; -import java.util.List; - -import static org.springframework.data.domain.Sort.Direction.ASC; -import static org.springframework.data.domain.Sort.Direction.DESC; - /** * Category controller. * @@ -32,7 +39,7 @@ public class CategoryController { private final PostCategoryService postCategoryService; public CategoryController(CategoryService categoryService, - PostCategoryService postCategoryService) { + PostCategoryService postCategoryService) { this.categoryService = categoryService; this.postCategoryService = postCategoryService; } @@ -46,8 +53,8 @@ public CategoryDTO getBy(@PathVariable("categoryId") Integer categoryId) { @GetMapping @ApiOperation("Lists all categories") public List listAll( - @SortDefault(sort = "createTime", direction = DESC) Sort sort, - @RequestParam(name = "more", required = false, defaultValue = "false") boolean more) { + @SortDefault(sort = "createTime", direction = DESC) Sort sort, + @RequestParam(name = "more", required = false, defaultValue = "false") boolean more) { if (more) { return postCategoryService.listCategoryWithPostCountDto(sort); } @@ -74,7 +81,7 @@ public CategoryDTO createBy(@RequestBody @Valid CategoryParam categoryParam) { @PutMapping("{categoryId:\\d+}") @ApiOperation("Updates category") public CategoryDTO updateBy(@PathVariable("categoryId") Integer categoryId, - @RequestBody @Valid CategoryParam categoryParam) { + @RequestBody @Valid CategoryParam categoryParam) { Category categoryToUpdate = categoryService.getById(categoryId); categoryParam.update(categoryToUpdate); return categoryService.convertTo(categoryService.update(categoryToUpdate)); diff --git a/src/main/java/run/halo/app/controller/admin/api/InstallController.java b/src/main/java/run/halo/app/controller/admin/api/InstallController.java index efada75ce9..b876a99205 100644 --- a/src/main/java/run/halo/app/controller/admin/api/InstallController.java +++ b/src/main/java/run/halo/app/controller/admin/api/InstallController.java @@ -2,6 +2,11 @@ import cn.hutool.crypto.SecureUtil; import io.swagger.annotations.ApiOperation; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.context.ApplicationEventPublisher; @@ -19,7 +24,11 @@ import run.halo.app.model.entity.User; import run.halo.app.model.enums.LogType; import run.halo.app.model.enums.PostStatus; -import run.halo.app.model.params.*; +import run.halo.app.model.params.CategoryParam; +import run.halo.app.model.params.InstallParam; +import run.halo.app.model.params.MenuParam; +import run.halo.app.model.params.PostParam; +import run.halo.app.model.params.SheetParam; import run.halo.app.model.properties.BlogProperties; import run.halo.app.model.properties.OtherProperties; import run.halo.app.model.properties.PrimaryProperties; @@ -27,11 +36,15 @@ import run.halo.app.model.support.BaseResponse; import run.halo.app.model.support.CreateCheck; import run.halo.app.model.vo.PostDetailVO; -import run.halo.app.service.*; +import run.halo.app.service.CategoryService; +import run.halo.app.service.MenuService; +import run.halo.app.service.OptionService; +import run.halo.app.service.PostCommentService; +import run.halo.app.service.PostService; +import run.halo.app.service.SheetService; +import run.halo.app.service.UserService; import run.halo.app.utils.ValidationUtils; -import java.util.*; - /** * Installation controller. * @@ -60,13 +73,13 @@ public class InstallController { private final ApplicationEventPublisher eventPublisher; public InstallController(UserService userService, - CategoryService categoryService, - PostService postService, - SheetService sheetService, - PostCommentService postCommentService, - OptionService optionService, - MenuService menuService, - ApplicationEventPublisher eventPublisher) { + CategoryService categoryService, + PostService postService, + SheetService sheetService, + PostCommentService postCommentService, + OptionService optionService, + MenuService menuService, + ApplicationEventPublisher eventPublisher) { this.userService = userService; this.categoryService = categoryService; this.postService = postService; @@ -86,7 +99,8 @@ public BaseResponse installBlog(@RequestBody InstallParam installParam) ValidationUtils.validate(installParam, CreateCheck.class); // Check is installed - boolean isInstalled = optionService.getByPropertyOrDefault(PrimaryProperties.IS_INSTALLED, Boolean.class, false); + boolean isInstalled = optionService + .getByPropertyOrDefault(PrimaryProperties.IS_INSTALLED, Boolean.class, false); if (isInstalled) { throw new BadRequestException("该博客已初始化,不能再次安装!"); @@ -114,7 +128,7 @@ public BaseResponse installBlog(@RequestBody InstallParam installParam) createDefaultMenu(); eventPublisher.publishEvent( - new LogEvent(this, user.getId().toString(), LogType.BLOG_INITIALIZED, "博客已成功初始化") + new LogEvent(this, user.getId().toString(), LogType.BLOG_INITIALIZED, "博客已成功初始化") ); return BaseResponse.ok("安装完成!"); @@ -171,7 +185,10 @@ private void createDefaultComment(@Nullable PostDetailVO post) { PostComment comment = new PostComment(); comment.setAuthor("Halo"); comment.setAuthorUrl("https://halo.run"); - comment.setContent("欢迎使用 Halo,这是你的第一条评论,头像来自 [Gravatar](https://cn.gravatar.com),你也可以通过注册 [Gravatar](https://cn.gravatar.com) 来显示自己的头像。"); + comment.setContent( + "欢迎使用 Halo,这是你的第一条评论,头像来自 [Gravatar](https://cn.gravatar.com)," + + "你也可以通过注册 [Gravatar]" + + "(https://cn.gravatar.com) 来显示自己的头像。"); comment.setEmail("hi@halo.run"); comment.setPostId(post.getId()); postCommentService.create(comment); @@ -190,28 +207,29 @@ private PostDetailVO createDefaultPostIfAbsent(@Nullable Category category) { postParam.setSlug("hello-halo"); postParam.setTitle("Hello Halo"); postParam.setStatus(PostStatus.PUBLISHED); - postParam.setOriginalContent("## Hello Halo\n" + - "\n" + - "如果你看到了这一篇文章,那么证明你已经安装成功了,感谢使用 [Halo](https://halo.run) 进行创作,希望能够使用愉快。\n" + - "\n" + - "## 相关链接\n" + - "\n" + - "- 官网:[https://halo.run](https://halo.run)\n" + - "- 社区:[https://bbs.halo.run](https://bbs.halo.run)\n" + - "- 主题仓库:[https://halo.run/p/themes.html](https://halo.run/p/themes.html)\n" + - "- 开源地址:[https://github.com/halo-dev/halo](https://github.com/halo-dev/halo)\n" + - "\n" + - "在使用过程中,有任何问题都可以通过以上链接找寻答案,或者联系我们。\n" + - "\n" + - "> 这是一篇自动生成的文章,请删除这篇文章之后开始你的创作吧!\n" + - "\n"); + postParam.setOriginalContent("## Hello Halo\n" + + "\n" + + "如果你看到了这一篇文章,那么证明你已经安装成功了,感谢使用 [Halo](https://halo.run) 进行创作,希望能够使用愉快。\n" + + "\n" + + "## 相关链接\n" + + "\n" + + "- 官网:[https://halo.run](https://halo.run)\n" + + "- 社区:[https://bbs.halo.run](https://bbs.halo.run)\n" + + "- 主题仓库:[https://halo.run/p/themes.html](https://halo.run/p/themes.html)\n" + + "- 开源地址:[https://github.com/halo-dev/halo](https://github.com/halo-dev/halo)\n" + + "\n" + + "在使用过程中,有任何问题都可以通过以上链接找寻答案,或者联系我们。\n" + + "\n" + + "> 这是一篇自动生成的文章,请删除这篇文章之后开始你的创作吧!\n" + + "\n"); Set categoryIds = new HashSet<>(); if (category != null) { categoryIds.add(category.getId()); postParam.setCategoryIds(categoryIds); } - return postService.createBy(postParam.convertTo(), Collections.emptySet(), categoryIds, false); + return postService + .createBy(postParam.convertTo(), Collections.emptySet(), categoryIds, false); } @Nullable @@ -225,11 +243,12 @@ private void createDefaultSheet() { sheetParam.setSlug("about"); sheetParam.setTitle("关于页面"); sheetParam.setStatus(PostStatus.PUBLISHED); - sheetParam.setOriginalContent("## 关于页面\n" + - "\n" + - "这是一个自定义页面,你可以在后台的 `页面` -> `所有页面` -> `自定义页面` 找到它,你可以用于新建关于页面、留言板页面等等。发挥你自己的想象力!\n" + - "\n" + - "> 这是一篇自动生成的页面,你可以在后台删除它。"); + sheetParam.setOriginalContent("## 关于页面\n" + + "\n" + + "这是一个自定义页面,你可以在后台的 `页面` -> `所有页面` -> `自定义页面` 找到它," + + "你可以用于新建关于页面、留言板页面等等。发挥你自己的想象力!\n" + + "\n" + + "> 这是一篇自动生成的页面,你可以在后台删除它。"); sheetService.createBy(sheetParam.convertTo(), false); } @@ -258,8 +277,9 @@ private User createUser(InstallParam installParam) { // Update user return userService.update(user); }).orElseGet(() -> { - String gravatar = "//cn.gravatar.com/avatar/" + SecureUtil.md5(installParam.getEmail()) + - "?s=256&d=mm"; + String gravatar = + "//cn.gravatar.com/avatar/" + SecureUtil.md5(installParam.getEmail()) + + "?s=256&d=mm"; installParam.setAvatar(gravatar); return userService.createBy(installParam); }); @@ -271,15 +291,20 @@ private void initSettings(InstallParam installParam) { properties.put(PrimaryProperties.IS_INSTALLED, Boolean.TRUE.toString()); properties.put(BlogProperties.BLOG_LOCALE, installParam.getLocale()); properties.put(BlogProperties.BLOG_TITLE, installParam.getTitle()); - properties.put(BlogProperties.BLOG_URL, StringUtils.isBlank(installParam.getUrl()) ? optionService.getBlogBaseUrl() : installParam.getUrl()); + properties.put(BlogProperties.BLOG_URL, + StringUtils.isBlank(installParam.getUrl()) ? optionService.getBlogBaseUrl() : + installParam.getUrl()); - Long birthday = optionService.getByPropertyOrDefault(PrimaryProperties.BIRTHDAY, Long.class, 0L); + Long birthday = + optionService.getByPropertyOrDefault(PrimaryProperties.BIRTHDAY, Long.class, 0L); if (birthday.equals(0L)) { properties.put(PrimaryProperties.BIRTHDAY, String.valueOf(System.currentTimeMillis())); } - Boolean globalAbsolutePathEnabled = optionService.getByPropertyOrDefault(OtherProperties.GLOBAL_ABSOLUTE_PATH_ENABLED, Boolean.class, null); + Boolean globalAbsolutePathEnabled = optionService + .getByPropertyOrDefault(OtherProperties.GLOBAL_ABSOLUTE_PATH_ENABLED, Boolean.class, + null); if (globalAbsolutePathEnabled == null) { properties.put(OtherProperties.GLOBAL_ABSOLUTE_PATH_ENABLED, Boolean.FALSE.toString()); diff --git a/src/main/java/run/halo/app/controller/admin/api/JournalCommentController.java b/src/main/java/run/halo/app/controller/admin/api/JournalCommentController.java index 1ee2225630..1207eee59d 100644 --- a/src/main/java/run/halo/app/controller/admin/api/JournalCommentController.java +++ b/src/main/java/run/halo/app/controller/admin/api/JournalCommentController.java @@ -1,13 +1,24 @@ package run.halo.app.controller.admin.api; +import static org.springframework.data.domain.Sort.Direction.DESC; + import io.swagger.annotations.ApiOperation; +import java.util.List; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.data.web.PageableDefault; import org.springframework.data.web.SortDefault; -import org.springframework.web.bind.annotation.*; +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 run.halo.app.model.dto.BaseCommentDTO; import run.halo.app.model.entity.JournalComment; import run.halo.app.model.enums.CommentStatus; @@ -19,10 +30,6 @@ import run.halo.app.service.JournalCommentService; import run.halo.app.service.OptionService; -import java.util.List; - -import static org.springframework.data.domain.Sort.Direction.DESC; - /** * Journal comment controller. * @@ -38,42 +45,48 @@ public class JournalCommentController { private final OptionService optionService; public JournalCommentController(JournalCommentService journalCommentService, - OptionService optionService) { + OptionService optionService) { this.journalCommentService = journalCommentService; this.optionService = optionService; } @GetMapping @ApiOperation("Lists journal comments") - public Page pageBy(@PageableDefault(sort = "createTime", direction = DESC) Pageable pageable, - CommentQuery commentQuery) { - Page journalCommentPage = journalCommentService.pageBy(commentQuery, pageable); + public Page pageBy( + @PageableDefault(sort = "createTime", direction = DESC) Pageable pageable, + CommentQuery commentQuery) { + Page journalCommentPage = + journalCommentService.pageBy(commentQuery, pageable); return journalCommentService.convertToWithJournalVo(journalCommentPage); } @GetMapping("latest") @ApiOperation("Lists latest journal comments") - public List listLatest(@RequestParam(name = "top", defaultValue = "10") int top, - @RequestParam(name = "status", required = false) CommentStatus status) { - List latestComments = journalCommentService.pageLatest(top, status).getContent(); + public List listLatest( + @RequestParam(name = "top", defaultValue = "10") int top, + @RequestParam(name = "status", required = false) CommentStatus status) { + List latestComments = + journalCommentService.pageLatest(top, status).getContent(); return journalCommentService.convertToWithJournalVo(latestComments); } @GetMapping("{journalId:\\d+}/tree_view") @ApiOperation("Lists comments with tree view") public Page listCommentTree(@PathVariable("journalId") Integer journalId, - @RequestParam(name = "page", required = false, defaultValue = "0") int page, - @SortDefault(sort = "createTime", direction = DESC) Sort sort) { - return journalCommentService.pageVosAllBy(journalId, PageRequest.of(page, optionService.getCommentPageSize(), sort)); + @RequestParam(name = "page", required = false, defaultValue = "0") int page, + @SortDefault(sort = "createTime", direction = DESC) Sort sort) { + return journalCommentService.pageVosAllBy(journalId, + PageRequest.of(page, optionService.getCommentPageSize(), sort)); } @GetMapping("{journalId:\\d+}/list_view") @ApiOperation("Lists comment with list view") public Page listComments(@PathVariable("journalId") Integer journalId, - @RequestParam(name = "page", required = false, defaultValue = "0") int page, - @SortDefault(sort = "createTime", direction = DESC) Sort sort) { - return journalCommentService.pageWithParentVoBy(journalId, PageRequest.of(page, optionService.getCommentPageSize(), sort)); + @RequestParam(name = "page", required = false, defaultValue = "0") int page, + @SortDefault(sort = "createTime", direction = DESC) Sort sort) { + return journalCommentService.pageWithParentVoBy(journalId, + PageRequest.of(page, optionService.getCommentPageSize(), sort)); } @PostMapping @@ -86,9 +99,10 @@ public BaseCommentDTO createCommentBy(@RequestBody JournalCommentParam journalCo @PutMapping("{commentId:\\d+}/status/{status}") @ApiOperation("Updates comment status") public BaseCommentDTO updateStatusBy(@PathVariable("commentId") Long commentId, - @PathVariable("status") CommentStatus status) { + @PathVariable("status") CommentStatus status) { // Update comment status - JournalComment updatedJournalComment = journalCommentService.updateStatus(commentId, status); + JournalComment updatedJournalComment = + journalCommentService.updateStatus(commentId, status); return journalCommentService.convertTo(updatedJournalComment); } diff --git a/src/main/java/run/halo/app/controller/admin/api/JournalController.java b/src/main/java/run/halo/app/controller/admin/api/JournalController.java index 38dbd5df62..5238a0d356 100644 --- a/src/main/java/run/halo/app/controller/admin/api/JournalController.java +++ b/src/main/java/run/halo/app/controller/admin/api/JournalController.java @@ -1,10 +1,22 @@ package run.halo.app.controller.admin.api; +import static org.springframework.data.domain.Sort.Direction.DESC; + import io.swagger.annotations.ApiOperation; +import java.util.List; +import javax.validation.Valid; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.web.PageableDefault; -import org.springframework.web.bind.annotation.*; +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 run.halo.app.model.dto.JournalDTO; import run.halo.app.model.dto.JournalWithCmtCountDTO; import run.halo.app.model.entity.Journal; @@ -12,11 +24,6 @@ import run.halo.app.model.params.JournalQuery; import run.halo.app.service.JournalService; -import javax.validation.Valid; -import java.util.List; - -import static org.springframework.data.domain.Sort.Direction.DESC; - /** * Journal controller. * @@ -36,15 +43,17 @@ public JournalController(JournalService journalService) { @GetMapping @ApiOperation("Lists journals") - public Page pageBy(@PageableDefault(sort = "createTime", direction = DESC) Pageable pageable, - JournalQuery journalQuery) { + public Page pageBy( + @PageableDefault(sort = "createTime", direction = DESC) Pageable pageable, + JournalQuery journalQuery) { Page journalPage = journalService.pageBy(journalQuery, pageable); return journalService.convertToCmtCountDto(journalPage); } @GetMapping("latest") @ApiOperation("Gets latest journals") - public List pageLatest(@RequestParam(name = "top", defaultValue = "10") int top) { + public List pageLatest( + @RequestParam(name = "top", defaultValue = "10") int top) { List journals = journalService.pageLatest(top).getContent(); return journalService.convertToCmtCountDto(journals); } @@ -59,7 +68,7 @@ public JournalDTO createBy(@RequestBody @Valid JournalParam journalParam) { @PutMapping("{id:\\d+}") @ApiOperation("Updates a Journal") public JournalDTO updateBy(@PathVariable("id") Integer id, - @RequestBody @Valid JournalParam journalParam) { + @RequestBody @Valid JournalParam journalParam) { Journal journal = journalService.getById(id); journalParam.update(journal); Journal updatedJournal = journalService.updateBy(journal); diff --git a/src/main/java/run/halo/app/controller/admin/api/LinkController.java b/src/main/java/run/halo/app/controller/admin/api/LinkController.java index a9f6bff25e..2ae82277d8 100644 --- a/src/main/java/run/halo/app/controller/admin/api/LinkController.java +++ b/src/main/java/run/halo/app/controller/admin/api/LinkController.java @@ -1,20 +1,26 @@ package run.halo.app.controller.admin.api; +import static org.springframework.data.domain.Sort.Direction.ASC; +import static org.springframework.data.domain.Sort.Direction.DESC; + import io.swagger.annotations.ApiOperation; +import java.util.List; +import javax.validation.Valid; import org.springframework.data.domain.Sort; import org.springframework.data.web.SortDefault; -import org.springframework.web.bind.annotation.*; +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 run.halo.app.model.dto.LinkDTO; import run.halo.app.model.entity.Link; import run.halo.app.model.params.LinkParam; import run.halo.app.service.LinkService; -import javax.validation.Valid; -import java.util.List; - -import static org.springframework.data.domain.Sort.Direction.ASC; -import static org.springframework.data.domain.Sort.Direction.DESC; - /** * Link Controller * @@ -53,7 +59,7 @@ public LinkDTO createBy(@RequestBody @Valid LinkParam linkParam) { @PutMapping("{id:\\d+}") @ApiOperation("Updates a link") public LinkDTO updateBy(@PathVariable("id") Integer id, - @RequestBody @Valid LinkParam linkParam) { + @RequestBody @Valid LinkParam linkParam) { Link link = linkService.updateBy(id, linkParam); return new LinkDTO().convertFrom(link); } diff --git a/src/main/java/run/halo/app/controller/admin/api/LogController.java b/src/main/java/run/halo/app/controller/admin/api/LogController.java index 4da971886f..37b702d2cc 100644 --- a/src/main/java/run/halo/app/controller/admin/api/LogController.java +++ b/src/main/java/run/halo/app/controller/admin/api/LogController.java @@ -1,6 +1,9 @@ package run.halo.app.controller.admin.api; +import static org.springframework.data.domain.Sort.Direction.DESC; + import io.swagger.annotations.ApiOperation; +import java.util.List; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.web.PageableDefault; @@ -12,10 +15,6 @@ import run.halo.app.model.entity.Log; import run.halo.app.service.LogService; -import java.util.List; - -import static org.springframework.data.domain.Sort.Direction.DESC; - /** * Log controller. * @@ -40,7 +39,8 @@ public List pageLatest(@RequestParam(name = "top", defaultValue = "10") @GetMapping @ApiOperation("Lists logs") - public Page pageBy(@PageableDefault(sort = "createTime", direction = DESC) Pageable pageable) { + public Page pageBy( + @PageableDefault(sort = "createTime", direction = DESC) Pageable pageable) { Page logPage = logService.listAll(pageable); return logPage.map(log -> new LogDTO().convertFrom(log)); } diff --git a/src/main/java/run/halo/app/controller/admin/api/MailController.java b/src/main/java/run/halo/app/controller/admin/api/MailController.java index 93a82f108a..6d11625fae 100644 --- a/src/main/java/run/halo/app/controller/admin/api/MailController.java +++ b/src/main/java/run/halo/app/controller/admin/api/MailController.java @@ -1,6 +1,7 @@ package run.halo.app.controller.admin.api; import io.swagger.annotations.ApiOperation; +import javax.validation.Valid; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; @@ -10,8 +11,6 @@ import run.halo.app.model.params.MailParam; import run.halo.app.model.support.BaseResponse; -import javax.validation.Valid; - /** * Mail controller. * diff --git a/src/main/java/run/halo/app/controller/admin/api/MenuController.java b/src/main/java/run/halo/app/controller/admin/api/MenuController.java index 204a9e42cb..716d7c8834 100644 --- a/src/main/java/run/halo/app/controller/admin/api/MenuController.java +++ b/src/main/java/run/halo/app/controller/admin/api/MenuController.java @@ -1,9 +1,23 @@ package run.halo.app.controller.admin.api; +import static org.springframework.data.domain.Sort.Direction.ASC; +import static org.springframework.data.domain.Sort.Direction.DESC; + import io.swagger.annotations.ApiOperation; +import java.util.List; +import java.util.stream.Collectors; +import javax.validation.Valid; import org.springframework.data.domain.Sort; import org.springframework.data.web.SortDefault; -import org.springframework.web.bind.annotation.*; +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 run.halo.app.model.dto.MenuDTO; import run.halo.app.model.dto.base.InputConverter; import run.halo.app.model.entity.Menu; @@ -11,13 +25,6 @@ import run.halo.app.model.vo.MenuVO; import run.halo.app.service.MenuService; -import javax.validation.Valid; -import java.util.List; -import java.util.stream.Collectors; - -import static org.springframework.data.domain.Sort.Direction.ASC; -import static org.springframework.data.domain.Sort.Direction.DESC; - /** * Menu controller. * @@ -49,7 +56,9 @@ public List listAsTree(@SortDefault(sort = "team", direction = DESC) Sor @GetMapping("team/tree_view") @ApiOperation("Lists menus as tree by team") - public List listDefaultsAsTreeByTeam(@SortDefault(sort = "priority", direction = ASC) Sort sort, @RequestParam(name = "team") String team) { + public List listDefaultsAsTreeByTeam( + @SortDefault(sort = "priority", direction = ASC) Sort sort, + @RequestParam(name = "team") String team) { return menuService.listByTeamAsTree(team, sort); } @@ -68,17 +77,18 @@ public MenuDTO createBy(@RequestBody @Valid MenuParam menuParam) { @PostMapping("/batch") public List createBatchBy(@RequestBody @Valid List menuParams) { List menus = menuParams - .stream() - .map(InputConverter::convertTo) - .collect(Collectors.toList()); + .stream() + .map(InputConverter::convertTo) + .collect(Collectors.toList()); return menuService.createInBatch(menus).stream() - .map(menu -> (MenuDTO) new MenuDTO().convertFrom(menu)) - .collect(Collectors.toList()); + .map(menu -> (MenuDTO) new MenuDTO().convertFrom(menu)) + .collect(Collectors.toList()); } @PutMapping("{menuId:\\d+}") @ApiOperation("Updates a menu") - public MenuDTO updateBy(@PathVariable("menuId") Integer menuId, @RequestBody @Valid MenuParam menuParam) { + public MenuDTO updateBy(@PathVariable("menuId") Integer menuId, + @RequestBody @Valid MenuParam menuParam) { // Get the menu Menu menu = menuService.getById(menuId); @@ -92,12 +102,12 @@ public MenuDTO updateBy(@PathVariable("menuId") Integer menuId, @RequestBody @Va @PutMapping("/batch") public List updateBatchBy(@RequestBody @Valid List menuParams) { List menus = menuParams - .stream() - .map(InputConverter::convertTo) - .collect(Collectors.toList()); + .stream() + .map(InputConverter::convertTo) + .collect(Collectors.toList()); return menuService.updateInBatch(menus).stream() - .map(menu -> (MenuDTO) new MenuDTO().convertFrom(menu)) - .collect(Collectors.toList()); + .map(menu -> (MenuDTO) new MenuDTO().convertFrom(menu)) + .collect(Collectors.toList()); } @DeleteMapping("{menuId:\\d+}") @@ -118,8 +128,8 @@ public List deleteBatchBy(@RequestBody List menuIds) { List menus = menuService.listAllByIds(menuIds); menuService.removeInBatch(menuIds); return menus.stream() - .map(menu -> (MenuDTO) new MenuDTO().convertFrom(menu)) - .collect(Collectors.toList()); + .map(menu -> (MenuDTO) new MenuDTO().convertFrom(menu)) + .collect(Collectors.toList()); } @GetMapping("teams") diff --git a/src/main/java/run/halo/app/controller/admin/api/MigrateController.java b/src/main/java/run/halo/app/controller/admin/api/MigrateController.java index b1ab2233c3..b696d5d468 100644 --- a/src/main/java/run/halo/app/controller/admin/api/MigrateController.java +++ b/src/main/java/run/halo/app/controller/admin/api/MigrateController.java @@ -27,7 +27,7 @@ public class MigrateController { private final OptionService optionService; public MigrateController(MigrateService migrateService, - OptionService optionService) { + OptionService optionService) { this.migrateService = migrateService; this.optionService = optionService; } @@ -35,7 +35,8 @@ public MigrateController(MigrateService migrateService, @PostMapping("halo") @ApiOperation("Migrate from Halo") public void migrateHalo(@RequestPart("file") MultipartFile file) { - if (optionService.getByPropertyOrDefault(PrimaryProperties.IS_INSTALLED, Boolean.class, false)) { + if (optionService + .getByPropertyOrDefault(PrimaryProperties.IS_INSTALLED, Boolean.class, false)) { throw new BadRequestException("无法在博客初始化完成之后迁移数据"); } migrateService.migrate(file, MigrateType.HALO); diff --git a/src/main/java/run/halo/app/controller/admin/api/OptionController.java b/src/main/java/run/halo/app/controller/admin/api/OptionController.java index 7fc73c6118..4ca4985a63 100644 --- a/src/main/java/run/halo/app/controller/admin/api/OptionController.java +++ b/src/main/java/run/halo/app/controller/admin/api/OptionController.java @@ -1,10 +1,22 @@ package run.halo.app.controller.admin.api; +import static org.springframework.data.domain.Sort.Direction.DESC; + import io.swagger.annotations.ApiOperation; +import java.util.List; +import java.util.Map; +import javax.validation.Valid; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.web.PageableDefault; -import org.springframework.web.bind.annotation.*; +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 run.halo.app.annotation.DisableOnCondition; import run.halo.app.model.dto.OptionDTO; import run.halo.app.model.dto.OptionSimpleDTO; @@ -13,12 +25,6 @@ import run.halo.app.model.params.OptionQuery; import run.halo.app.service.OptionService; -import javax.validation.Valid; -import java.util.List; -import java.util.Map; - -import static org.springframework.data.domain.Sort.Direction.DESC; - /** * Option Controller. * @@ -63,8 +69,9 @@ public Map listAllWithMapView(@RequestBody List keys) { @GetMapping("list_view") @ApiOperation("Lists all options with list view") - public Page listAllWithListView(@PageableDefault(sort = "updateTime", direction = DESC) Pageable pageable, - OptionQuery optionQuery) { + public Page listAllWithListView( + @PageableDefault(sort = "updateTime", direction = DESC) Pageable pageable, + OptionQuery optionQuery) { return optionService.pageDtosBy(pageable, optionQuery); } @@ -86,7 +93,7 @@ public void createBy(@RequestBody @Valid OptionParam optionParam) { @ApiOperation("Updates option") @DisableOnCondition public void updateBy(@PathVariable("optionId") Integer optionId, - @RequestBody @Valid OptionParam optionParam) { + @RequestBody @Valid OptionParam optionParam) { optionService.update(optionId, optionParam); } diff --git a/src/main/java/run/halo/app/controller/admin/api/PhotoController.java b/src/main/java/run/halo/app/controller/admin/api/PhotoController.java index 3db87c63b1..cb8edb81b2 100644 --- a/src/main/java/run/halo/app/controller/admin/api/PhotoController.java +++ b/src/main/java/run/halo/app/controller/admin/api/PhotoController.java @@ -1,23 +1,29 @@ package run.halo.app.controller.admin.api; +import static org.springframework.data.domain.Sort.Direction.DESC; + import io.swagger.annotations.ApiOperation; +import java.util.List; +import javax.validation.Valid; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.data.web.PageableDefault; import org.springframework.data.web.SortDefault; -import org.springframework.web.bind.annotation.*; +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 run.halo.app.model.dto.PhotoDTO; import run.halo.app.model.entity.Photo; import run.halo.app.model.params.PhotoParam; import run.halo.app.model.params.PhotoQuery; import run.halo.app.service.PhotoService; -import javax.validation.Valid; -import java.util.List; - -import static org.springframework.data.domain.Sort.Direction.DESC; - /** * Photo controller * @@ -36,14 +42,16 @@ public PhotoController(PhotoService photoService) { @GetMapping(value = "latest") @ApiOperation("Lists latest photos") - public List listPhotos(@SortDefault(sort = "createTime", direction = Sort.Direction.DESC) Sort sort) { + public List listPhotos( + @SortDefault(sort = "createTime", direction = Sort.Direction.DESC) Sort sort) { return photoService.listDtos(sort); } @GetMapping @ApiOperation("Lists photos") - public Page pageBy(@PageableDefault(sort = "createTime", direction = DESC) Pageable pageable, - PhotoQuery photoQuery) { + public Page pageBy( + @PageableDefault(sort = "createTime", direction = DESC) Pageable pageable, + PhotoQuery photoQuery) { return photoService.pageDtosBy(pageable, photoQuery); } @@ -68,7 +76,7 @@ public PhotoDTO createBy(@Valid @RequestBody PhotoParam photoParam) { @PutMapping("{photoId:\\d+}") @ApiOperation("Updates a photo") public PhotoDTO updateBy(@PathVariable("photoId") Integer photoId, - @RequestBody @Valid PhotoParam photoParam) { + @RequestBody @Valid PhotoParam photoParam) { // Get the photo Photo photo = photoService.getById(photoId); diff --git a/src/main/java/run/halo/app/controller/admin/api/PostCommentController.java b/src/main/java/run/halo/app/controller/admin/api/PostCommentController.java index 1cc42bb27b..47713d99f6 100644 --- a/src/main/java/run/halo/app/controller/admin/api/PostCommentController.java +++ b/src/main/java/run/halo/app/controller/admin/api/PostCommentController.java @@ -1,13 +1,25 @@ package run.halo.app.controller.admin.api; +import static org.springframework.data.domain.Sort.Direction.DESC; + import io.swagger.annotations.ApiOperation; +import java.util.List; +import javax.validation.Valid; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.data.web.PageableDefault; import org.springframework.data.web.SortDefault; -import org.springframework.web.bind.annotation.*; +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 run.halo.app.model.dto.BaseCommentDTO; import run.halo.app.model.entity.PostComment; import run.halo.app.model.enums.CommentStatus; @@ -19,11 +31,6 @@ import run.halo.app.service.OptionService; import run.halo.app.service.PostCommentService; -import javax.validation.Valid; -import java.util.List; - -import static org.springframework.data.domain.Sort.Direction.DESC; - /** * Post comment controller. * @@ -40,23 +47,25 @@ public class PostCommentController { private final OptionService optionService; public PostCommentController(PostCommentService postCommentService, - OptionService optionService) { + OptionService optionService) { this.postCommentService = postCommentService; this.optionService = optionService; } @GetMapping @ApiOperation("Lists post comments") - public Page pageBy(@PageableDefault(sort = "createTime", direction = DESC) Pageable pageable, - CommentQuery commentQuery) { + public Page pageBy( + @PageableDefault(sort = "createTime", direction = DESC) Pageable pageable, + CommentQuery commentQuery) { Page commentPage = postCommentService.pageBy(commentQuery, pageable); return postCommentService.convertToWithPostVo(commentPage); } @GetMapping("latest") @ApiOperation("Pages post latest comments") - public List listLatest(@RequestParam(name = "top", defaultValue = "10") int top, - @RequestParam(name = "status", required = false) CommentStatus status) { + public List listLatest( + @RequestParam(name = "top", defaultValue = "10") int top, + @RequestParam(name = "status", required = false) CommentStatus status) { // Get latest comment List content = postCommentService.pageLatest(top, status).getContent(); @@ -67,17 +76,19 @@ public List listLatest(@RequestParam(name = "top", defaul @GetMapping("{postId:\\d+}/tree_view") @ApiOperation("Lists post comments with tree view") public Page listCommentTree(@PathVariable("postId") Integer postId, - @RequestParam(name = "page", required = false, defaultValue = "0") int page, - @SortDefault(sort = "createTime", direction = DESC) Sort sort) { - return postCommentService.pageVosAllBy(postId, PageRequest.of(page, optionService.getCommentPageSize(), sort)); + @RequestParam(name = "page", required = false, defaultValue = "0") int page, + @SortDefault(sort = "createTime", direction = DESC) Sort sort) { + return postCommentService + .pageVosAllBy(postId, PageRequest.of(page, optionService.getCommentPageSize(), sort)); } @GetMapping("{postId:\\d+}/list_view") @ApiOperation("Lists post comment with list view") public Page listComments(@PathVariable("postId") Integer postId, - @RequestParam(name = "page", required = false, defaultValue = "0") int page, - @SortDefault(sort = "createTime", direction = DESC) Sort sort) { - return postCommentService.pageWithParentVoBy(postId, PageRequest.of(page, optionService.getCommentPageSize(), sort)); + @RequestParam(name = "page", required = false, defaultValue = "0") int page, + @SortDefault(sort = "createTime", direction = DESC) Sort sort) { + return postCommentService.pageWithParentVoBy(postId, + PageRequest.of(page, optionService.getCommentPageSize(), sort)); } @PostMapping @@ -90,7 +101,7 @@ public BaseCommentDTO createBy(@RequestBody PostCommentParam postCommentParam) { @PutMapping("{commentId:\\d+}/status/{status}") @ApiOperation("Updates post comment status") public BaseCommentDTO updateStatusBy(@PathVariable("commentId") Long commentId, - @PathVariable("status") CommentStatus status) { + @PathVariable("status") CommentStatus status) { // Update comment status PostComment updatedPostComment = postCommentService.updateStatus(commentId, status); return postCommentService.convertTo(updatedPostComment); @@ -98,8 +109,9 @@ public BaseCommentDTO updateStatusBy(@PathVariable("commentId") Long commentId, @PutMapping("status/{status}") @ApiOperation("Updates post comment status in batch") - public List updateStatusInBatch(@PathVariable(name = "status") CommentStatus status, - @RequestBody List ids) { + public List updateStatusInBatch( + @PathVariable(name = "status") CommentStatus status, + @RequestBody List ids) { List comments = postCommentService.updateStatusByIds(ids, status); return postCommentService.convertTo(comments); } @@ -127,7 +139,7 @@ public PostCommentWithPostVO getBy(@PathVariable("commentId") Long commentId) { @PutMapping("{commentId:\\d+}") @ApiOperation("Updates a post comment") public BaseCommentDTO updateBy(@Valid @RequestBody PostCommentParam commentParam, - @PathVariable("commentId") Long commentId) { + @PathVariable("commentId") Long commentId) { PostComment commentToUpdate = postCommentService.getById(commentId); commentParam.update(commentToUpdate); diff --git a/src/main/java/run/halo/app/controller/admin/api/PostController.java b/src/main/java/run/halo/app/controller/admin/api/PostController.java index d34359d3c7..081dc6a27a 100644 --- a/src/main/java/run/halo/app/controller/admin/api/PostController.java +++ b/src/main/java/run/halo/app/controller/admin/api/PostController.java @@ -1,11 +1,27 @@ package run.halo.app.controller.admin.api; +import static org.springframework.data.domain.Sort.Direction.DESC; + import cn.hutool.core.util.IdUtil; import io.swagger.annotations.ApiOperation; +import java.io.UnsupportedEncodingException; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.concurrent.TimeUnit; +import javax.validation.Valid; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.web.PageableDefault; -import org.springframework.web.bind.annotation.*; +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 run.halo.app.cache.AbstractStringCacheStore; import run.halo.app.model.dto.post.BasePostDetailDTO; import run.halo.app.model.dto.post.BasePostMinimalDTO; @@ -20,15 +36,6 @@ import run.halo.app.service.OptionService; import run.halo.app.service.PostService; -import javax.validation.Valid; -import java.io.UnsupportedEncodingException; -import java.net.URLEncoder; -import java.nio.charset.StandardCharsets; -import java.util.List; -import java.util.concurrent.TimeUnit; - -import static org.springframework.data.domain.Sort.Direction.DESC; - /** * Post controller. * @@ -48,8 +55,8 @@ public class PostController { private final OptionService optionService; public PostController(PostService postService, - AbstractStringCacheStore cacheStore, - OptionService optionService) { + AbstractStringCacheStore cacheStore, + OptionService optionService) { this.postService = postService; this.cacheStore = cacheStore; this.optionService = optionService; @@ -57,9 +64,10 @@ public PostController(PostService postService, @GetMapping @ApiOperation("Lists posts") - public Page pageBy(@PageableDefault(sort = {"topPriority", "createTime"}, direction = DESC) Pageable pageable, - PostQuery postQuery, - @RequestParam(value = "more", defaultValue = "true") Boolean more) { + public Page pageBy( + @PageableDefault(sort = {"topPriority", "createTime"}, direction = DESC) Pageable pageable, + PostQuery postQuery, + @RequestParam(value = "more", defaultValue = "true") Boolean more) { Page postPage = postService.pageBy(postQuery, pageable); if (more) { return postService.convertToListVo(postPage); @@ -70,15 +78,17 @@ public Page pageBy(@PageableDefault(sort = {"topPri @GetMapping("latest") @ApiOperation("Pages latest post") - public List pageLatest(@RequestParam(name = "top", defaultValue = "10") int top) { + public List pageLatest( + @RequestParam(name = "top", defaultValue = "10") int top) { return postService.convertToMinimal(postService.pageLatest(top).getContent()); } @GetMapping("status/{status}") @ApiOperation("Gets a page of post by post status") - public Page pageByStatus(@PathVariable(name = "status") PostStatus status, - @RequestParam(value = "more", required = false, defaultValue = "false") Boolean more, - @PageableDefault(sort = "createTime", direction = DESC) Pageable pageable) { + public Page pageByStatus( + @PathVariable(name = "status") PostStatus status, + @RequestParam(value = "more", required = false, defaultValue = "false") Boolean more, + @PageableDefault(sort = "createTime", direction = DESC) Pageable pageable) { Page posts = postService.pageBy(status, pageable); if (more) { @@ -104,29 +114,33 @@ public void likes(@PathVariable("postId") Integer postId) { @PostMapping @ApiOperation("Creates a post") public PostDetailVO createBy(@Valid @RequestBody PostParam postParam, - @RequestParam(value = "autoSave", required = false, defaultValue = "false") Boolean autoSave) { + @RequestParam(value = "autoSave", required = false, defaultValue = "false") + Boolean autoSave) { // Convert to Post post = postParam.convertTo(); - return postService.createBy(post, postParam.getTagIds(), postParam.getCategoryIds(), postParam.getPostMetas(), autoSave); + return postService.createBy(post, postParam.getTagIds(), postParam.getCategoryIds(), + postParam.getPostMetas(), autoSave); } @PutMapping("{postId:\\d+}") @ApiOperation("Updates a post") public PostDetailVO updateBy(@Valid @RequestBody PostParam postParam, - @PathVariable("postId") Integer postId, - @RequestParam(value = "autoSave", required = false, defaultValue = "false") Boolean autoSave) { + @PathVariable("postId") Integer postId, + @RequestParam(value = "autoSave", required = false, defaultValue = "false") + Boolean autoSave) { // Get the post info Post postToUpdate = postService.getById(postId); postParam.update(postToUpdate); - return postService.updateBy(postToUpdate, postParam.getTagIds(), postParam.getCategoryIds(), postParam.getPostMetas(), autoSave); + return postService.updateBy(postToUpdate, postParam.getTagIds(), postParam.getCategoryIds(), + postParam.getPostMetas(), autoSave); } @PutMapping("{postId:\\d+}/status/{status}") @ApiOperation("Updates post status") public BasePostMinimalDTO updateStatusBy( - @PathVariable("postId") Integer postId, - @PathVariable("status") PostStatus status) { + @PathVariable("postId") Integer postId, + @PathVariable("status") PostStatus status) { Post post = postService.updateStatus(status, postId); return new BasePostMinimalDTO().convertFrom(post); @@ -135,15 +149,15 @@ public BasePostMinimalDTO updateStatusBy( @PutMapping("status/{status}") @ApiOperation("Updates post status in batch") public List updateStatusInBatch(@PathVariable(name = "status") PostStatus status, - @RequestBody List ids) { + @RequestBody List ids) { return postService.updateStatusByIds(ids, status); } @PutMapping("{postId:\\d+}/status/draft/content") @ApiOperation("Updates draft") public BasePostDetailDTO updateDraftBy( - @PathVariable("postId") Integer postId, - @RequestBody PostContentParam contentParam) { + @PathVariable("postId") Integer postId, + @RequestBody PostContentParam contentParam) { // Update draft content Post post = postService.updateDraftContent(contentParam.getContent(), postId); @@ -164,7 +178,8 @@ public List deletePermanentlyInBatch(@RequestBody List ids) { @GetMapping(value = {"preview/{postId:\\d+}", "{postId:\\d+}/preview"}) @ApiOperation("Gets a post preview link") - public String preview(@PathVariable("postId") Integer postId) throws UnsupportedEncodingException { + public String preview(@PathVariable("postId") Integer postId) + throws UnsupportedEncodingException { Post post = postService.getById(postId); post.setSlug(URLEncoder.encode(post.getSlug(), StandardCharsets.UTF_8.name())); @@ -186,10 +201,10 @@ public String preview(@PathVariable("postId") Integer postId) throws Unsupported if (optionService.getPostPermalinkType().equals(PostPermalinkType.ID)) { previewUrl.append("&token=") - .append(token); + .append(token); } else { previewUrl.append("?token=") - .append(token); + .append(token); } // build preview post url and return diff --git a/src/main/java/run/halo/app/controller/admin/api/SheetCommentController.java b/src/main/java/run/halo/app/controller/admin/api/SheetCommentController.java index 152c5a8dca..f2a15c2547 100644 --- a/src/main/java/run/halo/app/controller/admin/api/SheetCommentController.java +++ b/src/main/java/run/halo/app/controller/admin/api/SheetCommentController.java @@ -1,13 +1,25 @@ package run.halo.app.controller.admin.api; +import static org.springframework.data.domain.Sort.Direction.DESC; + import io.swagger.annotations.ApiOperation; +import java.util.List; +import javax.validation.Valid; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.data.web.PageableDefault; import org.springframework.data.web.SortDefault; -import org.springframework.web.bind.annotation.*; +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 run.halo.app.model.dto.BaseCommentDTO; import run.halo.app.model.entity.SheetComment; import run.halo.app.model.enums.CommentStatus; @@ -19,11 +31,6 @@ import run.halo.app.service.OptionService; import run.halo.app.service.SheetCommentService; -import javax.validation.Valid; -import java.util.List; - -import static org.springframework.data.domain.Sort.Direction.DESC; - /** * Sheet comment controller. * @@ -40,23 +47,25 @@ public class SheetCommentController { private final OptionService optionService; public SheetCommentController(SheetCommentService sheetCommentService, - OptionService optionService) { + OptionService optionService) { this.sheetCommentService = sheetCommentService; this.optionService = optionService; } @GetMapping @ApiOperation("Lists sheet comments") - public Page pageBy(@PageableDefault(sort = "createTime", direction = DESC) Pageable pageable, - CommentQuery commentQuery) { + public Page pageBy( + @PageableDefault(sort = "createTime", direction = DESC) Pageable pageable, + CommentQuery commentQuery) { Page sheetCommentPage = sheetCommentService.pageBy(commentQuery, pageable); return sheetCommentService.convertToWithSheetVo(sheetCommentPage); } @GetMapping("latest") @ApiOperation("Lists latest sheet comments") - public List listLatest(@RequestParam(name = "top", defaultValue = "10") int top, - @RequestParam(name = "status", required = false) CommentStatus status) { + public List listLatest( + @RequestParam(name = "top", defaultValue = "10") int top, + @RequestParam(name = "status", required = false) CommentStatus status) { Page sheetCommentPage = sheetCommentService.pageLatest(top, status); return sheetCommentService.convertToWithSheetVo(sheetCommentPage.getContent()); } @@ -64,17 +73,19 @@ public List listLatest(@RequestParam(name = "top", defa @GetMapping("{sheetId:\\d+}/tree_view") @ApiOperation("Lists sheet comments with tree view") public Page listCommentTree(@PathVariable("sheetId") Integer sheetId, - @RequestParam(name = "page", required = false, defaultValue = "0") int page, - @SortDefault(sort = "createTime", direction = DESC) Sort sort) { - return sheetCommentService.pageVosAllBy(sheetId, PageRequest.of(page, optionService.getCommentPageSize(), sort)); + @RequestParam(name = "page", required = false, defaultValue = "0") int page, + @SortDefault(sort = "createTime", direction = DESC) Sort sort) { + return sheetCommentService + .pageVosAllBy(sheetId, PageRequest.of(page, optionService.getCommentPageSize(), sort)); } @GetMapping("{sheetId:\\d+}/list_view") @ApiOperation("Lists sheet comment with list view") public Page listComments(@PathVariable("sheetId") Integer sheetId, - @RequestParam(name = "page", required = false, defaultValue = "0") int page, - @SortDefault(sort = "createTime", direction = DESC) Sort sort) { - return sheetCommentService.pageWithParentVoBy(sheetId, PageRequest.of(page, optionService.getCommentPageSize(), sort)); + @RequestParam(name = "page", required = false, defaultValue = "0") int page, + @SortDefault(sort = "createTime", direction = DESC) Sort sort) { + return sheetCommentService.pageWithParentVoBy(sheetId, + PageRequest.of(page, optionService.getCommentPageSize(), sort)); } @PostMapping @@ -87,7 +98,7 @@ public BaseCommentDTO createBy(@RequestBody SheetCommentParam commentParam) { @PutMapping("{commentId:\\d+}/status/{status}") @ApiOperation("Updates sheet comment status") public BaseCommentDTO updateStatusBy(@PathVariable("commentId") Long commentId, - @PathVariable("status") CommentStatus status) { + @PathVariable("status") CommentStatus status) { // Update comment status SheetComment updatedSheetComment = sheetCommentService.updateStatus(commentId, status); return sheetCommentService.convertTo(updatedSheetComment); @@ -95,8 +106,9 @@ public BaseCommentDTO updateStatusBy(@PathVariable("commentId") Long commentId, @PutMapping("status/{status}") @ApiOperation("Updates sheet comment status in batch") - public List updateStatusInBatch(@PathVariable(name = "status") CommentStatus status, - @RequestBody List ids) { + public List updateStatusInBatch( + @PathVariable(name = "status") CommentStatus status, + @RequestBody List ids) { List comments = sheetCommentService.updateStatusByIds(ids, status); return sheetCommentService.convertTo(comments); } @@ -125,7 +137,7 @@ public SheetCommentWithSheetVO getBy(@PathVariable("commentId") Long commentId) @PutMapping("{commentId:\\d+}") @ApiOperation("Updates a sheet comment") public BaseCommentDTO updateBy(@Valid @RequestBody SheetCommentParam commentParam, - @PathVariable("commentId") Long commentId) { + @PathVariable("commentId") Long commentId) { SheetComment commentToUpdate = sheetCommentService.getById(commentId); commentParam.update(commentToUpdate); diff --git a/src/main/java/run/halo/app/controller/admin/api/SheetController.java b/src/main/java/run/halo/app/controller/admin/api/SheetController.java index b80e66d1ee..ade88fb4c7 100644 --- a/src/main/java/run/halo/app/controller/admin/api/SheetController.java +++ b/src/main/java/run/halo/app/controller/admin/api/SheetController.java @@ -1,11 +1,27 @@ package run.halo.app.controller.admin.api; +import static org.springframework.data.domain.Sort.Direction.DESC; + import cn.hutool.core.util.IdUtil; import io.swagger.annotations.ApiOperation; +import java.io.UnsupportedEncodingException; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.concurrent.TimeUnit; +import javax.validation.Valid; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.web.PageableDefault; -import org.springframework.web.bind.annotation.*; +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 run.halo.app.cache.AbstractStringCacheStore; import run.halo.app.model.dto.IndependentSheetDTO; import run.halo.app.model.dto.post.BasePostDetailDTO; @@ -19,15 +35,6 @@ import run.halo.app.service.OptionService; import run.halo.app.service.SheetService; -import javax.validation.Valid; -import java.io.UnsupportedEncodingException; -import java.net.URLEncoder; -import java.nio.charset.StandardCharsets; -import java.util.List; -import java.util.concurrent.TimeUnit; - -import static org.springframework.data.domain.Sort.Direction.DESC; - /** * Sheet controller. * @@ -46,8 +53,8 @@ public class SheetController { private final OptionService optionService; public SheetController(SheetService sheetService, - AbstractStringCacheStore cacheStore, - OptionService optionService) { + AbstractStringCacheStore cacheStore, + OptionService optionService) { this.sheetService = sheetService; this.cacheStore = cacheStore; this.optionService = optionService; @@ -62,7 +69,8 @@ public SheetDetailVO getBy(@PathVariable("sheetId") Integer sheetId) { @GetMapping @ApiOperation("Gets a page of sheet") - public Page pageBy(@PageableDefault(sort = "createTime", direction = DESC) Pageable pageable) { + public Page pageBy( + @PageableDefault(sort = "createTime", direction = DESC) Pageable pageable) { Page sheetPage = sheetService.pageBy(pageable); return sheetService.convertToListVo(sheetPage); } @@ -76,17 +84,20 @@ public List independentSheets() { @PostMapping @ApiOperation("Creates a sheet") public SheetDetailVO createBy(@RequestBody @Valid SheetParam sheetParam, - @RequestParam(value = "autoSave", required = false, defaultValue = "false") Boolean autoSave) { - Sheet sheet = sheetService.createBy(sheetParam.convertTo(), sheetParam.getSheetMetas(), autoSave); + @RequestParam(value = "autoSave", required = false, defaultValue = "false") + Boolean autoSave) { + Sheet sheet = + sheetService.createBy(sheetParam.convertTo(), sheetParam.getSheetMetas(), autoSave); return sheetService.convertToDetailVo(sheet); } @PutMapping("{sheetId:\\d+}") @ApiOperation("Updates a sheet") public SheetDetailVO updateBy( - @PathVariable("sheetId") Integer sheetId, - @RequestBody @Valid SheetParam sheetParam, - @RequestParam(value = "autoSave", required = false, defaultValue = "false") Boolean autoSave) { + @PathVariable("sheetId") Integer sheetId, + @RequestBody @Valid SheetParam sheetParam, + @RequestParam(value = "autoSave", required = false, defaultValue = "false") + Boolean autoSave) { Sheet sheetToUpdate = sheetService.getById(sheetId); sheetParam.update(sheetToUpdate); @@ -99,8 +110,8 @@ public SheetDetailVO updateBy( @PutMapping("{sheetId:\\d+}/{status}") @ApiOperation("Updates a sheet") public void updateStatusBy( - @PathVariable("sheetId") Integer sheetId, - @PathVariable("status") PostStatus status) { + @PathVariable("sheetId") Integer sheetId, + @PathVariable("status") PostStatus status) { Sheet sheet = sheetService.getById(sheetId); // Set status @@ -113,8 +124,8 @@ public void updateStatusBy( @PutMapping("{sheetId:\\d+}/status/draft/content") @ApiOperation("Updates draft") public BasePostDetailDTO updateDraftBy( - @PathVariable("sheetId") Integer sheetId, - @RequestBody PostContentParam contentParam) { + @PathVariable("sheetId") Integer sheetId, + @RequestBody PostContentParam contentParam) { // Update draft content Sheet sheet = sheetService.updateDraftContent(contentParam.getContent(), sheetId); @@ -130,7 +141,8 @@ public SheetDetailVO deleteBy(@PathVariable("sheetId") Integer sheetId) { @GetMapping("preview/{sheetId:\\d+}") @ApiOperation("Gets a sheet preview link") - public String preview(@PathVariable("sheetId") Integer sheetId) throws UnsupportedEncodingException { + public String preview(@PathVariable("sheetId") Integer sheetId) + throws UnsupportedEncodingException { Sheet sheet = sheetService.getById(sheetId); sheet.setSlug(URLEncoder.encode(sheet.getSlug(), StandardCharsets.UTF_8.name())); @@ -149,8 +161,8 @@ public String preview(@PathVariable("sheetId") Integer sheetId) throws Unsupport } previewUrl.append(sheetMinimalDTO.getFullPath()) - .append("?token=") - .append(token); + .append("?token=") + .append(token); // build preview post url and return return previewUrl.toString(); diff --git a/src/main/java/run/halo/app/controller/admin/api/StaticStorageController.java b/src/main/java/run/halo/app/controller/admin/api/StaticStorageController.java index b80431a64e..9ce5198123 100644 --- a/src/main/java/run/halo/app/controller/admin/api/StaticStorageController.java +++ b/src/main/java/run/halo/app/controller/admin/api/StaticStorageController.java @@ -1,14 +1,21 @@ package run.halo.app.controller.admin.api; import io.swagger.annotations.ApiOperation; -import org.springframework.web.bind.annotation.*; +import java.util.List; +import org.springframework.web.bind.annotation.DeleteMapping; +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.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; import run.halo.app.model.params.StaticContentParam; import run.halo.app.model.support.StaticFile; import run.halo.app.service.StaticStorageService; -import java.util.List; - /** * Static storage controller. * @@ -40,21 +47,21 @@ public void deletePermanently(@RequestParam("path") String path) { @PostMapping @ApiOperation("Creates a folder") public void createFolder(String basePath, - @RequestParam("folderName") String folderName) { + @RequestParam("folderName") String folderName) { staticStorageService.createFolder(basePath, folderName); } @PostMapping("upload") @ApiOperation("Uploads static file") public void upload(String basePath, - @RequestPart("file") MultipartFile file) { + @RequestPart("file") MultipartFile file) { staticStorageService.upload(basePath, file); } @PostMapping("rename") @ApiOperation("Renames static file") public void rename(String basePath, - String newName) { + String newName) { staticStorageService.rename(basePath, newName); } diff --git a/src/main/java/run/halo/app/controller/admin/api/TagController.java b/src/main/java/run/halo/app/controller/admin/api/TagController.java index 2cf648bf56..9b1df13b36 100644 --- a/src/main/java/run/halo/app/controller/admin/api/TagController.java +++ b/src/main/java/run/halo/app/controller/admin/api/TagController.java @@ -2,19 +2,26 @@ import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; +import java.util.List; +import javax.validation.Valid; import lombok.extern.slf4j.Slf4j; import org.springframework.data.domain.Sort; import org.springframework.data.web.SortDefault; -import org.springframework.web.bind.annotation.*; +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 run.halo.app.model.dto.TagDTO; import run.halo.app.model.entity.Tag; import run.halo.app.model.params.TagParam; import run.halo.app.service.PostTagService; import run.halo.app.service.TagService; -import javax.validation.Valid; -import java.util.List; - /** * Tag controller. * @@ -31,16 +38,17 @@ public class TagController { private final PostTagService postTagService; public TagController(TagService tagService, - PostTagService postTagService) { + PostTagService postTagService) { this.tagService = tagService; this.postTagService = postTagService; } @GetMapping @ApiOperation("Lists tags") - public List listTags(@SortDefault(sort = "createTime", direction = Sort.Direction.DESC) Sort sort, - @ApiParam("Return more information(post count) if it is set") - @RequestParam(name = "more", required = false, defaultValue = "false") Boolean more) { + public List listTags( + @SortDefault(sort = "createTime", direction = Sort.Direction.DESC) Sort sort, + @ApiParam("Return more information(post count) if it is set") + @RequestParam(name = "more", required = false, defaultValue = "false") Boolean more) { if (more) { return postTagService.listTagWithCountDtos(sort); } @@ -68,7 +76,7 @@ public TagDTO getBy(@PathVariable("tagId") Integer tagId) { @PutMapping("{tagId:\\d+}") @ApiOperation("Updates a tag") public TagDTO updateBy(@PathVariable("tagId") Integer tagId, - @Valid @RequestBody TagParam tagParam) { + @Valid @RequestBody TagParam tagParam) { // Get old tag Tag tag = tagService.getById(tagId); diff --git a/src/main/java/run/halo/app/controller/admin/api/ThemeController.java b/src/main/java/run/halo/app/controller/admin/api/ThemeController.java index 3e8f28d6bb..e33927af90 100644 --- a/src/main/java/run/halo/app/controller/admin/api/ThemeController.java +++ b/src/main/java/run/halo/app/controller/admin/api/ThemeController.java @@ -1,8 +1,19 @@ package run.halo.app.controller.admin.api; import io.swagger.annotations.ApiOperation; +import java.util.List; +import java.util.Map; import org.springframework.http.HttpStatus; -import org.springframework.web.bind.annotation.*; +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; import run.halo.app.annotation.DisableOnCondition; import run.halo.app.cache.lock.CacheLock; @@ -14,9 +25,6 @@ import run.halo.app.service.ThemeService; import run.halo.app.service.ThemeSettingService; -import java.util.List; -import java.util.Map; - /** * Theme controller. * @@ -32,7 +40,7 @@ public class ThemeController { private final ThemeSettingService themeSettingService; public ThemeController(ThemeService themeService, - ThemeSettingService themeSettingService) { + ThemeSettingService themeSettingService) { this.themeService = themeService; this.themeSettingService = themeSettingService; } @@ -64,14 +72,16 @@ public List listFiles(@PathVariable("themeId") String themeId) { @GetMapping("files/content") @ApiOperation("Gets template content") public BaseResponse getContentBy(@RequestParam(name = "path") String path) { - return BaseResponse.ok(HttpStatus.OK.getReasonPhrase(), themeService.getTemplateContent(path)); + return BaseResponse + .ok(HttpStatus.OK.getReasonPhrase(), themeService.getTemplateContent(path)); } @GetMapping("{themeId}/files/content") @ApiOperation("Gets template content by theme id") public BaseResponse getContentBy(@PathVariable("themeId") String themeId, - @RequestParam(name = "path") String path) { - return BaseResponse.ok(HttpStatus.OK.getReasonPhrase(), themeService.getTemplateContent(themeId, path)); + @RequestParam(name = "path") String path) { + return BaseResponse + .ok(HttpStatus.OK.getReasonPhrase(), themeService.getTemplateContent(themeId, path)); } @PutMapping("files/content") @@ -85,20 +95,22 @@ public void updateContentBy(@RequestBody ThemeContentParam param) { @ApiOperation("Updates template content by theme id") @DisableOnCondition public void updateContentBy(@PathVariable("themeId") String themeId, - @RequestBody ThemeContentParam param) { + @RequestBody ThemeContentParam param) { themeService.saveTemplateContent(themeId, param.getPath(), param.getContent()); } @GetMapping("activation/template/custom/sheet") @ApiOperation("Gets custom sheet templates") public List customSheetTemplate() { - return themeService.listCustomTemplates(themeService.getActivatedThemeId(), ThemeService.CUSTOM_SHEET_PREFIX); + return themeService.listCustomTemplates(themeService.getActivatedThemeId(), + ThemeService.CUSTOM_SHEET_PREFIX); } @GetMapping("activation/template/custom/post") @ApiOperation("Gets custom post templates") public List customPostTemplate() { - return themeService.listCustomTemplates(themeService.getActivatedThemeId(), ThemeService.CUSTOM_POST_PREFIX); + return themeService.listCustomTemplates(themeService.getActivatedThemeId(), + ThemeService.CUSTOM_POST_PREFIX); } @PostMapping("{themeId}/activation") @@ -147,7 +159,7 @@ public void saveSettingsBy(@RequestBody Map settings) { @ApiOperation("Saves theme settings") @CacheLock(prefix = "save_theme_setting_by_themeId") public void saveSettingsBy(@PathVariable("themeId") String themeId, - @RequestBody Map settings) { + @RequestBody Map settings) { themeSettingService.save(settings, themeId); } @@ -155,7 +167,7 @@ public void saveSettingsBy(@PathVariable("themeId") String themeId, @ApiOperation("Deletes a theme") @DisableOnCondition public void deleteBy(@PathVariable("themeId") String themeId, - @RequestParam(value = "deleteSettings", defaultValue = "false") Boolean deleteSettings) { + @RequestParam(value = "deleteSettings", defaultValue = "false") Boolean deleteSettings) { themeService.deleteTheme(themeId, deleteSettings); } @@ -168,7 +180,7 @@ public ThemeProperty uploadTheme(@RequestPart("file") MultipartFile file) { @PostMapping("upload/{themeId}") @ApiOperation("Upgrades theme by file") public ThemeProperty updateThemeByUpload(@PathVariable("themeId") String themeId, - @RequestPart("file") MultipartFile file) { + @RequestPart("file") MultipartFile file) { return themeService.update(themeId, file); } @@ -192,13 +204,15 @@ public List fetchReleases(@RequestParam("uri") String uri) { @GetMapping("fetchingRelease") @ApiOperation("Fetches a specific release") - public ThemeProperty fetchRelease(@RequestParam("uri") String uri, @RequestParam("tag") String tagName) { + public ThemeProperty fetchRelease(@RequestParam("uri") String uri, + @RequestParam("tag") String tagName) { return themeService.fetchRelease(uri, tagName); } @GetMapping("fetchBranch") @ApiOperation("Fetch specific branch") - public ThemeProperty fetchBranch(@RequestParam("uri") String uri, @RequestParam("branch") String branchName) { + public ThemeProperty fetchBranch(@RequestParam("uri") String uri, + @RequestParam("branch") String branchName) { return themeService.fetchBranch(uri, branchName); } diff --git a/src/main/java/run/halo/app/controller/admin/api/UserController.java b/src/main/java/run/halo/app/controller/admin/api/UserController.java index 813db9d1ad..3e056fe5bd 100644 --- a/src/main/java/run/halo/app/controller/admin/api/UserController.java +++ b/src/main/java/run/halo/app/controller/admin/api/UserController.java @@ -4,7 +4,12 @@ import cn.hutool.core.util.StrUtil; import cn.hutool.extra.qrcode.QrCodeUtil; import io.swagger.annotations.ApiOperation; -import org.springframework.web.bind.annotation.*; +import javax.validation.Valid; +import org.springframework.web.bind.annotation.GetMapping; +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 run.halo.app.annotation.DisableOnCondition; import run.halo.app.cache.lock.CacheLock; import run.halo.app.exception.BadRequestException; @@ -21,8 +26,6 @@ import run.halo.app.utils.TwoFactorAuthUtils; import run.halo.app.utils.ValidationUtils; -import javax.validation.Valid; - /** * User controller. * @@ -62,21 +65,25 @@ public UserDTO updateProfile(@RequestBody UserParam userParam, User user) { @PutMapping("profiles/password") @ApiOperation("Updates user's password") @DisableOnCondition - public BaseResponse updatePassword(@RequestBody @Valid PasswordParam passwordParam, User user) { - userService.updatePassword(passwordParam.getOldPassword(), passwordParam.getNewPassword(), user.getId()); + public BaseResponse updatePassword(@RequestBody @Valid PasswordParam passwordParam, + User user) { + userService.updatePassword(passwordParam.getOldPassword(), passwordParam.getNewPassword(), + user.getId()); return BaseResponse.ok("密码修改成功"); } @PutMapping("mfa/generate") @ApiOperation("Generate Multi-Factor Auth qr image") @DisableOnCondition - public MultiFactorAuthVO generateMFAQrImage(@RequestBody MultiFactorAuthParam multiFactorAuthParam, User user) { + public MultiFactorAuthVO generateMFAQrImage( + @RequestBody MultiFactorAuthParam multiFactorAuthParam, User user) { if (MFAType.NONE == user.getMfaType()) { if (MFAType.TFA_TOTP == multiFactorAuthParam.getMfaType()) { String mfaKey = TwoFactorAuthUtils.generateTFAKey(); - String optAuthUrl = TwoFactorAuthUtils.generateOtpAuthUrl(user.getNickname(), mfaKey); - String qrImageBase64 = "data:image/png;base64," + - Base64.encode(QrCodeUtil.generatePng(optAuthUrl, 128, 128)); + String optAuthUrl = + TwoFactorAuthUtils.generateOtpAuthUrl(user.getNickname(), mfaKey); + String qrImageBase64 = "data:image/png;base64," + + Base64.encode(QrCodeUtil.generatePng(optAuthUrl, 128, 128)); return new MultiFactorAuthVO(qrImageBase64, optAuthUrl, mfaKey, MFAType.TFA_TOTP); } else { throw new BadRequestException("暂不支持的 MFA 认证的方式"); @@ -90,17 +97,23 @@ public MultiFactorAuthVO generateMFAQrImage(@RequestBody MultiFactorAuthParam mu @ApiOperation("Updates user's Multi Factor Auth") @CacheLock(autoDelete = false, prefix = "mfa") @DisableOnCondition - public MultiFactorAuthVO updateMFAuth(@RequestBody @Valid MultiFactorAuthParam multiFactorAuthParam, User user) { - if (StrUtil.isNotBlank(user.getMfaKey()) && MFAType.useMFA(multiFactorAuthParam.getMfaType())) { + public MultiFactorAuthVO updateMFAuth( + @RequestBody @Valid MultiFactorAuthParam multiFactorAuthParam, User user) { + if (StrUtil.isNotBlank(user.getMfaKey()) + && MFAType.useMFA(multiFactorAuthParam.getMfaType())) { return new MultiFactorAuthVO(MFAType.TFA_TOTP); - } else if (StrUtil.isBlank(user.getMfaKey()) && !MFAType.useMFA(multiFactorAuthParam.getMfaType())) { + } else if (StrUtil.isBlank(user.getMfaKey()) + && !MFAType.useMFA(multiFactorAuthParam.getMfaType())) { return new MultiFactorAuthVO(MFAType.NONE); } else { - final String tfaKey = StrUtil.isNotBlank(user.getMfaKey()) ? user.getMfaKey() : multiFactorAuthParam.getMfaKey(); + final String tfaKey = StrUtil.isNotBlank(user.getMfaKey()) ? user.getMfaKey() : + multiFactorAuthParam.getMfaKey(); TwoFactorAuthUtils.validateTFACode(tfaKey, multiFactorAuthParam.getAuthcode()); } // update MFA key - User updateUser = userService.updateMFA(multiFactorAuthParam.getMfaType(), multiFactorAuthParam.getMfaKey(), user.getId()); + User updateUser = userService + .updateMFA(multiFactorAuthParam.getMfaType(), multiFactorAuthParam.getMfaKey(), + user.getId()); return new MultiFactorAuthVO(updateUser.getMfaType()); } diff --git a/src/main/java/run/halo/app/controller/content/ContentContentController.java b/src/main/java/run/halo/app/controller/content/ContentContentController.java index 60e902d61e..d15ec95877 100644 --- a/src/main/java/run/halo/app/controller/content/ContentContentController.java +++ b/src/main/java/run/halo/app/controller/content/ContentContentController.java @@ -1,14 +1,28 @@ package run.halo.app.controller.content; import cn.hutool.core.util.IdUtil; +import java.io.UnsupportedEncodingException; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.concurrent.TimeUnit; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.*; +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.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; import run.halo.app.cache.AbstractStringCacheStore; import run.halo.app.cache.lock.CacheLock; -import run.halo.app.controller.content.model.*; +import run.halo.app.controller.content.model.CategoryModel; +import run.halo.app.controller.content.model.JournalModel; +import run.halo.app.controller.content.model.LinkModel; +import run.halo.app.controller.content.model.PhotoModel; +import run.halo.app.controller.content.model.PostModel; +import run.halo.app.controller.content.model.SheetModel; +import run.halo.app.controller.content.model.TagModel; import run.halo.app.exception.NotFoundException; import run.halo.app.model.dto.post.BasePostMinimalDTO; import run.halo.app.model.entity.Post; @@ -20,11 +34,6 @@ import run.halo.app.service.PostService; import run.halo.app.service.SheetService; -import java.io.UnsupportedEncodingException; -import java.net.URLEncoder; -import java.nio.charset.StandardCharsets; -import java.util.concurrent.TimeUnit; - /** * @author ryanwang * @date 2020-01-07 @@ -57,16 +66,16 @@ public class ContentContentController { private final AbstractStringCacheStore cacheStore; public ContentContentController(PostModel postModel, - SheetModel sheetModel, - CategoryModel categoryModel, - TagModel tagModel, - JournalModel journalModel, - PhotoModel photoModel, - LinkModel linkModel, - OptionService optionService, - PostService postService, - SheetService sheetService, - AbstractStringCacheStore cacheStore) { + SheetModel sheetModel, + CategoryModel categoryModel, + TagModel tagModel, + JournalModel journalModel, + PhotoModel photoModel, + LinkModel linkModel, + OptionService optionService, + PostService postService, + SheetService sheetService, + AbstractStringCacheStore cacheStore) { this.postModel = postModel; this.sheetModel = sheetModel; this.categoryModel = categoryModel; @@ -82,8 +91,8 @@ public ContentContentController(PostModel postModel, @GetMapping("{prefix}") public String content(@PathVariable("prefix") String prefix, - @RequestParam(value = "token", required = false) String token, - Model model) { + @RequestParam(value = "token", required = false) String token, + Model model) { if (optionService.getSheetPermalinkType().equals(SheetPermalinkType.ROOT)) { Sheet sheet = sheetService.getBySlug(prefix); return sheetModel.content(sheet, token, model); @@ -111,8 +120,8 @@ public String content(@PathVariable("prefix") String prefix, @GetMapping("{prefix}/page/{page:\\d+}") public String content(@PathVariable("prefix") String prefix, - @PathVariable(value = "page") Integer page, - Model model) { + @PathVariable(value = "page") Integer page, + Model model) { if (optionService.getArchivesPrefix().equals(prefix)) { return postModel.archives(page, model); } @@ -130,22 +139,24 @@ public String content(@PathVariable("prefix") String prefix, @GetMapping("{prefix}/{slug}") public String content(@PathVariable("prefix") String prefix, - @PathVariable("slug") String slug, - @RequestParam(value = "token", required = false) String token, - Model model) { + @PathVariable("slug") String slug, + @RequestParam(value = "token", required = false) String token, + Model model) { PostPermalinkType postPermalinkType = optionService.getPostPermalinkType(); if (optionService.getArchivesPrefix().equals(prefix)) { if (postPermalinkType.equals(PostPermalinkType.DEFAULT)) { Post post = postService.getBySlug(slug); return postModel.content(post, token, model); } - if (postPermalinkType.equals(PostPermalinkType.ID_SLUG) && StringUtils.isNumeric(slug)) { + if (postPermalinkType.equals(PostPermalinkType.ID_SLUG) + && StringUtils.isNumeric(slug)) { Post post = postService.getById(Integer.parseInt(slug)); return postModel.content(post, token, model); } } - if (optionService.getSheetPermalinkType().equals(SheetPermalinkType.SECONDARY) && optionService.getSheetPrefix().equals(prefix)) { + if (optionService.getSheetPermalinkType().equals(SheetPermalinkType.SECONDARY) + && optionService.getSheetPrefix().equals(prefix)) { Sheet sheet = sheetService.getBySlug(slug); return sheetModel.content(sheet, token, model); } @@ -158,7 +169,8 @@ public String content(@PathVariable("prefix") String prefix, return tagModel.listPost(model, slug, 1); } - if (postPermalinkType.equals(PostPermalinkType.YEAR) && prefix.length() == 4 && StringUtils.isNumeric(prefix)) { + if (postPermalinkType.equals(PostPermalinkType.YEAR) && prefix.length() == 4 + && StringUtils.isNumeric(prefix)) { Post post = postService.getBy(Integer.parseInt(prefix), slug); return postModel.content(post, token, model); } @@ -168,9 +180,9 @@ public String content(@PathVariable("prefix") String prefix, @GetMapping("{prefix}/{slug}/page/{page:\\d+}") public String content(@PathVariable("prefix") String prefix, - @PathVariable("slug") String slug, - @PathVariable("page") Integer page, - Model model) { + @PathVariable("slug") String slug, + @PathVariable("page") Integer page, + Model model) { if (optionService.getCategoriesPrefix().equals(prefix)) { return categoryModel.listPost(model, slug, page); } @@ -184,10 +196,10 @@ public String content(@PathVariable("prefix") String prefix, @GetMapping("{year:\\d+}/{month:\\d+}/{slug}") public String content(@PathVariable("year") Integer year, - @PathVariable("month") Integer month, - @PathVariable("slug") String slug, - @RequestParam(value = "token", required = false) String token, - Model model) { + @PathVariable("month") Integer month, + @PathVariable("slug") String slug, + @RequestParam(value = "token", required = false) String token, + Model model) { PostPermalinkType postPermalinkType = optionService.getPostPermalinkType(); if (postPermalinkType.equals(PostPermalinkType.DATE)) { Post post = postService.getBy(year, month, slug); @@ -199,11 +211,11 @@ public String content(@PathVariable("year") Integer year, @GetMapping("{year:\\d+}/{month:\\d+}/{day:\\d+}/{slug}") public String content(@PathVariable("year") Integer year, - @PathVariable("month") Integer month, - @PathVariable("day") Integer day, - @PathVariable("slug") String slug, - @RequestParam(value = "token", required = false) String token, - Model model) { + @PathVariable("month") Integer month, + @PathVariable("day") Integer day, + @PathVariable("slug") String slug, + @RequestParam(value = "token", required = false) String token, + Model model) { PostPermalinkType postPermalinkType = optionService.getPostPermalinkType(); if (postPermalinkType.equals(PostPermalinkType.DAY)) { Post post = postService.getBy(year, month, day, slug); @@ -216,7 +228,7 @@ public String content(@PathVariable("year") Integer year, @PostMapping(value = "archives/{slug:.*}/password") @CacheLock(traceRequest = true, expired = 2) public String password(@PathVariable("slug") String slug, - @RequestParam(value = "password") String password) throws UnsupportedEncodingException { + @RequestParam(value = "password") String password) throws UnsupportedEncodingException { Post post = postService.getBy(PostStatus.INTIMATE, slug); post.setSlug(URLEncoder.encode(post.getSlug(), StandardCharsets.UTF_8.name())); @@ -237,10 +249,10 @@ public String password(@PathVariable("slug") String slug, if (optionService.getPostPermalinkType().equals(PostPermalinkType.ID)) { redirectUrl.append("&token=") - .append(token); + .append(token); } else { redirectUrl.append("?token=") - .append(token); + .append(token); } } diff --git a/src/main/java/run/halo/app/controller/content/ContentFeedController.java b/src/main/java/run/halo/app/controller/content/ContentFeedController.java index 6f0e7a9ce4..d672017156 100644 --- a/src/main/java/run/halo/app/controller/content/ContentFeedController.java +++ b/src/main/java/run/halo/app/controller/content/ContentFeedController.java @@ -1,7 +1,11 @@ package run.halo.app.controller.content; +import static org.springframework.data.domain.Sort.Direction.DESC; + import freemarker.template.Template; import freemarker.template.TemplateException; +import java.io.IOException; +import java.util.List; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.RegExUtils; import org.springframework.data.domain.Page; @@ -29,11 +33,6 @@ import run.halo.app.service.PostCategoryService; import run.halo.app.service.PostService; -import java.io.IOException; -import java.util.List; - -import static org.springframework.data.domain.Sort.Direction.DESC; - /** * @author ryanwang * @date 2019-03-21 @@ -42,11 +41,11 @@ @Controller public class ContentFeedController { - private final static String UTF_8_SUFFIX = ";charset=UTF-8"; + private static final String UTF_8_SUFFIX = ";charset=UTF-8"; - private final static String XML_INVALID_CHAR = "[\\x00-\\x1F\\x7F]"; + private static final String XML_INVALID_CHAR = "[\\x00-\\x1F\\x7F]"; - private final static String XML_MEDIA_TYPE = MediaType.APPLICATION_XML_VALUE + UTF_8_SUFFIX; + private static final String XML_MEDIA_TYPE = MediaType.APPLICATION_XML_VALUE + UTF_8_SUFFIX; private final PostService postService; @@ -59,10 +58,10 @@ public class ContentFeedController { private final FreeMarkerConfigurer freeMarker; public ContentFeedController(PostService postService, - CategoryService categoryService, - PostCategoryService postCategoryService, - OptionService optionService, - FreeMarkerConfigurer freeMarker) { + CategoryService categoryService, + PostCategoryService postCategoryService, + OptionService optionService, + FreeMarkerConfigurer freeMarker) { this.postService = postService; this.categoryService = categoryService; this.postCategoryService = postCategoryService; @@ -90,18 +89,21 @@ public String feed(Model model) throws IOException, TemplateException { * Get category post rss. * * @param model model - * @param slug slug + * @param slug slug * @return rss xml content * @throws IOException throw IOException * @throws TemplateException throw TemplateException */ - @GetMapping(value = {"feed/categories/{slug}", "feed/categories/{slug}.xml"}, produces = XML_MEDIA_TYPE) + @GetMapping(value = {"feed/categories/{slug}", + "feed/categories/{slug}.xml"}, produces = XML_MEDIA_TYPE) @ResponseBody - public String feed(Model model, @PathVariable(name = "slug") String slug) throws IOException, TemplateException { + public String feed(Model model, @PathVariable(name = "slug") String slug) + throws IOException, TemplateException { Category category = categoryService.getBySlugOfNonNull(slug); CategoryDTO categoryDTO = categoryService.convertTo(category); model.addAttribute("category", categoryDTO); - model.addAttribute("posts", buildCategoryPosts(buildPostPageable(optionService.getRssPageSize()), categoryDTO)); + model.addAttribute("posts", + buildCategoryPosts(buildPostPageable(optionService.getRssPageSize()), categoryDTO)); Template template = freeMarker.getConfiguration().getTemplate("common/web/rss.ftl"); return FreeMarkerTemplateUtils.processTemplateIntoString(template, model); } @@ -126,18 +128,21 @@ public String atom(Model model) throws IOException, TemplateException { * Get category posts atom.xml * * @param model model - * @param slug slug + * @param slug slug * @return atom xml content * @throws IOException throw IOException * @throws TemplateException throw TemplateException */ - @GetMapping(value = {"atom/categories/{slug}", "atom/categories/{slug}.xml"}, produces = XML_MEDIA_TYPE) + @GetMapping(value = {"atom/categories/{slug}", + "atom/categories/{slug}.xml"}, produces = XML_MEDIA_TYPE) @ResponseBody - public String atom(Model model, @PathVariable(name = "slug") String slug) throws IOException, TemplateException { + public String atom(Model model, @PathVariable(name = "slug") String slug) + throws IOException, TemplateException { Category category = categoryService.getBySlugOfNonNull(slug); CategoryDTO categoryDTO = categoryService.convertTo(category); model.addAttribute("category", categoryDTO); - model.addAttribute("posts", buildCategoryPosts(buildPostPageable(optionService.getRssPageSize()), categoryDTO)); + model.addAttribute("posts", + buildCategoryPosts(buildPostPageable(optionService.getRssPageSize()), categoryDTO)); Template template = freeMarker.getConfiguration().getTemplate("common/web/atom.ftl"); return FreeMarkerTemplateUtils.processTemplateIntoString(template, model); } @@ -153,7 +158,8 @@ public String atom(Model model, @PathVariable(name = "slug") String slug) throws @GetMapping(value = {"sitemap", "sitemap.xml"}, produces = XML_MEDIA_TYPE) @ResponseBody public String sitemapXml(Model model, - @PageableDefault(size = Integer.MAX_VALUE, sort = "createTime", direction = DESC) Pageable pageable) throws IOException, TemplateException { + @PageableDefault(size = Integer.MAX_VALUE, sort = "createTime", direction = DESC) + Pageable pageable) throws IOException, TemplateException { model.addAttribute("posts", buildPosts(pageable)); Template template = freeMarker.getConfiguration().getTemplate("common/web/sitemap_xml.ftl"); return FreeMarkerTemplateUtils.processTemplateIntoString(template, model); @@ -167,7 +173,8 @@ public String sitemapXml(Model model, */ @GetMapping(value = "sitemap.html") public String sitemapHtml(Model model, - @PageableDefault(size = Integer.MAX_VALUE, sort = "createTime", direction = DESC) Pageable pageable) { + @PageableDefault(size = Integer.MAX_VALUE, sort = "createTime", direction = DESC) + Pageable pageable) { model.addAttribute("posts", buildPosts(pageable)); return "common/web/sitemap_html"; } @@ -210,8 +217,10 @@ private List buildPosts(@NonNull Pageable pageable) { Page postPage = postService.pageBy(PostStatus.PUBLISHED, pageable); Page posts = postService.convertToDetailVo(postPage); posts.getContent().forEach(postDetailVO -> { - postDetailVO.setFormatContent(RegExUtils.replaceAll(postDetailVO.getFormatContent(), XML_INVALID_CHAR, "")); - postDetailVO.setSummary(RegExUtils.replaceAll(postDetailVO.getSummary(), XML_INVALID_CHAR, "")); + postDetailVO.setFormatContent( + RegExUtils.replaceAll(postDetailVO.getFormatContent(), XML_INVALID_CHAR, "")); + postDetailVO + .setSummary(RegExUtils.replaceAll(postDetailVO.getSummary(), XML_INVALID_CHAR, "")); }); return posts.getContent(); } @@ -223,15 +232,19 @@ private List buildPosts(@NonNull Pageable pageable) { * @param category category * @return list of post detail vo. */ - private List buildCategoryPosts(@NonNull Pageable pageable, @NonNull CategoryDTO category) { + private List buildCategoryPosts(@NonNull Pageable pageable, + @NonNull CategoryDTO category) { Assert.notNull(pageable, "Pageable must not be null"); Assert.notNull(category, "Category slug must not be null"); - Page postPage = postCategoryService.pagePostBy(category.getId(), PostStatus.PUBLISHED, pageable); + Page postPage = + postCategoryService.pagePostBy(category.getId(), PostStatus.PUBLISHED, pageable); Page posts = postService.convertToDetailVo(postPage); posts.getContent().forEach(postDetailVO -> { - postDetailVO.setFormatContent(RegExUtils.replaceAll(postDetailVO.getFormatContent(), XML_INVALID_CHAR, "")); - postDetailVO.setSummary(RegExUtils.replaceAll(postDetailVO.getSummary(), XML_INVALID_CHAR, "")); + postDetailVO.setFormatContent( + RegExUtils.replaceAll(postDetailVO.getFormatContent(), XML_INVALID_CHAR, "")); + postDetailVO + .setSummary(RegExUtils.replaceAll(postDetailVO.getSummary(), XML_INVALID_CHAR, "")); }); return posts.getContent(); } diff --git a/src/main/java/run/halo/app/controller/content/ContentIndexController.java b/src/main/java/run/halo/app/controller/content/ContentIndexController.java index 7d362695da..368cf91d64 100644 --- a/src/main/java/run/halo/app/controller/content/ContentIndexController.java +++ b/src/main/java/run/halo/app/controller/content/ContentIndexController.java @@ -1,5 +1,6 @@ package run.halo.app.controller.content; +import java.util.Objects; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; @@ -12,8 +13,6 @@ import run.halo.app.service.OptionService; import run.halo.app.service.PostService; -import java.util.Objects; - /** * Blog index page controller * @@ -32,8 +31,8 @@ public class ContentIndexController { private final PostModel postModel; public ContentIndexController(PostService postService, - OptionService optionService, - PostModel postModel) { + OptionService optionService, + PostModel postModel) { this.postService = postService; this.optionService = optionService; this.postModel = postModel; @@ -43,7 +42,7 @@ public ContentIndexController(PostService postService, /** * Render blog index * - * @param p post id + * @param p post id * @param model model * @return template path: themes/{theme}/index.ftl */ @@ -64,12 +63,12 @@ public String index(Integer p, String token, Model model) { * Render blog index * * @param model model - * @param page current page number + * @param page current page number * @return template path: themes/{theme}/index.ftl */ @GetMapping(value = "page/{page}") public String index(Model model, - @PathVariable(value = "page") Integer page) { + @PathVariable(value = "page") Integer page) { return postModel.list(page, model); } } diff --git a/src/main/java/run/halo/app/controller/content/ContentSearchController.java b/src/main/java/run/halo/app/controller/content/ContentSearchController.java index d52f51c1ea..b87989fa77 100644 --- a/src/main/java/run/halo/app/controller/content/ContentSearchController.java +++ b/src/main/java/run/halo/app/controller/content/ContentSearchController.java @@ -1,5 +1,7 @@ package run.halo.app.controller.content; +import static org.springframework.data.domain.Sort.Direction.DESC; + import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; @@ -18,8 +20,6 @@ import run.halo.app.service.PostService; import run.halo.app.service.ThemeService; -import static org.springframework.data.domain.Sort.Direction.DESC; - /** * Search controller. * @@ -36,7 +36,8 @@ public class ContentSearchController { private final ThemeService themeService; - public ContentSearchController(PostService postService, OptionService optionService, ThemeService themeService) { + public ContentSearchController(PostService postService, OptionService optionService, + ThemeService themeService) { this.postService = postService; this.optionService = optionService; this.themeService = themeService; @@ -45,28 +46,28 @@ public ContentSearchController(PostService postService, OptionService optionServ /** * Render post search page. * - * @param model model + * @param model model * @param keyword keyword * @return template path : themes/{theme}/search.ftl */ @GetMapping public String search(Model model, - @RequestParam(value = "keyword") String keyword) { + @RequestParam(value = "keyword") String keyword) { return this.search(model, HtmlUtils.htmlEscape(keyword), 1, Sort.by(DESC, "createTime")); } /** * Render post search page. * - * @param model model + * @param model model * @param keyword keyword * @return template path :themes/{theme}/search.ftl */ @GetMapping(value = "page/{page}") public String search(Model model, - @RequestParam(value = "keyword") String keyword, - @PathVariable(value = "page") Integer page, - @SortDefault(sort = "createTime", direction = DESC) Sort sort) { + @RequestParam(value = "keyword") String keyword, + @PathVariable(value = "page") Integer page, + @SortDefault(sort = "createTime", direction = DESC) Sort sort) { final Pageable pageable = PageRequest.of(page - 1, optionService.getPostPageSize(), sort); final Page postPage = postService.pageBy(keyword, pageable); diff --git a/src/main/java/run/halo/app/controller/content/MainController.java b/src/main/java/run/halo/app/controller/content/MainController.java index d25acc24d5..70e2437d63 100644 --- a/src/main/java/run/halo/app/controller/content/MainController.java +++ b/src/main/java/run/halo/app/controller/content/MainController.java @@ -1,5 +1,7 @@ package run.halo.app.controller.content; +import java.io.IOException; +import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; @@ -13,9 +15,6 @@ import run.halo.app.service.UserService; import run.halo.app.utils.HaloUtils; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; - /** * Main controller. * @@ -28,12 +27,12 @@ public class MainController { /** * Index redirect uri. */ - private final static String INDEX_REDIRECT_URI = "index.html"; + private static final String INDEX_REDIRECT_URI = "index.html"; /** * Install redirect uri. */ - private final static String INSTALL_REDIRECT_URI = INDEX_REDIRECT_URI + "#install"; + private static final String INSTALL_REDIRECT_URI = INDEX_REDIRECT_URI + "#install"; private final UserService userService; @@ -41,7 +40,8 @@ public class MainController { private final HaloProperties haloProperties; - public MainController(UserService userService, OptionService optionService, HaloProperties haloProperties) { + public MainController(UserService userService, OptionService optionService, + HaloProperties haloProperties) { this.userService = userService; this.optionService = optionService; this.haloProperties = haloProperties; @@ -49,7 +49,9 @@ public MainController(UserService userService, OptionService optionService, Halo @GetMapping("${halo.admin-path:admin}") public void admin(HttpServletResponse response) throws IOException { - String adminIndexRedirectUri = HaloUtils.ensureBoth(haloProperties.getAdminPath(), HaloUtils.URL_SEPARATOR) + INDEX_REDIRECT_URI; + String adminIndexRedirectUri = + HaloUtils.ensureBoth(haloProperties.getAdminPath(), HaloUtils.URL_SEPARATOR) + + INDEX_REDIRECT_URI; response.sendRedirect(adminIndexRedirectUri); } @@ -61,13 +63,16 @@ public String version() { @GetMapping("install") public void installation(HttpServletResponse response) throws IOException { - String installRedirectUri = StringUtils.appendIfMissing(this.haloProperties.getAdminPath(), "/") + INSTALL_REDIRECT_URI; + String installRedirectUri = + StringUtils.appendIfMissing(this.haloProperties.getAdminPath(), "/") + + INSTALL_REDIRECT_URI; response.sendRedirect(installRedirectUri); } @GetMapping("avatar") public void avatar(HttpServletResponse response) throws IOException { - User user = userService.getCurrentUser().orElseThrow(() -> new ServiceException("未查询到博主信息")); + User user = + userService.getCurrentUser().orElseThrow(() -> new ServiceException("未查询到博主信息")); if (StringUtils.isNotEmpty(user.getAvatar())) { response.sendRedirect(HaloUtils.normalizeUrl(user.getAvatar())); } @@ -75,7 +80,8 @@ public void avatar(HttpServletResponse response) throws IOException { @GetMapping("logo") public void logo(HttpServletResponse response) throws IOException { - String blogLogo = optionService.getByProperty(BlogProperties.BLOG_LOGO).orElse("").toString(); + String blogLogo = + optionService.getByProperty(BlogProperties.BLOG_LOGO).orElse("").toString(); if (StringUtils.isNotEmpty(blogLogo)) { response.sendRedirect(HaloUtils.normalizeUrl(blogLogo)); } @@ -83,7 +89,8 @@ public void logo(HttpServletResponse response) throws IOException { @GetMapping("favicon.ico") public void favicon(HttpServletResponse response) throws IOException { - String favicon = optionService.getByProperty(BlogProperties.BLOG_FAVICON).orElse("").toString(); + String favicon = + optionService.getByProperty(BlogProperties.BLOG_FAVICON).orElse("").toString(); if (StringUtils.isNotEmpty(favicon)) { response.sendRedirect(HaloUtils.normalizeUrl(favicon)); } diff --git a/src/main/java/run/halo/app/controller/content/api/ArchiveController.java b/src/main/java/run/halo/app/controller/content/api/ArchiveController.java index a0da511a47..56be8444b8 100644 --- a/src/main/java/run/halo/app/controller/content/api/ArchiveController.java +++ b/src/main/java/run/halo/app/controller/content/api/ArchiveController.java @@ -1,5 +1,6 @@ package run.halo.app.controller.content.api; +import java.util.List; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @@ -7,8 +8,6 @@ import run.halo.app.model.vo.ArchiveYearVO; import run.halo.app.service.PostService; -import java.util.List; - /** * Content archive controller. * diff --git a/src/main/java/run/halo/app/controller/content/api/CategoryController.java b/src/main/java/run/halo/app/controller/content/api/CategoryController.java index 90b3189f44..88a322ca83 100644 --- a/src/main/java/run/halo/app/controller/content/api/CategoryController.java +++ b/src/main/java/run/halo/app/controller/content/api/CategoryController.java @@ -1,12 +1,19 @@ package run.halo.app.controller.content.api; +import static org.springframework.data.domain.Sort.Direction.DESC; + import io.swagger.annotations.ApiOperation; +import java.util.List; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.data.web.PageableDefault; import org.springframework.data.web.SortDefault; -import org.springframework.web.bind.annotation.*; +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.RequestParam; +import org.springframework.web.bind.annotation.RestController; import run.halo.app.model.dto.CategoryDTO; import run.halo.app.model.entity.Category; import run.halo.app.model.entity.Post; @@ -16,10 +23,6 @@ import run.halo.app.service.PostCategoryService; import run.halo.app.service.PostService; -import java.util.List; - -import static org.springframework.data.domain.Sort.Direction.DESC; - /** * Content category controller. * @@ -37,8 +40,8 @@ public class CategoryController { private final PostService postService; public CategoryController(CategoryService categoryService, - PostCategoryService postCategoryService, - PostService postService) { + PostCategoryService postCategoryService, + PostService postService) { this.categoryService = categoryService; this.postCategoryService = postCategoryService; this.postService = postService; @@ -46,8 +49,9 @@ public CategoryController(CategoryService categoryService, @GetMapping @ApiOperation("Lists categories") - public List listCategories(@SortDefault(sort = "updateTime", direction = DESC) Sort sort, - @RequestParam(name = "more", required = false, defaultValue = "false") Boolean more) { + public List listCategories( + @SortDefault(sort = "updateTime", direction = DESC) Sort sort, + @RequestParam(name = "more", required = false, defaultValue = "false") Boolean more) { if (more) { return postCategoryService.listCategoryWithPostCountDto(sort); } @@ -57,11 +61,13 @@ public List listCategories(@SortDefault(sort = "updateTim @GetMapping("{slug}/posts") @ApiOperation("Lists posts by category slug") public Page listPostsBy(@PathVariable("slug") String slug, - @PageableDefault(sort = {"topPriority", "updateTime"}, direction = DESC) Pageable pageable) { + @PageableDefault(sort = {"topPriority", "updateTime"}, direction = DESC) + Pageable pageable) { // Get category by slug Category category = categoryService.getBySlugOfNonNull(slug); - Page postPage = postCategoryService.pagePostBy(category.getId(), PostStatus.PUBLISHED, pageable); + Page postPage = + postCategoryService.pagePostBy(category.getId(), PostStatus.PUBLISHED, pageable); return postService.convertToListVo(postPage); } } diff --git a/src/main/java/run/halo/app/controller/content/api/JournalController.java b/src/main/java/run/halo/app/controller/content/api/JournalController.java index 602d8efa40..eea2f5becf 100644 --- a/src/main/java/run/halo/app/controller/content/api/JournalController.java +++ b/src/main/java/run/halo/app/controller/content/api/JournalController.java @@ -1,13 +1,23 @@ package run.halo.app.controller.content.api; +import static org.springframework.data.domain.Sort.Direction.DESC; + import io.swagger.annotations.ApiOperation; +import java.nio.charset.StandardCharsets; +import java.util.List; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.data.web.PageableDefault; import org.springframework.data.web.SortDefault; -import org.springframework.web.bind.annotation.*; +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; import org.springframework.web.util.HtmlUtils; import run.halo.app.cache.lock.CacheLock; import run.halo.app.model.dto.BaseCommentDTO; @@ -25,11 +35,6 @@ import run.halo.app.service.JournalService; import run.halo.app.service.OptionService; -import java.nio.charset.StandardCharsets; -import java.util.List; - -import static org.springframework.data.domain.Sort.Direction.DESC; - /** * Content journal controller. * @@ -48,8 +53,8 @@ public class JournalController { private final OptionService optionService; public JournalController(JournalService journalService, - JournalCommentService journalCommentService, - OptionService optionService) { + JournalCommentService journalCommentService, + OptionService optionService) { this.journalService = journalService; this.journalCommentService = journalCommentService; this.optionService = optionService; @@ -57,7 +62,8 @@ public JournalController(JournalService journalService, @GetMapping @ApiOperation("Lists journals") - public Page pageBy(@PageableDefault(sort = "createTime", direction = DESC) Pageable pageable) { + public Page pageBy( + @PageableDefault(sort = "createTime", direction = DESC) Pageable pageable) { Page journals = journalService.pageBy(JournalType.PUBLIC, pageable); return journalService.convertToCmtCountDto(journals); } @@ -70,18 +76,21 @@ public JournalDTO getBy(@PathVariable("journalId") Integer journalId) { } @GetMapping("{journalId:\\d+}/comments/top_view") - public Page listTopComments(@PathVariable("journalId") Integer journalId, - @RequestParam(name = "page", required = false, defaultValue = "0") int page, - @SortDefault(sort = "createTime", direction = DESC) Sort sort) { - return journalCommentService.pageTopCommentsBy(journalId, CommentStatus.PUBLISHED, PageRequest.of(page, optionService.getCommentPageSize(), sort)); + public Page listTopComments( + @PathVariable("journalId") Integer journalId, + @RequestParam(name = "page", required = false, defaultValue = "0") int page, + @SortDefault(sort = "createTime", direction = DESC) Sort sort) { + return journalCommentService.pageTopCommentsBy(journalId, CommentStatus.PUBLISHED, + PageRequest.of(page, optionService.getCommentPageSize(), sort)); } @GetMapping("{journalId:\\d+}/comments/{commentParentId:\\d+}/children") public List listChildrenBy(@PathVariable("journalId") Integer journalId, - @PathVariable("commentParentId") Long commentParentId, - @SortDefault(sort = "createTime", direction = DESC) Sort sort) { + @PathVariable("commentParentId") Long commentParentId, + @SortDefault(sort = "createTime", direction = DESC) Sort sort) { // Find all children comments - List postComments = journalCommentService.listChildrenBy(journalId, commentParentId, CommentStatus.PUBLISHED, sort); + List postComments = journalCommentService + .listChildrenBy(journalId, commentParentId, CommentStatus.PUBLISHED, sort); // Convert to base comment dto return journalCommentService.convertTo(postComments); } @@ -89,17 +98,19 @@ public List listChildrenBy(@PathVariable("journalId") Integer jo @GetMapping("{journalId:\\d+}/comments/tree_view") @ApiOperation("Lists comments with tree view") public Page listCommentsTree(@PathVariable("journalId") Integer journalId, - @RequestParam(name = "page", required = false, defaultValue = "0") int page, - @SortDefault(sort = "createTime", direction = DESC) Sort sort) { - return journalCommentService.pageVosBy(journalId, PageRequest.of(page, optionService.getCommentPageSize(), sort)); + @RequestParam(name = "page", required = false, defaultValue = "0") int page, + @SortDefault(sort = "createTime", direction = DESC) Sort sort) { + return journalCommentService + .pageVosBy(journalId, PageRequest.of(page, optionService.getCommentPageSize(), sort)); } @GetMapping("{journalId:\\d+}/comments/list_view") @ApiOperation("Lists comment with list view") public Page listComments(@PathVariable("journalId") Integer journalId, - @RequestParam(name = "page", required = false, defaultValue = "0") int page, - @SortDefault(sort = "createTime", direction = DESC) Sort sort) { - return journalCommentService.pageWithParentVoBy(journalId, PageRequest.of(page, optionService.getCommentPageSize(), sort)); + @RequestParam(name = "page", required = false, defaultValue = "0") int page, + @SortDefault(sort = "createTime", direction = DESC) Sort sort) { + return journalCommentService.pageWithParentVoBy(journalId, + PageRequest.of(page, optionService.getCommentPageSize(), sort)); } @PostMapping("comments") @@ -108,7 +119,8 @@ public Page listComments(@PathVariable("journalId") Int public BaseCommentDTO comment(@RequestBody JournalCommentParam journalCommentParam) { // Escape content - journalCommentParam.setContent(HtmlUtils.htmlEscape(journalCommentParam.getContent(), StandardCharsets.UTF_8.displayName())); + journalCommentParam.setContent(HtmlUtils + .htmlEscape(journalCommentParam.getContent(), StandardCharsets.UTF_8.displayName())); return journalCommentService.convertTo(journalCommentService.createBy(journalCommentParam)); } diff --git a/src/main/java/run/halo/app/controller/content/api/LinkController.java b/src/main/java/run/halo/app/controller/content/api/LinkController.java index 80d7aae461..75db791e8d 100644 --- a/src/main/java/run/halo/app/controller/content/api/LinkController.java +++ b/src/main/java/run/halo/app/controller/content/api/LinkController.java @@ -1,6 +1,9 @@ package run.halo.app.controller.content.api; +import static org.springframework.data.domain.Sort.Direction.DESC; + import io.swagger.annotations.ApiOperation; +import java.util.List; import org.springframework.data.domain.Sort; import org.springframework.data.web.SortDefault; import org.springframework.web.bind.annotation.GetMapping; @@ -10,10 +13,6 @@ import run.halo.app.model.vo.LinkTeamVO; import run.halo.app.service.LinkService; -import java.util.List; - -import static org.springframework.data.domain.Sort.Direction.DESC; - /** * Content link controller. * diff --git a/src/main/java/run/halo/app/controller/content/api/MenuController.java b/src/main/java/run/halo/app/controller/content/api/MenuController.java index c03d748c92..9824df2868 100644 --- a/src/main/java/run/halo/app/controller/content/api/MenuController.java +++ b/src/main/java/run/halo/app/controller/content/api/MenuController.java @@ -1,6 +1,9 @@ package run.halo.app.controller.content.api; +import static org.springframework.data.domain.Sort.Direction.DESC; + import io.swagger.annotations.ApiOperation; +import java.util.List; import org.springframework.data.domain.Sort; import org.springframework.data.web.SortDefault; import org.springframework.web.bind.annotation.GetMapping; @@ -10,10 +13,6 @@ import run.halo.app.model.vo.MenuVO; import run.halo.app.service.MenuService; -import java.util.List; - -import static org.springframework.data.domain.Sort.Direction.DESC; - /** * Content menu controller. * @@ -39,7 +38,8 @@ public List listAll(@SortDefault(sort = "priority", direction = DESC) S @GetMapping(value = "tree_view") @ApiOperation("Lists menus with tree view") - public List listMenusTree(@SortDefault(sort = "createTime", direction = DESC) Sort sort) { + public List listMenusTree( + @SortDefault(sort = "createTime", direction = DESC) Sort sort) { return menuService.listAsTree(sort); } } diff --git a/src/main/java/run/halo/app/controller/content/api/OptionController.java b/src/main/java/run/halo/app/controller/content/api/OptionController.java index 940890920d..6c3cbfeb12 100644 --- a/src/main/java/run/halo/app/controller/content/api/OptionController.java +++ b/src/main/java/run/halo/app/controller/content/api/OptionController.java @@ -1,17 +1,20 @@ package run.halo.app.controller.content.api; import io.swagger.annotations.ApiOperation; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; import org.springframework.http.HttpStatus; import org.springframework.util.CollectionUtils; -import org.springframework.web.bind.annotation.*; +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.RequestParam; +import org.springframework.web.bind.annotation.RestController; import run.halo.app.model.dto.OptionDTO; import run.halo.app.model.support.BaseResponse; import run.halo.app.service.OptionService; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - /** * Content option controller. * @@ -36,7 +39,8 @@ public List listAll() { @GetMapping("map_view") @ApiOperation("Lists options with map view") - public Map listAllWithMapView(@RequestParam(value = "key", required = false) List keys) { + public Map listAllWithMapView( + @RequestParam(value = "key", required = false) List keys) { if (CollectionUtils.isEmpty(keys)) { return optionService.listOptions(); } @@ -47,7 +51,8 @@ public Map listAllWithMapView(@RequestParam(value = "key", requi @GetMapping("keys/{key}") @ApiOperation("Gets option value by option key") public BaseResponse getBy(@PathVariable("key") String key) { - return BaseResponse.ok(HttpStatus.OK.getReasonPhrase(), optionService.getByKey(key).orElse(null)); + return BaseResponse + .ok(HttpStatus.OK.getReasonPhrase(), optionService.getByKey(key).orElse(null)); } diff --git a/src/main/java/run/halo/app/controller/content/api/PhotoController.java b/src/main/java/run/halo/app/controller/content/api/PhotoController.java index e6787e3ea3..87ed1bc5b7 100644 --- a/src/main/java/run/halo/app/controller/content/api/PhotoController.java +++ b/src/main/java/run/halo/app/controller/content/api/PhotoController.java @@ -1,5 +1,8 @@ package run.halo.app.controller.content.api; +import static org.springframework.data.domain.Sort.Direction.DESC; + +import java.util.List; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; @@ -12,10 +15,6 @@ import run.halo.app.model.params.PhotoQuery; import run.halo.app.service.PhotoService; -import java.util.List; - -import static org.springframework.data.domain.Sort.Direction.DESC; - /** * Content photo controller. * @@ -39,13 +38,15 @@ public PhotoController(PhotoService photoService) { * @return all of photos */ @GetMapping(value = "latest") - public List listPhotos(@SortDefault(sort = "updateTime", direction = Sort.Direction.DESC) Sort sort) { + public List listPhotos( + @SortDefault(sort = "updateTime", direction = Sort.Direction.DESC) Sort sort) { return photoService.listDtos(sort); } @GetMapping - public Page pageBy(@PageableDefault(sort = "updateTime", direction = DESC) Pageable pageable, - PhotoQuery photoQuery) { + public Page pageBy( + @PageableDefault(sort = "updateTime", direction = DESC) Pageable pageable, + PhotoQuery photoQuery) { return photoService.pageDtosBy(pageable, photoQuery); } } diff --git a/src/main/java/run/halo/app/controller/content/api/PostController.java b/src/main/java/run/halo/app/controller/content/api/PostController.java index e1570e86ed..ee24c0baa5 100644 --- a/src/main/java/run/halo/app/controller/content/api/PostController.java +++ b/src/main/java/run/halo/app/controller/content/api/PostController.java @@ -1,13 +1,23 @@ package run.halo.app.controller.content.api; +import static org.springframework.data.domain.Sort.Direction.DESC; + import io.swagger.annotations.ApiOperation; +import java.nio.charset.StandardCharsets; +import java.util.List; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.data.web.PageableDefault; import org.springframework.data.web.SortDefault; -import org.springframework.web.bind.annotation.*; +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; import org.springframework.web.util.HtmlUtils; import run.halo.app.cache.lock.CacheLock; import run.halo.app.exception.NotFoundException; @@ -18,16 +28,15 @@ import run.halo.app.model.enums.CommentStatus; import run.halo.app.model.enums.PostStatus; import run.halo.app.model.params.PostCommentParam; -import run.halo.app.model.vo.*; +import run.halo.app.model.vo.BaseCommentVO; +import run.halo.app.model.vo.BaseCommentWithParentVO; +import run.halo.app.model.vo.CommentWithHasChildrenVO; +import run.halo.app.model.vo.PostDetailVO; +import run.halo.app.model.vo.PostListVO; import run.halo.app.service.OptionService; import run.halo.app.service.PostCommentService; import run.halo.app.service.PostService; -import java.nio.charset.StandardCharsets; -import java.util.List; - -import static org.springframework.data.domain.Sort.Direction.DESC; - /** * Content post controller. * @@ -46,8 +55,8 @@ public class PostController { private final OptionService optionService; public PostController(PostService postService, - PostCommentService postCommentService, - OptionService optionService) { + PostCommentService postCommentService, + OptionService optionService) { this.postService = postService; this.postCommentService = postCommentService; this.optionService = optionService; @@ -55,7 +64,8 @@ public PostController(PostService postService, @GetMapping @ApiOperation("Lists posts") - public Page pageBy(@PageableDefault(sort = "createTime", direction = DESC) Pageable pageable) { + public Page pageBy( + @PageableDefault(sort = "createTime", direction = DESC) Pageable pageable) { Page postPage = postService.pageBy(PostStatus.PUBLISHED, pageable); return postService.convertToListVo(postPage); } @@ -63,7 +73,7 @@ public Page pageBy(@PageableDefault(sort = "createTime", direction = @PostMapping(value = "search") @ApiOperation("Lists posts by keyword") public Page pageBy(@RequestParam(value = "keyword") String keyword, - @PageableDefault(sort = "createTime", direction = DESC) Pageable pageable) { + @PageableDefault(sort = "createTime", direction = DESC) Pageable pageable) { Page postPage = postService.pageBy(keyword, pageable); return postService.convertToSimple(postPage); } @@ -71,8 +81,10 @@ public Page pageBy(@RequestParam(value = "keyword") String ke @GetMapping("{postId:\\d+}") @ApiOperation("Gets a post") public PostDetailVO getBy(@PathVariable("postId") Integer postId, - @RequestParam(value = "formatDisabled", required = false, defaultValue = "true") Boolean formatDisabled, - @RequestParam(value = "sourceDisabled", required = false, defaultValue = "false") Boolean sourceDisabled) { + @RequestParam(value = "formatDisabled", required = false, defaultValue = "true") + Boolean formatDisabled, + @RequestParam(value = "sourceDisabled", required = false, defaultValue = "false") + Boolean sourceDisabled) { PostDetailVO postDetailVO = postService.convertToDetailVo(postService.getById(postId)); if (formatDisabled) { @@ -90,27 +102,13 @@ public PostDetailVO getBy(@PathVariable("postId") Integer postId, return postDetailVO; } - @GetMapping("{postId:\\d+}/prev") - @ApiOperation("Gets previous post by current post id.") - public PostDetailVO getPrevPostBy(@PathVariable("postId") Integer postId) { - Post post = postService.getById(postId); - Post prevPost = postService.getPrevPost(post).orElseThrow(() -> new NotFoundException("查询不到该文章的信息")); - return postService.convertToDetailVo(prevPost); - } - - @GetMapping("{postId:\\d+}/next") - @ApiOperation("Gets next post by current post id.") - public PostDetailVO getNextPostBy(@PathVariable("postId") Integer postId) { - Post post = postService.getById(postId); - Post nextPost = postService.getNextPost(post).orElseThrow(() -> new NotFoundException("查询不到该文章的信息")); - return postService.convertToDetailVo(nextPost); - } - @GetMapping("/slug") @ApiOperation("Gets a post") public PostDetailVO getBy(@RequestParam("slug") String slug, - @RequestParam(value = "formatDisabled", required = false, defaultValue = "true") Boolean formatDisabled, - @RequestParam(value = "sourceDisabled", required = false, defaultValue = "false") Boolean sourceDisabled) { + @RequestParam(value = "formatDisabled", required = false, defaultValue = "true") + Boolean formatDisabled, + @RequestParam(value = "sourceDisabled", required = false, defaultValue = "false") + Boolean sourceDisabled) { PostDetailVO postDetailVO = postService.convertToDetailVo(postService.getBySlug(slug)); if (formatDisabled) { @@ -128,20 +126,39 @@ public PostDetailVO getBy(@RequestParam("slug") String slug, return postDetailVO; } + @GetMapping("{postId:\\d+}/prev") + @ApiOperation("Gets previous post by current post id.") + public PostDetailVO getPrevPostBy(@PathVariable("postId") Integer postId) { + Post post = postService.getById(postId); + Post prevPost = + postService.getPrevPost(post).orElseThrow(() -> new NotFoundException("查询不到该文章的信息")); + return postService.convertToDetailVo(prevPost); + } + + @GetMapping("{postId:\\d+}/next") + @ApiOperation("Gets next post by current post id.") + public PostDetailVO getNextPostBy(@PathVariable("postId") Integer postId) { + Post post = postService.getById(postId); + Post nextPost = + postService.getNextPost(post).orElseThrow(() -> new NotFoundException("查询不到该文章的信息")); + return postService.convertToDetailVo(nextPost); + } + @GetMapping("{postId:\\d+}/comments/top_view") public Page listTopComments(@PathVariable("postId") Integer postId, - @RequestParam(name = "page", required = false, defaultValue = "0") int page, - @SortDefault(sort = "createTime", direction = DESC) Sort sort) { - return postCommentService.pageTopCommentsBy(postId, CommentStatus.PUBLISHED, PageRequest.of(page, optionService.getCommentPageSize(), sort)); + @RequestParam(name = "page", required = false, defaultValue = "0") int page, + @SortDefault(sort = "createTime", direction = DESC) Sort sort) { + return postCommentService.pageTopCommentsBy(postId, CommentStatus.PUBLISHED, + PageRequest.of(page, optionService.getCommentPageSize(), sort)); } - @GetMapping("{postId:\\d+}/comments/{commentParentId:\\d+}/children") public List listChildrenBy(@PathVariable("postId") Integer postId, - @PathVariable("commentParentId") Long commentParentId, - @SortDefault(sort = "createTime", direction = DESC) Sort sort) { + @PathVariable("commentParentId") Long commentParentId, + @SortDefault(sort = "createTime", direction = DESC) Sort sort) { // Find all children comments - List postComments = postCommentService.listChildrenBy(postId, commentParentId, CommentStatus.PUBLISHED, sort); + List postComments = postCommentService + .listChildrenBy(postId, commentParentId, CommentStatus.PUBLISHED, sort); // Convert to base comment dto return postCommentService.convertTo(postComments); @@ -150,17 +167,19 @@ public List listChildrenBy(@PathVariable("postId") Integer postI @GetMapping("{postId:\\d+}/comments/tree_view") @ApiOperation("Lists comments with tree view") public Page listCommentsTree(@PathVariable("postId") Integer postId, - @RequestParam(name = "page", required = false, defaultValue = "0") int page, - @SortDefault(sort = "createTime", direction = DESC) Sort sort) { - return postCommentService.pageVosBy(postId, PageRequest.of(page, optionService.getCommentPageSize(), sort)); + @RequestParam(name = "page", required = false, defaultValue = "0") int page, + @SortDefault(sort = "createTime", direction = DESC) Sort sort) { + return postCommentService + .pageVosBy(postId, PageRequest.of(page, optionService.getCommentPageSize(), sort)); } @GetMapping("{postId:\\d+}/comments/list_view") @ApiOperation("Lists comment with list view") public Page listComments(@PathVariable("postId") Integer postId, - @RequestParam(name = "page", required = false, defaultValue = "0") int page, - @SortDefault(sort = "createTime", direction = DESC) Sort sort) { - return postCommentService.pageWithParentVoBy(postId, PageRequest.of(page, optionService.getCommentPageSize(), sort)); + @RequestParam(name = "page", required = false, defaultValue = "0") int page, + @SortDefault(sort = "createTime", direction = DESC) Sort sort) { + return postCommentService.pageWithParentVoBy(postId, + PageRequest.of(page, optionService.getCommentPageSize(), sort)); } @PostMapping("comments") @@ -170,7 +189,8 @@ public BaseCommentDTO comment(@RequestBody PostCommentParam postCommentParam) { postCommentService.validateCommentBlackListStatus(); // Escape content - postCommentParam.setContent(HtmlUtils.htmlEscape(postCommentParam.getContent(), StandardCharsets.UTF_8.displayName())); + postCommentParam.setContent(HtmlUtils + .htmlEscape(postCommentParam.getContent(), StandardCharsets.UTF_8.displayName())); return postCommentService.convertTo(postCommentService.createBy(postCommentParam)); } diff --git a/src/main/java/run/halo/app/controller/content/api/SheetController.java b/src/main/java/run/halo/app/controller/content/api/SheetController.java index bb1a2f2dee..efe5b71369 100644 --- a/src/main/java/run/halo/app/controller/content/api/SheetController.java +++ b/src/main/java/run/halo/app/controller/content/api/SheetController.java @@ -1,13 +1,23 @@ package run.halo.app.controller.content.api; +import static org.springframework.data.domain.Sort.Direction.DESC; + import io.swagger.annotations.ApiOperation; +import java.nio.charset.StandardCharsets; +import java.util.List; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.data.web.PageableDefault; import org.springframework.data.web.SortDefault; -import org.springframework.web.bind.annotation.*; +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; import org.springframework.web.util.HtmlUtils; import run.halo.app.cache.lock.CacheLock; import run.halo.app.model.dto.BaseCommentDTO; @@ -16,16 +26,15 @@ import run.halo.app.model.enums.CommentStatus; import run.halo.app.model.enums.PostStatus; import run.halo.app.model.params.SheetCommentParam; -import run.halo.app.model.vo.*; +import run.halo.app.model.vo.BaseCommentVO; +import run.halo.app.model.vo.BaseCommentWithParentVO; +import run.halo.app.model.vo.CommentWithHasChildrenVO; +import run.halo.app.model.vo.SheetDetailVO; +import run.halo.app.model.vo.SheetListVO; import run.halo.app.service.OptionService; import run.halo.app.service.SheetCommentService; import run.halo.app.service.SheetService; -import java.nio.charset.StandardCharsets; -import java.util.List; - -import static org.springframework.data.domain.Sort.Direction.DESC; - /** * Content sheet controller. * @@ -43,7 +52,8 @@ public class SheetController { private final OptionService optionService; - public SheetController(SheetService sheetService, SheetCommentService sheetCommentService, OptionService optionService) { + public SheetController(SheetService sheetService, SheetCommentService sheetCommentService, + OptionService optionService) { this.sheetService = sheetService; this.sheetCommentService = sheetCommentService; this.optionService = optionService; @@ -51,7 +61,8 @@ public SheetController(SheetService sheetService, SheetCommentService sheetComme @GetMapping @ApiOperation("Lists sheets") - public Page pageBy(@PageableDefault(sort = "createTime", direction = DESC) Pageable pageable) { + public Page pageBy( + @PageableDefault(sort = "createTime", direction = DESC) Pageable pageable) { Page sheetPage = sheetService.pageBy(PostStatus.PUBLISHED, pageable); return sheetService.convertToListVo(sheetPage); } @@ -59,8 +70,10 @@ public Page pageBy(@PageableDefault(sort = "createTime", direction @GetMapping("{sheetId:\\d+}") @ApiOperation("Gets a sheet") public SheetDetailVO getBy(@PathVariable("sheetId") Integer sheetId, - @RequestParam(value = "formatDisabled", required = false, defaultValue = "true") Boolean formatDisabled, - @RequestParam(value = "sourceDisabled", required = false, defaultValue = "false") Boolean sourceDisabled) { + @RequestParam(value = "formatDisabled", required = false, defaultValue = "true") + Boolean formatDisabled, + @RequestParam(value = "sourceDisabled", required = false, defaultValue = "false") + Boolean sourceDisabled) { SheetDetailVO sheetDetailVO = sheetService.convertToDetailVo(sheetService.getById(sheetId)); if (formatDisabled) { @@ -81,8 +94,10 @@ public SheetDetailVO getBy(@PathVariable("sheetId") Integer sheetId, @GetMapping("/slug") @ApiOperation("Gets a sheet by slug") public SheetDetailVO getBy(@RequestParam("slug") String slug, - @RequestParam(value = "formatDisabled", required = false, defaultValue = "true") Boolean formatDisabled, - @RequestParam(value = "sourceDisabled", required = false, defaultValue = "false") Boolean sourceDisabled) { + @RequestParam(value = "formatDisabled", required = false, defaultValue = "true") + Boolean formatDisabled, + @RequestParam(value = "sourceDisabled", required = false, defaultValue = "false") + Boolean sourceDisabled) { SheetDetailVO sheetDetailVO = sheetService.convertToDetailVo(sheetService.getBySlug(slug)); if (formatDisabled) { @@ -102,17 +117,19 @@ public SheetDetailVO getBy(@RequestParam("slug") String slug, @GetMapping("{sheetId:\\d+}/comments/top_view") public Page listTopComments(@PathVariable("sheetId") Integer sheetId, - @RequestParam(name = "page", required = false, defaultValue = "0") int page, - @SortDefault(sort = "createTime", direction = DESC) Sort sort) { - return sheetCommentService.pageTopCommentsBy(sheetId, CommentStatus.PUBLISHED, PageRequest.of(page, optionService.getCommentPageSize(), sort)); + @RequestParam(name = "page", required = false, defaultValue = "0") int page, + @SortDefault(sort = "createTime", direction = DESC) Sort sort) { + return sheetCommentService.pageTopCommentsBy(sheetId, CommentStatus.PUBLISHED, + PageRequest.of(page, optionService.getCommentPageSize(), sort)); } @GetMapping("{sheetId:\\d+}/comments/{commentParentId:\\d+}/children") public List listChildrenBy(@PathVariable("sheetId") Integer sheetId, - @PathVariable("commentParentId") Long commentParentId, - @SortDefault(sort = "createTime", direction = DESC) Sort sort) { + @PathVariable("commentParentId") Long commentParentId, + @SortDefault(sort = "createTime", direction = DESC) Sort sort) { // Find all children comments - List sheetComments = sheetCommentService.listChildrenBy(sheetId, commentParentId, CommentStatus.PUBLISHED, sort); + List sheetComments = sheetCommentService + .listChildrenBy(sheetId, commentParentId, CommentStatus.PUBLISHED, sort); // Convert to base comment dto return sheetCommentService.convertTo(sheetComments); } @@ -121,17 +138,19 @@ public List listChildrenBy(@PathVariable("sheetId") Integer shee @GetMapping("{sheetId:\\d+}/comments/tree_view") @ApiOperation("Lists comments with tree view") public Page listCommentsTree(@PathVariable("sheetId") Integer sheetId, - @RequestParam(name = "page", required = false, defaultValue = "0") int page, - @SortDefault(sort = "createTime", direction = DESC) Sort sort) { - return sheetCommentService.pageVosBy(sheetId, PageRequest.of(page, optionService.getCommentPageSize(), sort)); + @RequestParam(name = "page", required = false, defaultValue = "0") int page, + @SortDefault(sort = "createTime", direction = DESC) Sort sort) { + return sheetCommentService + .pageVosBy(sheetId, PageRequest.of(page, optionService.getCommentPageSize(), sort)); } @GetMapping("{sheetId:\\d+}/comments/list_view") @ApiOperation("Lists comment with list view") public Page listComments(@PathVariable("sheetId") Integer sheetId, - @RequestParam(name = "page", required = false, defaultValue = "0") int page, - @SortDefault(sort = "createTime", direction = DESC) Sort sort) { - return sheetCommentService.pageWithParentVoBy(sheetId, PageRequest.of(page, optionService.getCommentPageSize(), sort)); + @RequestParam(name = "page", required = false, defaultValue = "0") int page, + @SortDefault(sort = "createTime", direction = DESC) Sort sort) { + return sheetCommentService.pageWithParentVoBy(sheetId, + PageRequest.of(page, optionService.getCommentPageSize(), sort)); } @PostMapping("comments") @@ -140,7 +159,8 @@ public Page listComments(@PathVariable("sheetId") Integ public BaseCommentDTO comment(@RequestBody SheetCommentParam sheetCommentParam) { // Escape content - sheetCommentParam.setContent(HtmlUtils.htmlEscape(sheetCommentParam.getContent(), StandardCharsets.UTF_8.displayName())); + sheetCommentParam.setContent(HtmlUtils + .htmlEscape(sheetCommentParam.getContent(), StandardCharsets.UTF_8.displayName())); return sheetCommentService.convertTo(sheetCommentService.createBy(sheetCommentParam)); } } diff --git a/src/main/java/run/halo/app/controller/content/api/TagController.java b/src/main/java/run/halo/app/controller/content/api/TagController.java index f6ac35ee28..56ed94256c 100644 --- a/src/main/java/run/halo/app/controller/content/api/TagController.java +++ b/src/main/java/run/halo/app/controller/content/api/TagController.java @@ -1,13 +1,20 @@ package run.halo.app.controller.content.api; +import static org.springframework.data.domain.Sort.Direction.DESC; + import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; +import java.util.List; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.data.web.PageableDefault; import org.springframework.data.web.SortDefault; -import org.springframework.web.bind.annotation.*; +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.RequestParam; +import org.springframework.web.bind.annotation.RestController; import run.halo.app.model.dto.TagDTO; import run.halo.app.model.entity.Post; import run.halo.app.model.entity.Tag; @@ -17,10 +24,6 @@ import run.halo.app.service.PostTagService; import run.halo.app.service.TagService; -import java.util.List; - -import static org.springframework.data.domain.Sort.Direction.DESC; - /** * Content tag controller. * @@ -39,8 +42,8 @@ public class TagController { private final PostService postService; public TagController(TagService tagService, - PostTagService postTagService, - PostService postService) { + PostTagService postTagService, + PostService postService) { this.tagService = tagService; this.postTagService = postTagService; this.postService = postService; @@ -48,9 +51,10 @@ public TagController(TagService tagService, @GetMapping @ApiOperation("Lists tags") - public List listTags(@SortDefault(sort = "updateTime", direction = DESC) Sort sort, - @ApiParam("If the param is true, post count of tag will be returned") - @RequestParam(name = "more", required = false, defaultValue = "false") Boolean more) { + public List listTags( + @SortDefault(sort = "updateTime", direction = DESC) Sort sort, + @ApiParam("If the param is true, post count of tag will be returned") + @RequestParam(name = "more", required = false, defaultValue = "false") Boolean more) { if (more) { return postTagService.listTagWithCountDtos(sort); } @@ -60,12 +64,14 @@ public List listTags(@SortDefault(sort = "updateTime", directi @GetMapping("{slug}/posts") @ApiOperation("Lists posts by tag slug") public Page listPostsBy(@PathVariable("slug") String slug, - @PageableDefault(sort = {"topPriority", "updateTime"}, direction = DESC) Pageable pageable) { + @PageableDefault(sort = {"topPriority", "updateTime"}, direction = DESC) + Pageable pageable) { // Get tag by slug Tag tag = tagService.getBySlugOfNonNull(slug); // Get posts, convert and return - Page postPage = postTagService.pagePostsBy(tag.getId(), PostStatus.PUBLISHED, pageable); + Page postPage = + postTagService.pagePostsBy(tag.getId(), PostStatus.PUBLISHED, pageable); return postService.convertToListVo(postPage); } } diff --git a/src/main/java/run/halo/app/controller/content/api/ThemeController.java b/src/main/java/run/halo/app/controller/content/api/ThemeController.java index 37f8e6c572..927ab861be 100644 --- a/src/main/java/run/halo/app/controller/content/api/ThemeController.java +++ b/src/main/java/run/halo/app/controller/content/api/ThemeController.java @@ -1,6 +1,7 @@ package run.halo.app.controller.content.api; import io.swagger.annotations.ApiOperation; +import java.util.Map; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @@ -8,8 +9,6 @@ import run.halo.app.service.ThemeService; import run.halo.app.service.ThemeSettingService; -import java.util.Map; - /** * Content theme controller. * diff --git a/src/main/java/run/halo/app/controller/content/api/UserController.java b/src/main/java/run/halo/app/controller/content/api/UserController.java index d7de6ec0b7..a3bcacde7f 100644 --- a/src/main/java/run/halo/app/controller/content/api/UserController.java +++ b/src/main/java/run/halo/app/controller/content/api/UserController.java @@ -26,6 +26,7 @@ public UserController(UserService userService) { @GetMapping("profile") @ApiOperation("Gets blogger profile") public UserDTO getProfile() { - return userService.getCurrentUser().map(user -> (UserDTO) new UserDTO().convertFrom(user)).get(); + return userService.getCurrentUser().map(user -> (UserDTO) new UserDTO().convertFrom(user)) + .get(); } } diff --git a/src/main/java/run/halo/app/controller/content/model/CategoryModel.java b/src/main/java/run/halo/app/controller/content/model/CategoryModel.java index 90f27a3ae2..04bdb18cf4 100644 --- a/src/main/java/run/halo/app/controller/content/model/CategoryModel.java +++ b/src/main/java/run/halo/app/controller/content/model/CategoryModel.java @@ -1,5 +1,7 @@ package run.halo.app.controller.content.model; +import static org.springframework.data.domain.Sort.Direction.DESC; + import org.apache.commons.lang3.StringUtils; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; @@ -12,9 +14,11 @@ import run.halo.app.model.entity.Post; import run.halo.app.model.enums.PostStatus; import run.halo.app.model.vo.PostListVO; -import run.halo.app.service.*; - -import static org.springframework.data.domain.Sort.Direction.DESC; +import run.halo.app.service.CategoryService; +import run.halo.app.service.OptionService; +import run.halo.app.service.PostCategoryService; +import run.halo.app.service.PostService; +import run.halo.app.service.ThemeService; /** * Category Model. @@ -35,7 +39,9 @@ public class CategoryModel { private final OptionService optionService; - public CategoryModel(CategoryService categoryService, ThemeService themeService, PostCategoryService postCategoryService, PostService postService, OptionService optionService) { + public CategoryModel(CategoryService categoryService, ThemeService themeService, + PostCategoryService postCategoryService, PostService postService, + OptionService optionService) { this.categoryService = categoryService; this.themeService = themeService; this.postCategoryService = postCategoryService; @@ -60,8 +66,8 @@ public String list(Model model) { * List category posts. * * @param model model - * @param slug slug - * @param page current page + * @param slug slug + * @param page current page * @return template name */ public String listPost(Model model, String slug, Integer page) { @@ -70,9 +76,10 @@ public String listPost(Model model, String slug, Integer page) { CategoryDTO categoryDTO = categoryService.convertTo(category); final Pageable pageable = PageRequest.of(page - 1, - optionService.getArchivesPageSize(), - Sort.by(DESC, "topPriority", "createTime")); - Page postPage = postCategoryService.pagePostBy(category.getId(), PostStatus.PUBLISHED, pageable); + optionService.getArchivesPageSize(), + Sort.by(DESC, "topPriority", "createTime")); + Page postPage = + postCategoryService.pagePostBy(category.getId(), PostStatus.PUBLISHED, pageable); Page posts = postService.convertToListVo(postPage); // Generate meta description. diff --git a/src/main/java/run/halo/app/controller/content/model/JournalModel.java b/src/main/java/run/halo/app/controller/content/model/JournalModel.java index f37dd159d9..b1b4546498 100644 --- a/src/main/java/run/halo/app/controller/content/model/JournalModel.java +++ b/src/main/java/run/halo/app/controller/content/model/JournalModel.java @@ -1,5 +1,7 @@ package run.halo.app.controller.content.model; +import static org.springframework.data.domain.Sort.Direction.DESC; + import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; @@ -13,8 +15,6 @@ import run.halo.app.service.OptionService; import run.halo.app.service.ThemeService; -import static org.springframework.data.domain.Sort.Direction.DESC; - /** * @author ryanwang * @date 2020-02-11 @@ -29,8 +29,8 @@ public class JournalModel { private final ThemeService themeService; public JournalModel(JournalService journalService, - OptionService optionService, - ThemeService themeService) { + OptionService optionService, + ThemeService themeService) { this.journalService = journalService; this.optionService = optionService; this.themeService = themeService; @@ -38,9 +38,12 @@ public JournalModel(JournalService journalService, public String list(Integer page, Model model) { - int pageSize = optionService.getByPropertyOrDefault(SheetProperties.JOURNALS_PAGE_SIZE, Integer.class, Integer.parseInt(SheetProperties.JOURNALS_PAGE_SIZE.defaultValue())); + int pageSize = optionService + .getByPropertyOrDefault(SheetProperties.JOURNALS_PAGE_SIZE, Integer.class, + Integer.parseInt(SheetProperties.JOURNALS_PAGE_SIZE.defaultValue())); - Pageable pageable = PageRequest.of(page >= 1 ? page - 1 : page, pageSize, Sort.by(DESC, "createTime")); + Pageable pageable = + PageRequest.of(page >= 1 ? page - 1 : page, pageSize, Sort.by(DESC, "createTime")); Page journals = journalService.pageBy(JournalType.PUBLIC, pageable); diff --git a/src/main/java/run/halo/app/controller/content/model/LinkModel.java b/src/main/java/run/halo/app/controller/content/model/LinkModel.java index accc56a807..ccf040985d 100644 --- a/src/main/java/run/halo/app/controller/content/model/LinkModel.java +++ b/src/main/java/run/halo/app/controller/content/model/LinkModel.java @@ -17,7 +17,7 @@ public class LinkModel { private final OptionService optionService; public LinkModel(ThemeService themeService, - OptionService optionService) { + OptionService optionService) { this.themeService = themeService; this.optionService = optionService; } diff --git a/src/main/java/run/halo/app/controller/content/model/PhotoModel.java b/src/main/java/run/halo/app/controller/content/model/PhotoModel.java index 47fb6d6d4a..946d3244f1 100644 --- a/src/main/java/run/halo/app/controller/content/model/PhotoModel.java +++ b/src/main/java/run/halo/app/controller/content/model/PhotoModel.java @@ -1,5 +1,7 @@ package run.halo.app.controller.content.model; +import static org.springframework.data.domain.Sort.Direction.DESC; + import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; @@ -12,8 +14,6 @@ import run.halo.app.service.PhotoService; import run.halo.app.service.ThemeService; -import static org.springframework.data.domain.Sort.Direction.DESC; - /** * @author ryanwang * @date 2020-02-11 @@ -28,8 +28,8 @@ public class PhotoModel { private final OptionService optionService; public PhotoModel(PhotoService photoService, - ThemeService themeService, - OptionService optionService) { + ThemeService themeService, + OptionService optionService) { this.photoService = photoService; this.themeService = themeService; this.optionService = optionService; @@ -38,10 +38,11 @@ public PhotoModel(PhotoService photoService, public String list(Integer page, Model model) { int pageSize = optionService.getByPropertyOrDefault(SheetProperties.PHOTOS_PAGE_SIZE, - Integer.class, - Integer.parseInt(SheetProperties.PHOTOS_PAGE_SIZE.defaultValue())); + Integer.class, + Integer.parseInt(SheetProperties.PHOTOS_PAGE_SIZE.defaultValue())); - Pageable pageable = PageRequest.of(page >= 1 ? page - 1 : page, pageSize, Sort.by(DESC, "createTime")); + Pageable pageable = + PageRequest.of(page >= 1 ? page - 1 : page, pageSize, Sort.by(DESC, "createTime")); Page photos = photoService.pageBy(pageable); diff --git a/src/main/java/run/halo/app/controller/content/model/PostModel.java b/src/main/java/run/halo/app/controller/content/model/PostModel.java index cdb9cfc18a..b452a7e597 100644 --- a/src/main/java/run/halo/app/controller/content/model/PostModel.java +++ b/src/main/java/run/halo/app/controller/content/model/PostModel.java @@ -1,5 +1,10 @@ package run.halo.app.controller.content.model; +import static run.halo.app.model.support.HaloConst.POST_PASSWORD_TEMPLATE; +import static run.halo.app.model.support.HaloConst.SUFFIX_FTL; + +import java.util.List; +import java.util.stream.Collectors; import org.apache.commons.lang3.StringUtils; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; @@ -15,15 +20,18 @@ import run.halo.app.model.entity.Tag; import run.halo.app.model.enums.PostEditorType; import run.halo.app.model.enums.PostStatus; -import run.halo.app.model.support.HaloConst; import run.halo.app.model.vo.ArchiveYearVO; import run.halo.app.model.vo.PostListVO; -import run.halo.app.service.*; +import run.halo.app.service.CategoryService; +import run.halo.app.service.OptionService; +import run.halo.app.service.PostCategoryService; +import run.halo.app.service.PostMetaService; +import run.halo.app.service.PostService; +import run.halo.app.service.PostTagService; +import run.halo.app.service.TagService; +import run.halo.app.service.ThemeService; import run.halo.app.utils.MarkdownUtils; -import java.util.List; -import java.util.stream.Collectors; - /** * Post Model * @@ -52,14 +60,14 @@ public class PostModel { private final AbstractStringCacheStore cacheStore; public PostModel(PostService postService, - ThemeService themeService, - PostCategoryService postCategoryService, - CategoryService categoryService, - PostMetaService postMetaService, - PostTagService postTagService, - TagService tagService, - OptionService optionService, - AbstractStringCacheStore cacheStore) { + ThemeService themeService, + PostCategoryService postCategoryService, + CategoryService categoryService, + PostMetaService postMetaService, + PostTagService postTagService, + TagService tagService, + OptionService optionService, + AbstractStringCacheStore cacheStore) { this.postService = postService; this.themeService = themeService; this.postCategoryService = postCategoryService; @@ -75,17 +83,18 @@ public String content(Post post, String token, Model model) { if (post.getStatus().equals(PostStatus.INTIMATE) && StringUtils.isEmpty(token)) { model.addAttribute("slug", post.getSlug()); - if (themeService.templateExists(HaloConst.POST_PASSWORD_TEMPLATE + HaloConst.SUFFIX_FTL)) { - return themeService.render(HaloConst.POST_PASSWORD_TEMPLATE); + if (themeService.templateExists(POST_PASSWORD_TEMPLATE + SUFFIX_FTL)) { + return themeService.render(POST_PASSWORD_TEMPLATE); } - return "common/template/" + HaloConst.POST_PASSWORD_TEMPLATE; + return "common/template/" + POST_PASSWORD_TEMPLATE; } if (StringUtils.isEmpty(token)) { post = postService.getBy(PostStatus.PUBLISHED, post.getSlug()); } else { // verify token - String cachedToken = cacheStore.getAny(token, String.class).orElseThrow(() -> new ForbiddenException("您没有该文章的访问权限")); + String cachedToken = cacheStore.getAny(token, String.class) + .orElseThrow(() -> new ForbiddenException("您没有该文章的访问权限")); if (!cachedToken.equals(token)) { throw new ForbiddenException("您没有该文章的访问权限"); } @@ -98,8 +107,10 @@ public String content(Post post, String token, Model model) { postService.publishVisitEvent(post.getId()); - postService.getPrevPost(post).ifPresent(prevPost -> model.addAttribute("prevPost", postService.convertToDetailVo(prevPost))); - postService.getNextPost(post).ifPresent(nextPost -> model.addAttribute("nextPost", postService.convertToDetailVo(nextPost))); + postService.getPrevPost(post).ifPresent( + prevPost -> model.addAttribute("prevPost", postService.convertToDetailVo(prevPost))); + postService.getNextPost(post).ifPresent( + nextPost -> model.addAttribute("nextPost", postService.convertToDetailVo(nextPost))); List categories = postCategoryService.listCategoriesBy(post.getId()); List tags = postTagService.listTagsBy(post.getId()); @@ -109,14 +120,16 @@ public String content(Post post, String token, Model model) { if (StringUtils.isNotEmpty(post.getMetaKeywords())) { model.addAttribute("meta_keywords", post.getMetaKeywords()); } else { - model.addAttribute("meta_keywords", tags.stream().map(Tag::getName).collect(Collectors.joining(","))); + model.addAttribute("meta_keywords", + tags.stream().map(Tag::getName).collect(Collectors.joining(","))); } // Generate meta description. if (StringUtils.isNotEmpty(post.getMetaDescription())) { model.addAttribute("meta_description", post.getMetaDescription()); } else { - model.addAttribute("meta_description", postService.generateDescription(post.getFormatContent())); + model.addAttribute("meta_description", + postService.generateDescription(post.getFormatContent())); } model.addAttribute("is_post", true); @@ -126,7 +139,7 @@ public String content(Post post, String token, Model model) { model.addAttribute("metas", postMetaService.convertToMap(metas)); if (themeService.templateExists( - ThemeService.CUSTOM_POST_PREFIX + post.getTemplate() + HaloConst.SUFFIX_FTL)) { + ThemeService.CUSTOM_POST_PREFIX + post.getTemplate() + SUFFIX_FTL)) { return themeService.render(ThemeService.CUSTOM_POST_PREFIX + post.getTemplate()); } @@ -136,7 +149,7 @@ public String content(Post post, String token, Model model) { public String list(Integer page, Model model) { int pageSize = optionService.getPostPageSize(); Pageable pageable = PageRequest - .of(page >= 1 ? page - 1 : page, pageSize, postService.getPostDefaultSort()); + .of(page >= 1 ? page - 1 : page, pageSize, postService.getPostDefaultSort()); Page postPage = postService.pageBy(PostStatus.PUBLISHED, pageable); Page posts = postService.convertToListVo(postPage); @@ -151,7 +164,7 @@ public String list(Integer page, Model model) { public String archives(Integer page, Model model) { int pageSize = optionService.getArchivesPageSize(); Pageable pageable = PageRequest - .of(page >= 1 ? page - 1 : page, pageSize, Sort.by(Sort.Direction.DESC, "createTime")); + .of(page >= 1 ? page - 1 : page, pageSize, Sort.by(Sort.Direction.DESC, "createTime")); Page postPage = postService.pageBy(PostStatus.PUBLISHED, pageable); diff --git a/src/main/java/run/halo/app/controller/content/model/SheetModel.java b/src/main/java/run/halo/app/controller/content/model/SheetModel.java index b0fe5bd413..9d1551787b 100644 --- a/src/main/java/run/halo/app/controller/content/model/SheetModel.java +++ b/src/main/java/run/halo/app/controller/content/model/SheetModel.java @@ -1,5 +1,6 @@ package run.halo.app.controller.content.model; +import java.util.List; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Component; import org.springframework.ui.Model; @@ -17,8 +18,6 @@ import run.halo.app.service.ThemeService; import run.halo.app.utils.MarkdownUtils; -import java.util.List; - /** * Sheet model. * @@ -39,10 +38,10 @@ public class SheetModel { private final OptionService optionService; public SheetModel(SheetService sheetService, - SheetMetaService sheetMetaService, - AbstractStringCacheStore cacheStore, - ThemeService themeService, - OptionService optionService) { + SheetMetaService sheetMetaService, + AbstractStringCacheStore cacheStore, + ThemeService themeService, + OptionService optionService) { this.sheetService = sheetService; this.sheetMetaService = sheetMetaService; this.cacheStore = cacheStore; @@ -64,7 +63,8 @@ public String content(Sheet sheet, String token, Model model) { sheet = sheetService.getBy(PostStatus.PUBLISHED, sheet.getSlug()); } else { // verify token - String cachedToken = cacheStore.getAny(token, String.class).orElseThrow(() -> new ForbiddenException("您没有该页面的访问权限")); + String cachedToken = cacheStore.getAny(token, String.class) + .orElseThrow(() -> new ForbiddenException("您没有该页面的访问权限")); if (!cachedToken.equals(token)) { throw new ForbiddenException("您没有该页面的访问权限"); } @@ -93,7 +93,8 @@ public String content(Sheet sheet, String token, Model model) { if (StringUtils.isNotEmpty(sheet.getMetaDescription())) { model.addAttribute("meta_description", sheet.getMetaDescription()); } else { - model.addAttribute("meta_description", sheetService.generateDescription(sheet.getFormatContent())); + model.addAttribute("meta_description", + sheetService.generateDescription(sheet.getFormatContent())); } // sheet and post all can use @@ -102,7 +103,8 @@ public String content(Sheet sheet, String token, Model model) { model.addAttribute("is_sheet", true); model.addAttribute("metas", sheetMetaService.convertToMap(metas)); - if (themeService.templateExists(ThemeService.CUSTOM_SHEET_PREFIX + sheet.getTemplate() + HaloConst.SUFFIX_FTL)) { + if (themeService.templateExists( + ThemeService.CUSTOM_SHEET_PREFIX + sheet.getTemplate() + HaloConst.SUFFIX_FTL)) { return themeService.render(ThemeService.CUSTOM_SHEET_PREFIX + sheet.getTemplate()); } return themeService.render("sheet"); diff --git a/src/main/java/run/halo/app/controller/content/model/TagModel.java b/src/main/java/run/halo/app/controller/content/model/TagModel.java index 0713486715..5bffd42bff 100644 --- a/src/main/java/run/halo/app/controller/content/model/TagModel.java +++ b/src/main/java/run/halo/app/controller/content/model/TagModel.java @@ -1,5 +1,7 @@ package run.halo.app.controller.content.model; +import static org.springframework.data.domain.Sort.Direction.DESC; + import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; @@ -11,9 +13,11 @@ import run.halo.app.model.entity.Tag; import run.halo.app.model.enums.PostStatus; import run.halo.app.model.vo.PostListVO; -import run.halo.app.service.*; - -import static org.springframework.data.domain.Sort.Direction.DESC; +import run.halo.app.service.OptionService; +import run.halo.app.service.PostService; +import run.halo.app.service.PostTagService; +import run.halo.app.service.TagService; +import run.halo.app.service.ThemeService; /** * Tag Model. @@ -34,7 +38,8 @@ public class TagModel { private final ThemeService themeService; - public TagModel(TagService tagService, PostService postService, PostTagService postTagService, OptionService optionService, ThemeService themeService) { + public TagModel(TagService tagService, PostService postService, PostTagService postTagService, + OptionService optionService, ThemeService themeService) { this.tagService = tagService; this.postService = postService; this.postTagService = postTagService; @@ -54,8 +59,10 @@ public String listPost(Model model, String slug, Integer page) { final Tag tag = tagService.getBySlugOfNonNull(slug); TagDTO tagDTO = tagService.convertTo(tag); - final Pageable pageable = PageRequest.of(page - 1, optionService.getArchivesPageSize(), Sort.by(DESC, "createTime")); - Page postPage = postTagService.pagePostsBy(tag.getId(), PostStatus.PUBLISHED, pageable); + final Pageable pageable = PageRequest + .of(page - 1, optionService.getArchivesPageSize(), Sort.by(DESC, "createTime")); + Page postPage = + postTagService.pagePostsBy(tag.getId(), PostStatus.PUBLISHED, pageable); Page posts = postService.convertToListVo(postPage); model.addAttribute("is_tag", true); diff --git a/src/main/java/run/halo/app/controller/core/CommonController.java b/src/main/java/run/halo/app/controller/core/CommonController.java index 25fc0cc840..c018d1fbd1 100644 --- a/src/main/java/run/halo/app/controller/core/CommonController.java +++ b/src/main/java/run/halo/app/controller/core/CommonController.java @@ -1,5 +1,11 @@ package run.halo.app.controller.core; +import static run.halo.app.model.support.HaloConst.DEFAULT_ERROR_PATH; + +import java.util.Collections; +import java.util.Map; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; import lombok.extern.slf4j.Slf4j; import org.springframework.boot.autoconfigure.web.ErrorProperties; import org.springframework.boot.autoconfigure.web.ServerProperties; @@ -21,13 +27,6 @@ import run.halo.app.service.ThemeService; import run.halo.app.utils.FilenameUtils; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.util.Collections; -import java.util.Map; - -import static run.halo.app.model.support.HaloConst.DEFAULT_ERROR_PATH; - /** * Error page Controller * @@ -45,7 +44,8 @@ public class CommonController extends AbstractErrorController { private static final String ERROR_TEMPLATE = "error.ftl"; - private static final String COULD_NOT_RESOLVE_VIEW_WITH_NAME_PREFIX = "Could not resolve view with name '"; + private static final String COULD_NOT_RESOLVE_VIEW_WITH_NAME_PREFIX = + "Could not resolve view with name '"; private final ThemeService themeService; @@ -54,9 +54,9 @@ public class CommonController extends AbstractErrorController { private final OptionService optionService; public CommonController(ThemeService themeService, - ErrorAttributes errorAttributes, - ServerProperties serverProperties, - OptionService optionService) { + ErrorAttributes errorAttributes, + ServerProperties serverProperties, + OptionService optionService) { super(errorAttributes); this.themeService = themeService; this.errorProperties = serverProperties.getError(); @@ -70,12 +70,14 @@ public CommonController(ThemeService themeService, * @return String */ @GetMapping - public String handleError(HttpServletRequest request, HttpServletResponse response, Model model) { + public String handleError(HttpServletRequest request, HttpServletResponse response, + Model model) { handleCustomException(request); ErrorAttributeOptions options = getErrorAttributeOptions(request); - Map errorDetail = Collections.unmodifiableMap(getErrorAttributes(request, options)); + Map errorDetail = + Collections.unmodifiableMap(getErrorAttributes(request, options)); model.addAttribute("error", errorDetail); model.addAttribute("meta_keywords", optionService.getSeoKeywords()); model.addAttribute("meta_description", optionService.getSeoDescription()); @@ -138,9 +140,9 @@ private String getActualTemplatePath(@NonNull String template) { StringBuilder path = new StringBuilder(); path.append("themes/") - .append(themeService.getActivatedTheme().getFolderName()) - .append('/') - .append(FilenameUtils.getBasename(template)); + .append(themeService.getActivatedTheme().getFolderName()) + .append('/') + .append(FilenameUtils.getBasename(template)); return path.toString(); } @@ -168,11 +170,13 @@ private void handleCustomException(@NonNull HttpServletRequest request) { log.error("Caused by", rootCause); } AbstractHaloException haloException = (AbstractHaloException) rootCause; - request.setAttribute("javax.servlet.error.status_code", haloException.getStatus().value()); + request.setAttribute("javax.servlet.error.status_code", + haloException.getStatus().value()); request.setAttribute("javax.servlet.error.exception", rootCause); request.setAttribute("javax.servlet.error.message", haloException.getMessage()); } - } else if (StringUtils.startsWithIgnoreCase(throwable.getMessage(), COULD_NOT_RESOLVE_VIEW_WITH_NAME_PREFIX)) { + } else if (StringUtils.startsWithIgnoreCase(throwable.getMessage(), + COULD_NOT_RESOLVE_VIEW_WITH_NAME_PREFIX)) { log.debug("Captured an exception", throwable); request.setAttribute("javax.servlet.error.status_code", HttpStatus.NOT_FOUND.value()); @@ -221,7 +225,8 @@ private ErrorAttributeOptions getErrorAttributeOptions(HttpServletRequest reques if (include == ErrorProperties.IncludeStacktrace.ALWAYS) { return ErrorAttributeOptions.of(ErrorAttributeOptions.Include.STACK_TRACE); } - if (include == ErrorProperties.IncludeStacktrace.ON_TRACE_PARAM && getTraceParameter(request)) { + if (include == ErrorProperties.IncludeStacktrace.ON_TRACE_PARAM + && getTraceParameter(request)) { return ErrorAttributeOptions.of(ErrorAttributeOptions.Include.STACK_TRACE); } return ErrorAttributeOptions.defaults(); diff --git a/src/main/java/run/halo/app/core/CommonResultControllerAdvice.java b/src/main/java/run/halo/app/core/CommonResultControllerAdvice.java index b5d7cda461..4c1b8408a4 100644 --- a/src/main/java/run/halo/app/core/CommonResultControllerAdvice.java +++ b/src/main/java/run/halo/app/core/CommonResultControllerAdvice.java @@ -1,6 +1,6 @@ package run.halo.app.core; -import org.springframework.lang.NonNull; +import org.jetbrains.annotations.NotNull; import org.springframework.core.MethodParameter; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; @@ -9,6 +9,7 @@ import org.springframework.http.converter.json.MappingJacksonValue; import org.springframework.http.server.ServerHttpRequest; import org.springframework.http.server.ServerHttpResponse; +import org.springframework.lang.NonNull; import org.springframework.lang.Nullable; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice; @@ -23,18 +24,19 @@ public class CommonResultControllerAdvice implements ResponseBodyAdvice { @Override - public boolean supports(@NonNull MethodParameter returnType, @NonNull Class> converterType) { + public boolean supports(MethodParameter returnType, + @NotNull Class> converterType) { return AbstractJackson2HttpMessageConverter.class.isAssignableFrom(converterType); } @Override @NonNull public final Object beforeBodyWrite(@Nullable Object body, - @NonNull MethodParameter returnType, - @NonNull MediaType contentType, - @NonNull Class> converterType, - @NonNull ServerHttpRequest request, - @NonNull ServerHttpResponse response) { + @NotNull MethodParameter returnType, + @NotNull MediaType contentType, + @NotNull Class> converterType, + @NotNull ServerHttpRequest request, + @NotNull ServerHttpResponse response) { MappingJacksonValue container = getOrCreateContainer(body); // The contain body will never be null beforeBodyWriteInternal(container, contentType, returnType, request, response); @@ -46,14 +48,15 @@ public final Object beforeBodyWrite(@Nullable Object body, * additional serialization instructions) or simply cast it if already wrapped. */ private MappingJacksonValue getOrCreateContainer(Object body) { - return body instanceof MappingJacksonValue ? (MappingJacksonValue) body : new MappingJacksonValue(body); + return body instanceof MappingJacksonValue ? (MappingJacksonValue) body : + new MappingJacksonValue(body); } private void beforeBodyWriteInternal(MappingJacksonValue bodyContainer, - MediaType contentType, - MethodParameter returnType, - ServerHttpRequest request, - ServerHttpResponse response) { + MediaType contentType, + MethodParameter returnType, + ServerHttpRequest request, + ServerHttpResponse response) { // Get return body Object returnBody = bodyContainer.getValue(); diff --git a/src/main/java/run/halo/app/core/ControllerExceptionHandler.java b/src/main/java/run/halo/app/core/ControllerExceptionHandler.java index a538ebe830..2ef72b6644 100644 --- a/src/main/java/run/halo/app/core/ControllerExceptionHandler.java +++ b/src/main/java/run/halo/app/core/ControllerExceptionHandler.java @@ -1,5 +1,7 @@ package run.halo.app.core; +import java.util.Map; +import javax.validation.ConstraintViolationException; import lombok.extern.slf4j.Slf4j; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.http.HttpStatus; @@ -20,21 +22,20 @@ import run.halo.app.utils.ExceptionUtils; import run.halo.app.utils.ValidationUtils; -import javax.validation.ConstraintViolationException; -import java.util.Map; - /** * Exception handler of controller. * * @author johnniang */ -@RestControllerAdvice(value = {"run.halo.app.controller.admin.api", "run.halo.app.controller.content.api"}) +@RestControllerAdvice(value = {"run.halo.app.controller.admin.api", + "run.halo.app.controller.content.api"}) @Slf4j public class ControllerExceptionHandler { @ExceptionHandler(DataIntegrityViolationException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) - public BaseResponse handleDataIntegrityViolationException(DataIntegrityViolationException e) { + public BaseResponse handleDataIntegrityViolationException( + DataIntegrityViolationException e) { BaseResponse baseResponse = handleBaseException(e); if (e.getCause() instanceof org.hibernate.exception.ConstraintViolationException) { baseResponse = handleBaseException(e.getCause()); @@ -45,9 +46,11 @@ public BaseResponse handleDataIntegrityViolationException(DataIntegrityViolat @ExceptionHandler(MissingServletRequestParameterException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) - public BaseResponse handleMissingServletRequestParameterException(MissingServletRequestParameterException e) { + public BaseResponse handleMissingServletRequestParameterException( + MissingServletRequestParameterException e) { BaseResponse baseResponse = handleBaseException(e); - baseResponse.setMessage(String.format("请求字段缺失, 类型为 %s,名称为 %s", e.getParameterType(), e.getParameterName())); + baseResponse.setMessage( + String.format("请求字段缺失, 类型为 %s,名称为 %s", e.getParameterType(), e.getParameterName())); return baseResponse; } @@ -63,18 +66,21 @@ public BaseResponse handleConstraintViolationException(ConstraintViolationExc @ExceptionHandler(MethodArgumentNotValidException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) - public BaseResponse handleMethodArgumentNotValidException(MethodArgumentNotValidException e) { + public BaseResponse handleMethodArgumentNotValidException( + MethodArgumentNotValidException e) { BaseResponse> baseResponse = handleBaseException(e); baseResponse.setStatus(HttpStatus.BAD_REQUEST.value()); baseResponse.setMessage("字段验证错误,请完善后重试!"); - Map errMap = ValidationUtils.mapWithFieldError(e.getBindingResult().getFieldErrors()); + Map errMap = + ValidationUtils.mapWithFieldError(e.getBindingResult().getFieldErrors()); baseResponse.setData(errMap); return baseResponse; } @ExceptionHandler(HttpRequestMethodNotSupportedException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) - public BaseResponse handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) { + public BaseResponse handleHttpRequestMethodNotSupportedException( + HttpRequestMethodNotSupportedException e) { BaseResponse baseResponse = handleBaseException(e); baseResponse.setStatus(HttpStatus.BAD_REQUEST.value()); return baseResponse; @@ -82,7 +88,8 @@ public BaseResponse handleHttpRequestMethodNotSupportedException(HttpRequestM @ExceptionHandler(HttpMediaTypeNotAcceptableException.class) @ResponseStatus(HttpStatus.NOT_ACCEPTABLE) - public BaseResponse handleHttpMediaTypeNotAcceptableException(HttpMediaTypeNotAcceptableException e) { + public BaseResponse handleHttpMediaTypeNotAcceptableException( + HttpMediaTypeNotAcceptableException e) { BaseResponse baseResponse = handleBaseException(e); baseResponse.setStatus(HttpStatus.NOT_ACCEPTABLE.value()); return baseResponse; @@ -90,7 +97,8 @@ public BaseResponse handleHttpMediaTypeNotAcceptableException(HttpMediaTypeNo @ExceptionHandler(HttpMessageNotReadableException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) - public BaseResponse handleHttpMessageNotReadableException(HttpMessageNotReadableException e) { + public BaseResponse handleHttpMessageNotReadableException( + HttpMessageNotReadableException e) { BaseResponse baseResponse = handleBaseException(e); baseResponse.setStatus(HttpStatus.BAD_REQUEST.value()); baseResponse.setMessage("缺失请求主体"); diff --git a/src/main/java/run/halo/app/core/ControllerLogAop.java b/src/main/java/run/halo/app/core/ControllerLogAop.java index d884bb2e5d..e0c13b7837 100644 --- a/src/main/java/run/halo/app/core/ControllerLogAop.java +++ b/src/main/java/run/halo/app/core/ControllerLogAop.java @@ -2,6 +2,10 @@ import cn.hutool.extra.servlet.ServletUtil; import com.fasterxml.jackson.core.JsonProcessingException; +import java.lang.reflect.Method; +import java.util.Objects; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; import lombok.extern.slf4j.Slf4j; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; @@ -19,11 +23,6 @@ import org.springframework.web.multipart.MultipartFile; import run.halo.app.utils.JsonUtils; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.lang.reflect.Method; -import java.util.Objects; - /** * @author johnniang */ @@ -50,7 +49,8 @@ public Object controller(ProceedingJoinPoint joinPoint) throws Throwable { Object[] args = joinPoint.getArgs(); // Get request attribute - ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); + ServletRequestAttributes requestAttributes = + (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = Objects.requireNonNull(requestAttributes).getRequest(); final StopWatch watch = new StopWatch(request.getRequestURI()); @@ -72,12 +72,13 @@ public Object controller(ProceedingJoinPoint joinPoint) throws Throwable { return returnObj; } - private void printRequestLog(HttpServletRequest request, String clazzName, String methodName, Object[] args) throws JsonProcessingException { + private void printRequestLog(HttpServletRequest request, String clazzName, String methodName, + Object[] args) throws JsonProcessingException { log.debug("Request URL: [{}], URI: [{}], Request Method: [{}], IP: [{}]", - request.getRequestURL(), - request.getRequestURI(), - request.getMethod(), - ServletUtil.getClientIP(request)); + request.getRequestURL(), + request.getRequestURI(), + request.getMethod(), + ServletUtil.getClientIP(request)); if (args == null || !log.isDebugEnabled()) { return; @@ -85,11 +86,11 @@ private void printRequestLog(HttpServletRequest request, String clazzName, Strin boolean shouldNotLog = false; for (Object arg : args) { - if (arg == null || - arg instanceof HttpServletRequest || - arg instanceof HttpServletResponse || - arg instanceof MultipartFile || - arg.getClass().isAssignableFrom(MultipartFile[].class)) { + if (arg == null + || arg instanceof HttpServletRequest + || arg instanceof HttpServletResponse + || arg instanceof MultipartFile + || arg.getClass().isAssignableFrom(MultipartFile[].class)) { shouldNotLog = true; break; } @@ -101,8 +102,9 @@ private void printRequestLog(HttpServletRequest request, String clazzName, Strin } } - private void printResponseLog(HttpServletRequest request, String className, String methodName, Object returnObj) - throws JsonProcessingException { + private void printResponseLog(HttpServletRequest request, String className, String methodName, + Object returnObj) + throws JsonProcessingException { if (log.isDebugEnabled()) { String returnData = ""; if (returnObj != null) { diff --git a/src/main/java/run/halo/app/core/PageJacksonSerializer.java b/src/main/java/run/halo/app/core/PageJacksonSerializer.java index de694297d0..d984fb09ec 100644 --- a/src/main/java/run/halo/app/core/PageJacksonSerializer.java +++ b/src/main/java/run/halo/app/core/PageJacksonSerializer.java @@ -3,11 +3,10 @@ import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; +import java.io.IOException; import org.springframework.data.domain.Page; import run.halo.app.model.support.CommentPage; -import java.io.IOException; - /** * Custom serializer for Page object. * @@ -17,7 +16,8 @@ public class PageJacksonSerializer extends JsonSerializer { @Override - public void serialize(Page page, JsonGenerator generator, SerializerProvider serializers) throws IOException { + public void serialize(Page page, JsonGenerator generator, SerializerProvider serializers) + throws IOException { generator.writeStartObject(); generator.writeObjectField("content", page.getContent()); diff --git a/src/main/java/run/halo/app/core/freemarker/method/RandomMethod.java b/src/main/java/run/halo/app/core/freemarker/method/RandomMethod.java index b11e4f7ce5..fc1dfefc3c 100644 --- a/src/main/java/run/halo/app/core/freemarker/method/RandomMethod.java +++ b/src/main/java/run/halo/app/core/freemarker/method/RandomMethod.java @@ -5,9 +5,8 @@ import freemarker.template.SimpleNumber; import freemarker.template.TemplateMethodModelEx; import freemarker.template.TemplateModelException; -import org.springframework.stereotype.Component; - import java.util.List; +import org.springframework.stereotype.Component; /** * Freemarker template random method. diff --git a/src/main/java/run/halo/app/core/freemarker/tag/CategoryTagDirective.java b/src/main/java/run/halo/app/core/freemarker/tag/CategoryTagDirective.java index 9f04a3443d..5ee3da5639 100644 --- a/src/main/java/run/halo/app/core/freemarker/tag/CategoryTagDirective.java +++ b/src/main/java/run/halo/app/core/freemarker/tag/CategoryTagDirective.java @@ -1,7 +1,17 @@ package run.halo.app.core.freemarker.tag; +import static org.springframework.data.domain.Sort.Direction.DESC; + import freemarker.core.Environment; -import freemarker.template.*; +import freemarker.template.Configuration; +import freemarker.template.DefaultObjectWrapperBuilder; +import freemarker.template.TemplateDirectiveBody; +import freemarker.template.TemplateDirectiveModel; +import freemarker.template.TemplateException; +import freemarker.template.TemplateModel; +import java.io.IOException; +import java.util.List; +import java.util.Map; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Component; import run.halo.app.model.entity.Category; @@ -9,12 +19,6 @@ import run.halo.app.service.CategoryService; import run.halo.app.service.PostCategoryService; -import java.io.IOException; -import java.util.List; -import java.util.Map; - -import static org.springframework.data.domain.Sort.Direction.DESC; - /** * Freemarker custom tag of category. * @@ -29,30 +33,35 @@ public class CategoryTagDirective implements TemplateDirectiveModel { private final PostCategoryService postCategoryService; public CategoryTagDirective(Configuration configuration, - CategoryService categoryService, - PostCategoryService postCategoryService) { + CategoryService categoryService, + PostCategoryService postCategoryService) { this.categoryService = categoryService; this.postCategoryService = postCategoryService; configuration.setSharedVariable("categoryTag", this); } @Override - public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException { - final DefaultObjectWrapperBuilder builder = new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_25); + public void execute(Environment env, Map params, TemplateModel[] loopVars, + TemplateDirectiveBody body) throws TemplateException, IOException { + final DefaultObjectWrapperBuilder builder = + new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_25); if (params.containsKey(HaloConst.METHOD_KEY)) { String method = params.get(HaloConst.METHOD_KEY).toString(); switch (method) { case "list": - env.setVariable("categories", builder.build().wrap(postCategoryService.listCategoryWithPostCountDto(Sort.by(DESC, "createTime")))); + env.setVariable("categories", builder.build().wrap(postCategoryService + .listCategoryWithPostCountDto(Sort.by(DESC, "createTime")))); break; case "tree": - env.setVariable("categories", builder.build().wrap(categoryService.listAsTree(Sort.by(DESC, "createTime")))); + env.setVariable("categories", builder.build() + .wrap(categoryService.listAsTree(Sort.by(DESC, "createTime")))); break; case "listByPostId": Integer postId = Integer.parseInt(params.get("postId").toString()); List categories = postCategoryService.listCategoriesBy(postId); - env.setVariable("categories", builder.build().wrap(categoryService.convertTo(categories))); + env.setVariable("categories", + builder.build().wrap(categoryService.convertTo(categories))); break; case "count": env.setVariable("count", builder.build().wrap(categoryService.count())); diff --git a/src/main/java/run/halo/app/core/freemarker/tag/CommentTagDirective.java b/src/main/java/run/halo/app/core/freemarker/tag/CommentTagDirective.java index 709cb7350f..3520f7451b 100644 --- a/src/main/java/run/halo/app/core/freemarker/tag/CommentTagDirective.java +++ b/src/main/java/run/halo/app/core/freemarker/tag/CommentTagDirective.java @@ -1,7 +1,14 @@ package run.halo.app.core.freemarker.tag; import freemarker.core.Environment; -import freemarker.template.*; +import freemarker.template.Configuration; +import freemarker.template.DefaultObjectWrapperBuilder; +import freemarker.template.TemplateDirectiveBody; +import freemarker.template.TemplateDirectiveModel; +import freemarker.template.TemplateException; +import freemarker.template.TemplateModel; +import java.io.IOException; +import java.util.Map; import org.springframework.data.domain.Page; import org.springframework.stereotype.Component; import run.halo.app.model.entity.PostComment; @@ -9,9 +16,6 @@ import run.halo.app.model.support.HaloConst; import run.halo.app.service.PostCommentService; -import java.io.IOException; -import java.util.Map; - /** * Freemarker custom tag of comment. * @@ -29,16 +33,20 @@ public CommentTagDirective(Configuration configuration, PostCommentService postC } @Override - public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException { - final DefaultObjectWrapperBuilder builder = new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_25); + public void execute(Environment env, Map params, TemplateModel[] loopVars, + TemplateDirectiveBody body) throws TemplateException, IOException { + final DefaultObjectWrapperBuilder builder = + new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_25); if (params.containsKey(HaloConst.METHOD_KEY)) { String method = params.get(HaloConst.METHOD_KEY).toString(); switch (method) { case "latest": int top = Integer.parseInt(params.get("top").toString()); - Page postComments = postCommentService.pageLatest(top, CommentStatus.PUBLISHED); - env.setVariable("comments", builder.build().wrap(postCommentService.convertToWithPostVo(postComments))); + Page postComments = + postCommentService.pageLatest(top, CommentStatus.PUBLISHED); + env.setVariable("comments", + builder.build().wrap(postCommentService.convertToWithPostVo(postComments))); break; case "count": env.setVariable("count", builder.build().wrap(postCommentService.count())); diff --git a/src/main/java/run/halo/app/core/freemarker/tag/LinkTagDirective.java b/src/main/java/run/halo/app/core/freemarker/tag/LinkTagDirective.java index 5089d8ffa0..8aab9f9f37 100644 --- a/src/main/java/run/halo/app/core/freemarker/tag/LinkTagDirective.java +++ b/src/main/java/run/halo/app/core/freemarker/tag/LinkTagDirective.java @@ -1,17 +1,21 @@ package run.halo.app.core.freemarker.tag; +import static org.springframework.data.domain.Sort.Direction.DESC; + import freemarker.core.Environment; -import freemarker.template.*; +import freemarker.template.Configuration; +import freemarker.template.DefaultObjectWrapperBuilder; +import freemarker.template.TemplateDirectiveBody; +import freemarker.template.TemplateDirectiveModel; +import freemarker.template.TemplateException; +import freemarker.template.TemplateModel; +import java.io.IOException; +import java.util.Map; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Component; import run.halo.app.model.support.HaloConst; import run.halo.app.service.LinkService; -import java.io.IOException; -import java.util.Map; - -import static org.springframework.data.domain.Sort.Direction.DESC; - /** * Freemarker custom tag of link. * @@ -29,8 +33,10 @@ public LinkTagDirective(Configuration configuration, LinkService linkService) { } @Override - public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException { - final DefaultObjectWrapperBuilder builder = new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_25); + public void execute(Environment env, Map params, TemplateModel[] loopVars, + TemplateDirectiveBody body) throws TemplateException, IOException { + final DefaultObjectWrapperBuilder builder = + new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_25); if (params.containsKey(HaloConst.METHOD_KEY)) { String method = params.get(HaloConst.METHOD_KEY).toString(); @@ -42,10 +48,12 @@ public void execute(Environment env, Map params, TemplateModel[] loopVars, Templ env.setVariable("links", builder.build().wrap(linkService.listAllByRandom())); break; case "listTeams": - env.setVariable("teams", builder.build().wrap(linkService.listTeamVos(Sort.by(DESC, "createTime")))); + env.setVariable("teams", + builder.build().wrap(linkService.listTeamVos(Sort.by(DESC, "createTime")))); break; case "listTeamsByRandom": - env.setVariable("teams", builder.build().wrap(linkService.listTeamVosByRandom(Sort.by(DESC, "createTime")))); + env.setVariable("teams", builder.build() + .wrap(linkService.listTeamVosByRandom(Sort.by(DESC, "createTime")))); break; case "count": env.setVariable("count", builder.build().wrap(linkService.count())); diff --git a/src/main/java/run/halo/app/core/freemarker/tag/MenuTagDirective.java b/src/main/java/run/halo/app/core/freemarker/tag/MenuTagDirective.java index 66aee6d421..e8ae861c9c 100644 --- a/src/main/java/run/halo/app/core/freemarker/tag/MenuTagDirective.java +++ b/src/main/java/run/halo/app/core/freemarker/tag/MenuTagDirective.java @@ -1,7 +1,16 @@ package run.halo.app.core.freemarker.tag; +import static org.springframework.data.domain.Sort.Direction.DESC; + import freemarker.core.Environment; -import freemarker.template.*; +import freemarker.template.Configuration; +import freemarker.template.DefaultObjectWrapperBuilder; +import freemarker.template.TemplateDirectiveBody; +import freemarker.template.TemplateDirectiveModel; +import freemarker.template.TemplateException; +import freemarker.template.TemplateModel; +import java.io.IOException; +import java.util.Map; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Component; import run.halo.app.model.properties.PrimaryProperties; @@ -9,11 +18,6 @@ import run.halo.app.service.MenuService; import run.halo.app.service.OptionService; -import java.io.IOException; -import java.util.Map; - -import static org.springframework.data.domain.Sort.Direction.DESC; - /** * Freemarker custom tag of menu. * @@ -29,37 +33,49 @@ public class MenuTagDirective implements TemplateDirectiveModel { private final OptionService optionService; - public MenuTagDirective(Configuration configuration, MenuService menuService, OptionService optionService) { + public MenuTagDirective(Configuration configuration, MenuService menuService, + OptionService optionService) { this.menuService = menuService; this.optionService = optionService; configuration.setSharedVariable("menuTag", this); } @Override - public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException { - final DefaultObjectWrapperBuilder builder = new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_25); + public void execute(Environment env, Map params, TemplateModel[] loopVars, + TemplateDirectiveBody body) throws TemplateException, IOException { + final DefaultObjectWrapperBuilder builder = + new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_25); if (params.containsKey(HaloConst.METHOD_KEY)) { String method = params.get(HaloConst.METHOD_KEY).toString(); switch (method) { case "list": - String listTeam = optionService.getByPropertyOrDefault(PrimaryProperties.DEFAULT_MENU_TEAM, String.class, ""); - env.setVariable("menus", builder.build().wrap(menuService.listByTeam(listTeam, Sort.by(DESC, "priority")))); + String listTeam = optionService + .getByPropertyOrDefault(PrimaryProperties.DEFAULT_MENU_TEAM, String.class, + ""); + env.setVariable("menus", builder.build() + .wrap(menuService.listByTeam(listTeam, Sort.by(DESC, "priority")))); break; case "tree": - String treeTeam = optionService.getByPropertyOrDefault(PrimaryProperties.DEFAULT_MENU_TEAM, String.class, ""); - env.setVariable("menus", builder.build().wrap(menuService.listByTeamAsTree(treeTeam, Sort.by(DESC, "priority")))); + String treeTeam = optionService + .getByPropertyOrDefault(PrimaryProperties.DEFAULT_MENU_TEAM, String.class, + ""); + env.setVariable("menus", builder.build() + .wrap(menuService.listByTeamAsTree(treeTeam, Sort.by(DESC, "priority")))); break; case "listTeams": - env.setVariable("teams", builder.build().wrap(menuService.listTeamVos(Sort.by(DESC, "priority")))); + env.setVariable("teams", + builder.build().wrap(menuService.listTeamVos(Sort.by(DESC, "priority")))); break; case "listByTeam": String team = params.get("team").toString(); - env.setVariable("menus", builder.build().wrap(menuService.listByTeam(team, Sort.by(DESC, "priority")))); + env.setVariable("menus", builder.build() + .wrap(menuService.listByTeam(team, Sort.by(DESC, "priority")))); break; case "treeByTeam": String treeTeamParam = params.get("team").toString(); - env.setVariable("menus", builder.build().wrap(menuService.listByTeamAsTree(treeTeamParam, Sort.by(DESC, "priority")))); + env.setVariable("menus", builder.build().wrap( + menuService.listByTeamAsTree(treeTeamParam, Sort.by(DESC, "priority")))); break; case "count": env.setVariable("count", builder.build().wrap(menuService.count())); diff --git a/src/main/java/run/halo/app/core/freemarker/tag/PaginationTagDirective.java b/src/main/java/run/halo/app/core/freemarker/tag/PaginationTagDirective.java index 9b07ee654d..17ddd16041 100644 --- a/src/main/java/run/halo/app/core/freemarker/tag/PaginationTagDirective.java +++ b/src/main/java/run/halo/app/core/freemarker/tag/PaginationTagDirective.java @@ -1,21 +1,25 @@ package run.halo.app.core.freemarker.tag; +import static run.halo.app.model.support.HaloConst.URL_SEPARATOR; + import cn.hutool.core.util.PageUtil; import freemarker.core.Environment; -import freemarker.template.*; +import freemarker.template.Configuration; +import freemarker.template.DefaultObjectWrapperBuilder; +import freemarker.template.TemplateDirectiveBody; +import freemarker.template.TemplateDirectiveModel; +import freemarker.template.TemplateException; +import freemarker.template.TemplateModel; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; import org.springframework.stereotype.Component; import run.halo.app.model.support.HaloConst; import run.halo.app.model.support.Pagination; import run.halo.app.model.support.RainbowPage; import run.halo.app.service.OptionService; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import static run.halo.app.model.support.HaloConst.URL_SEPARATOR; - /** * @author ryanwang * @date 2020-03-07 @@ -26,14 +30,16 @@ public class PaginationTagDirective implements TemplateDirectiveModel { private final OptionService optionService; public PaginationTagDirective(Configuration configuration, - OptionService optionService) { + OptionService optionService) { this.optionService = optionService; configuration.setSharedVariable("paginationTag", this); } @Override - public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException { - final DefaultObjectWrapperBuilder builder = new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_25); + public void execute(Environment env, Map params, TemplateModel[] loopVars, + TemplateDirectiveBody body) throws TemplateException, IOException { + final DefaultObjectWrapperBuilder builder = + new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_25); if (params.containsKey(HaloConst.METHOD_KEY)) { // Get params @@ -69,15 +75,15 @@ public void execute(Environment env, Map params, TemplateModel[] loopVars, Templ case "index": nextPageFullPath.append("/page/") - .append(page + 2) - .append(pathSuffix); + .append(page + 2) + .append(pathSuffix); if (page == 1) { prevPageFullPath.append(URL_SEPARATOR); } else { prevPageFullPath.append("/page/") - .append(page) - .append(pathSuffix); + .append(page) + .append(pathSuffix); } fullPath.append("/page/"); @@ -93,25 +99,24 @@ public void execute(Environment env, Map params, TemplateModel[] loopVars, Templ case "archives": nextPageFullPath.append(URL_SEPARATOR) - .append(optionService.getArchivesPrefix()); + .append(optionService.getArchivesPrefix()); prevPageFullPath.append(URL_SEPARATOR) - .append(optionService.getArchivesPrefix()); + .append(optionService.getArchivesPrefix()); nextPageFullPath.append("/page/") - .append(page + 2) - .append(pathSuffix); + .append(page + 2) + .append(pathSuffix); if (page == 1) { - prevPageFullPath. - append(pathSuffix); + prevPageFullPath.append(pathSuffix); } else { prevPageFullPath.append("/page/") - .append(page) - .append(pathSuffix); + .append(page) + .append(pathSuffix); } fullPath.append(URL_SEPARATOR) - .append(optionService.getArchivesPrefix()); + .append(optionService.getArchivesPrefix()); fullPath.append("/page/"); @@ -127,37 +132,38 @@ public void execute(Environment env, Map params, TemplateModel[] loopVars, Templ String keyword = params.get("keyword").toString(); nextPageFullPath.append(URL_SEPARATOR) - .append("search"); + .append("search"); prevPageFullPath.append(URL_SEPARATOR) - .append("search"); + .append("search"); nextPageFullPath.append("/page/") - .append(page + 2) - .append(pathSuffix) - .append("?keyword=") - .append(keyword); + .append(page + 2) + .append(pathSuffix) + .append("?keyword=") + .append(keyword); if (page == 1) { prevPageFullPath.append(pathSuffix) - .append("?keyword=") - .append(keyword); + .append("?keyword=") + .append(keyword); } else { prevPageFullPath.append("/page/") - .append(page) - .append(pathSuffix) - .append("?keyword=") - .append(keyword); + .append(page) + .append(pathSuffix) + .append("?keyword=") + .append(keyword); } fullPath.append(URL_SEPARATOR) - .append("search"); + .append("search"); fullPath.append("/page/"); for (int current : rainbow) { RainbowPage rainbowPage = new RainbowPage(); rainbowPage.setPage(current); - rainbowPage.setFullPath(fullPath.toString() + current + pathSuffix + "?keyword=" + keyword); + rainbowPage.setFullPath( + fullPath.toString() + current + pathSuffix + "?keyword=" + keyword); rainbowPage.setIsCurrent(page + 1 == current); rainbowPages.add(rainbowPage); } @@ -166,30 +172,30 @@ public void execute(Environment env, Map params, TemplateModel[] loopVars, Templ String tagSlug = params.get("slug").toString(); nextPageFullPath.append(URL_SEPARATOR) - .append(optionService.getTagsPrefix()) - .append(URL_SEPARATOR) - .append(tagSlug); + .append(optionService.getTagsPrefix()) + .append(URL_SEPARATOR) + .append(tagSlug); prevPageFullPath.append(URL_SEPARATOR) - .append(optionService.getTagsPrefix()) - .append(URL_SEPARATOR) - .append(tagSlug); + .append(optionService.getTagsPrefix()) + .append(URL_SEPARATOR) + .append(tagSlug); nextPageFullPath.append("/page/") - .append(page + 2) - .append(pathSuffix); + .append(page + 2) + .append(pathSuffix); if (page == 1) { prevPageFullPath.append(pathSuffix); } else { prevPageFullPath.append("/page/") - .append(page) - .append(pathSuffix); + .append(page) + .append(pathSuffix); } fullPath.append(URL_SEPARATOR) - .append(optionService.getTagsPrefix()) - .append(URL_SEPARATOR) - .append(tagSlug); + .append(optionService.getTagsPrefix()) + .append(URL_SEPARATOR) + .append(tagSlug); fullPath.append("/page/"); @@ -205,30 +211,30 @@ public void execute(Environment env, Map params, TemplateModel[] loopVars, Templ String categorySlug = params.get("slug").toString(); nextPageFullPath.append(URL_SEPARATOR) - .append(optionService.getCategoriesPrefix()) - .append(URL_SEPARATOR) - .append(categorySlug); + .append(optionService.getCategoriesPrefix()) + .append(URL_SEPARATOR) + .append(categorySlug); prevPageFullPath.append(URL_SEPARATOR) - .append(optionService.getCategoriesPrefix()) - .append(URL_SEPARATOR) - .append(categorySlug); + .append(optionService.getCategoriesPrefix()) + .append(URL_SEPARATOR) + .append(categorySlug); nextPageFullPath.append("/page/") - .append(page + 2) - .append(pathSuffix); + .append(page + 2) + .append(pathSuffix); if (page == 1) { prevPageFullPath.append(pathSuffix); } else { prevPageFullPath.append("/page/") - .append(page) - .append(pathSuffix); + .append(page) + .append(pathSuffix); } fullPath.append(URL_SEPARATOR) - .append(optionService.getCategoriesPrefix()) - .append(URL_SEPARATOR) - .append(categorySlug); + .append(optionService.getCategoriesPrefix()) + .append(URL_SEPARATOR) + .append(categorySlug); fullPath.append("/page/"); @@ -243,24 +249,24 @@ public void execute(Environment env, Map params, TemplateModel[] loopVars, Templ case "photos": nextPageFullPath.append(URL_SEPARATOR) - .append(optionService.getPhotosPrefix()); + .append(optionService.getPhotosPrefix()); prevPageFullPath.append(URL_SEPARATOR) - .append(optionService.getPhotosPrefix()); + .append(optionService.getPhotosPrefix()); nextPageFullPath.append("/page/") - .append(page + 2) - .append(pathSuffix); + .append(page + 2) + .append(pathSuffix); if (page == 1) { prevPageFullPath.append(pathSuffix); } else { prevPageFullPath.append("/page/") - .append(page) - .append(pathSuffix); + .append(page) + .append(pathSuffix); } fullPath.append(URL_SEPARATOR) - .append(optionService.getPhotosPrefix()); + .append(optionService.getPhotosPrefix()); fullPath.append("/page/"); @@ -275,24 +281,24 @@ public void execute(Environment env, Map params, TemplateModel[] loopVars, Templ case "journals": nextPageFullPath.append(URL_SEPARATOR) - .append(optionService.getJournalsPrefix()); + .append(optionService.getJournalsPrefix()); prevPageFullPath.append(URL_SEPARATOR) - .append(optionService.getJournalsPrefix()); + .append(optionService.getJournalsPrefix()); nextPageFullPath.append("/page/") - .append(page + 2) - .append(pathSuffix); + .append(page + 2) + .append(pathSuffix); if (page == 1) { prevPageFullPath.append(pathSuffix); } else { prevPageFullPath.append("/page/") - .append(page) - .append(pathSuffix); + .append(page) + .append(pathSuffix); } fullPath.append(URL_SEPARATOR) - .append(optionService.getJournalsPrefix()); + .append(optionService.getJournalsPrefix()); fullPath.append("/page/"); diff --git a/src/main/java/run/halo/app/core/freemarker/tag/PhotoTagDirective.java b/src/main/java/run/halo/app/core/freemarker/tag/PhotoTagDirective.java index 0280e90e2d..4ff20a92ea 100644 --- a/src/main/java/run/halo/app/core/freemarker/tag/PhotoTagDirective.java +++ b/src/main/java/run/halo/app/core/freemarker/tag/PhotoTagDirective.java @@ -1,17 +1,21 @@ package run.halo.app.core.freemarker.tag; +import static org.springframework.data.domain.Sort.Direction.DESC; + import freemarker.core.Environment; -import freemarker.template.*; +import freemarker.template.Configuration; +import freemarker.template.DefaultObjectWrapperBuilder; +import freemarker.template.TemplateDirectiveBody; +import freemarker.template.TemplateDirectiveModel; +import freemarker.template.TemplateException; +import freemarker.template.TemplateModel; +import java.io.IOException; +import java.util.Map; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Component; import run.halo.app.model.support.HaloConst; import run.halo.app.service.PhotoService; -import java.io.IOException; -import java.util.Map; - -import static org.springframework.data.domain.Sort.Direction.DESC; - /** * Freemarker custom tag of photo. * @@ -29,8 +33,10 @@ public PhotoTagDirective(Configuration configuration, PhotoService photoService) } @Override - public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException { - final DefaultObjectWrapperBuilder builder = new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_25); + public void execute(Environment env, Map params, TemplateModel[] loopVars, + TemplateDirectiveBody body) throws TemplateException, IOException { + final DefaultObjectWrapperBuilder builder = + new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_25); if (params.containsKey(HaloConst.METHOD_KEY)) { String method = params.get(HaloConst.METHOD_KEY).toString(); @@ -39,11 +45,13 @@ public void execute(Environment env, Map params, TemplateModel[] loopVars, Templ env.setVariable("photos", builder.build().wrap(photoService.listAll())); break; case "listTeams": - env.setVariable("teams", builder.build().wrap(photoService.listTeamVos(Sort.by(DESC, "createTime")))); + env.setVariable("teams", builder.build() + .wrap(photoService.listTeamVos(Sort.by(DESC, "createTime")))); break; case "listByTeam": String team = params.get("team").toString(); - env.setVariable("photos", builder.build().wrap(photoService.listByTeam(team, Sort.by(DESC, "createTime")))); + env.setVariable("photos", builder.build() + .wrap(photoService.listByTeam(team, Sort.by(DESC, "createTime")))); break; case "count": env.setVariable("count", builder.build().wrap(photoService.count())); diff --git a/src/main/java/run/halo/app/core/freemarker/tag/PostTagDirective.java b/src/main/java/run/halo/app/core/freemarker/tag/PostTagDirective.java index cb579b5ee2..8b875f71b4 100644 --- a/src/main/java/run/halo/app/core/freemarker/tag/PostTagDirective.java +++ b/src/main/java/run/halo/app/core/freemarker/tag/PostTagDirective.java @@ -1,7 +1,15 @@ package run.halo.app.core.freemarker.tag; import freemarker.core.Environment; -import freemarker.template.*; +import freemarker.template.Configuration; +import freemarker.template.DefaultObjectWrapperBuilder; +import freemarker.template.TemplateDirectiveBody; +import freemarker.template.TemplateDirectiveModel; +import freemarker.template.TemplateException; +import freemarker.template.TemplateModel; +import java.io.IOException; +import java.util.List; +import java.util.Map; import org.springframework.stereotype.Component; import run.halo.app.model.entity.Post; import run.halo.app.model.enums.PostStatus; @@ -10,10 +18,6 @@ import run.halo.app.service.PostService; import run.halo.app.service.PostTagService; -import java.io.IOException; -import java.util.List; -import java.util.Map; - /** * Freemarker custom tag of post. * @@ -30,9 +34,9 @@ public class PostTagDirective implements TemplateDirectiveModel { private final PostCategoryService postCategoryService; public PostTagDirective(Configuration configuration, - PostService postService, - PostTagService postTagService, - PostCategoryService postCategoryService) { + PostService postService, + PostTagService postTagService, + PostCategoryService postCategoryService) { this.postService = postService; this.postTagService = postTagService; this.postCategoryService = postCategoryService; @@ -40,44 +44,57 @@ public PostTagDirective(Configuration configuration, } @Override - public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException { - final DefaultObjectWrapperBuilder builder = new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_25); + public void execute(Environment env, Map params, TemplateModel[] loopVars, + TemplateDirectiveBody body) throws TemplateException, IOException { + final DefaultObjectWrapperBuilder builder = + new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_25); if (params.containsKey(HaloConst.METHOD_KEY)) { String method = params.get(HaloConst.METHOD_KEY).toString(); switch (method) { case "latest": int top = Integer.parseInt(params.get("top").toString()); - env.setVariable("posts", builder.build().wrap(postService.convertToListVo(postService.listLatest(top)))); + env.setVariable("posts", builder.build() + .wrap(postService.convertToListVo(postService.listLatest(top)))); break; case "count": - env.setVariable("count", builder.build().wrap(postService.countByStatus(PostStatus.PUBLISHED))); + env.setVariable("count", + builder.build().wrap(postService.countByStatus(PostStatus.PUBLISHED))); break; case "archiveYear": - env.setVariable("archives", builder.build().wrap(postService.listYearArchives())); + env.setVariable("archives", + builder.build().wrap(postService.listYearArchives())); break; case "archiveMonth": - env.setVariable("archives", builder.build().wrap(postService.listMonthArchives())); + env.setVariable("archives", + builder.build().wrap(postService.listMonthArchives())); break; case "archive": String type = params.get("type").toString(); - env.setVariable("archives", builder.build().wrap("year".equals(type) ? postService.listYearArchives() : postService.listMonthArchives())); + env.setVariable("archives", builder.build().wrap( + "year".equals(type) ? postService.listYearArchives() : + postService.listMonthArchives())); break; case "listByCategoryId": Integer categoryId = Integer.parseInt(params.get("categoryId").toString()); - env.setVariable("posts", builder.build().wrap(postService.convertToListVo(postCategoryService.listPostBy(categoryId, PostStatus.PUBLISHED)))); + env.setVariable("posts", builder.build().wrap(postService.convertToListVo( + postCategoryService.listPostBy(categoryId, PostStatus.PUBLISHED)))); break; case "listByCategorySlug": String categorySlug = params.get("categorySlug").toString(); - List posts = postCategoryService.listPostBy(categorySlug, PostStatus.PUBLISHED); - env.setVariable("posts", builder.build().wrap(postService.convertToListVo(posts))); + List posts = + postCategoryService.listPostBy(categorySlug, PostStatus.PUBLISHED); + env.setVariable("posts", + builder.build().wrap(postService.convertToListVo(posts))); break; case "listByTagId": Integer tagId = Integer.parseInt(params.get("tagId").toString()); - env.setVariable("posts", builder.build().wrap(postService.convertToListVo(postTagService.listPostsBy(tagId, PostStatus.PUBLISHED)))); + env.setVariable("posts", builder.build().wrap(postService + .convertToListVo(postTagService.listPostsBy(tagId, PostStatus.PUBLISHED)))); break; case "listByTagSlug": String tagSlug = params.get("tagSlug").toString(); - env.setVariable("posts", builder.build().wrap(postService.convertToListVo(postTagService.listPostsBy(tagSlug, PostStatus.PUBLISHED)))); + env.setVariable("posts", builder.build().wrap(postService.convertToListVo( + postTagService.listPostsBy(tagSlug, PostStatus.PUBLISHED)))); break; default: break; diff --git a/src/main/java/run/halo/app/core/freemarker/tag/TagTagDirective.java b/src/main/java/run/halo/app/core/freemarker/tag/TagTagDirective.java index 1c33269626..09fa96ffc2 100644 --- a/src/main/java/run/halo/app/core/freemarker/tag/TagTagDirective.java +++ b/src/main/java/run/halo/app/core/freemarker/tag/TagTagDirective.java @@ -1,7 +1,17 @@ package run.halo.app.core.freemarker.tag; +import static org.springframework.data.domain.Sort.Direction.DESC; + import freemarker.core.Environment; -import freemarker.template.*; +import freemarker.template.Configuration; +import freemarker.template.DefaultObjectWrapperBuilder; +import freemarker.template.TemplateDirectiveBody; +import freemarker.template.TemplateDirectiveModel; +import freemarker.template.TemplateException; +import freemarker.template.TemplateModel; +import java.io.IOException; +import java.util.List; +import java.util.Map; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Component; import run.halo.app.model.entity.Tag; @@ -9,12 +19,6 @@ import run.halo.app.service.PostTagService; import run.halo.app.service.TagService; -import java.io.IOException; -import java.util.List; -import java.util.Map; - -import static org.springframework.data.domain.Sort.Direction.DESC; - /** * Freemarker custom tag of tag. * @@ -29,22 +33,25 @@ public class TagTagDirective implements TemplateDirectiveModel { private final PostTagService postTagService; public TagTagDirective(Configuration configuration, - TagService tagService, - PostTagService postTagService) { + TagService tagService, + PostTagService postTagService) { this.tagService = tagService; this.postTagService = postTagService; configuration.setSharedVariable("tagTag", this); } @Override - public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException { - final DefaultObjectWrapperBuilder builder = new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_25); + public void execute(Environment env, Map params, TemplateModel[] loopVars, + TemplateDirectiveBody body) throws TemplateException, IOException { + final DefaultObjectWrapperBuilder builder = + new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_25); if (params.containsKey(HaloConst.METHOD_KEY)) { String method = params.get(HaloConst.METHOD_KEY).toString(); switch (method) { case "list": - env.setVariable("tags", builder.build().wrap(postTagService.listTagWithCountDtos(Sort.by(DESC, "createTime")))); + env.setVariable("tags", builder.build() + .wrap(postTagService.listTagWithCountDtos(Sort.by(DESC, "createTime")))); break; case "listByPostId": Integer postId = Integer.parseInt(params.get("postId").toString()); diff --git a/src/main/java/run/halo/app/core/freemarker/tag/ToolTagDirective.java b/src/main/java/run/halo/app/core/freemarker/tag/ToolTagDirective.java index 22fae23ca8..be3886886a 100644 --- a/src/main/java/run/halo/app/core/freemarker/tag/ToolTagDirective.java +++ b/src/main/java/run/halo/app/core/freemarker/tag/ToolTagDirective.java @@ -3,12 +3,16 @@ import cn.hutool.core.util.PageUtil; import cn.hutool.core.util.RandomUtil; import freemarker.core.Environment; -import freemarker.template.*; -import org.springframework.stereotype.Component; -import run.halo.app.model.support.HaloConst; - +import freemarker.template.Configuration; +import freemarker.template.DefaultObjectWrapperBuilder; +import freemarker.template.TemplateDirectiveBody; +import freemarker.template.TemplateDirectiveModel; +import freemarker.template.TemplateException; +import freemarker.template.TemplateModel; import java.io.IOException; import java.util.Map; +import org.springframework.stereotype.Component; +import run.halo.app.model.support.HaloConst; /** * Freemarker custom tag of tools. @@ -24,8 +28,10 @@ public ToolTagDirective(Configuration configuration) { } @Override - public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException { - final DefaultObjectWrapperBuilder builder = new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_25); + public void execute(Environment env, Map params, TemplateModel[] loopVars, + TemplateDirectiveBody body) throws TemplateException, IOException { + final DefaultObjectWrapperBuilder builder = + new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_25); if (params.containsKey(HaloConst.METHOD_KEY)) { String method = params.get(HaloConst.METHOD_KEY).toString(); @@ -34,7 +40,8 @@ public void execute(Environment env, Map params, TemplateModel[] loopVars, Templ int page = Integer.parseInt(params.get("page").toString()); int total = Integer.parseInt(params.get("total").toString()); int display = Integer.parseInt(params.get("display").toString()); - env.setVariable("numbers", builder.build().wrap(PageUtil.rainbow(page, total, display))); + env.setVariable("numbers", + builder.build().wrap(PageUtil.rainbow(page, total, display))); break; case "random": int min = Integer.parseInt(params.get("min").toString()); diff --git a/src/main/java/run/halo/app/event/StaticStorageChangedEvent.java b/src/main/java/run/halo/app/event/StaticStorageChangedEvent.java index 538f02b3aa..70784700d7 100644 --- a/src/main/java/run/halo/app/event/StaticStorageChangedEvent.java +++ b/src/main/java/run/halo/app/event/StaticStorageChangedEvent.java @@ -1,10 +1,9 @@ package run.halo.app.event; +import java.nio.file.Path; import lombok.Getter; import org.springframework.context.ApplicationEvent; -import java.nio.file.Path; - /** * @author ryanwang * @date 2020-03-24 @@ -18,7 +17,7 @@ public class StaticStorageChangedEvent extends ApplicationEvent { * Create a new {@code ApplicationEvent}. * * @param source the object on which the event initially occurred or with - * which the event is associated (never {@code null}) + * which the event is associated (never {@code null}) */ public StaticStorageChangedEvent(Object source, Path staticPath) { super(source); diff --git a/src/main/java/run/halo/app/event/comment/AbstractCommentBaseEvent.java b/src/main/java/run/halo/app/event/comment/AbstractCommentBaseEvent.java index 051231fda7..a5cf8238da 100644 --- a/src/main/java/run/halo/app/event/comment/AbstractCommentBaseEvent.java +++ b/src/main/java/run/halo/app/event/comment/AbstractCommentBaseEvent.java @@ -20,7 +20,7 @@ public abstract class AbstractCommentBaseEvent extends ApplicationEvent { /** * Create a new ApplicationEvent. * - * @param source the object on which the event initially occurred (never {@code null}) + * @param source the object on which the event initially occurred (never {@code null}) * @param commentId comment id */ public AbstractCommentBaseEvent(Object source, @NonNull Long commentId) { diff --git a/src/main/java/run/halo/app/event/comment/CommentNewEvent.java b/src/main/java/run/halo/app/event/comment/CommentNewEvent.java index 6231cb15f3..9162ad1045 100644 --- a/src/main/java/run/halo/app/event/comment/CommentNewEvent.java +++ b/src/main/java/run/halo/app/event/comment/CommentNewEvent.java @@ -13,7 +13,7 @@ public class CommentNewEvent extends AbstractCommentBaseEvent { /** * Create a new ApplicationEvent. * - * @param source the object on which the event initially occurred (never {@code null}) + * @param source the object on which the event initially occurred (never {@code null}) * @param commentId comment id */ public CommentNewEvent(Object source, @NonNull Long commentId) { diff --git a/src/main/java/run/halo/app/event/comment/CommentReplyEvent.java b/src/main/java/run/halo/app/event/comment/CommentReplyEvent.java index f5af5217b9..cc911b9854 100644 --- a/src/main/java/run/halo/app/event/comment/CommentReplyEvent.java +++ b/src/main/java/run/halo/app/event/comment/CommentReplyEvent.java @@ -13,7 +13,7 @@ public class CommentReplyEvent extends AbstractCommentBaseEvent { /** * Create a new ApplicationEvent. * - * @param source the object on which the event initially occurred (never {@code null}) + * @param source the object on which the event initially occurred (never {@code null}) * @param commentId comment id */ public CommentReplyEvent(Object source, @NonNull Long commentId) { diff --git a/src/main/java/run/halo/app/event/logger/LogEvent.java b/src/main/java/run/halo/app/event/logger/LogEvent.java index 2f26c258d3..2a14fc61b4 100644 --- a/src/main/java/run/halo/app/event/logger/LogEvent.java +++ b/src/main/java/run/halo/app/event/logger/LogEvent.java @@ -17,7 +17,7 @@ public class LogEvent extends ApplicationEvent { /** * Create a new ApplicationEvent. * - * @param source the object on which the event initially occurred (never {@code null}) + * @param source the object on which the event initially occurred (never {@code null}) * @param logParam login param */ public LogEvent(Object source, LogParam logParam) { diff --git a/src/main/java/run/halo/app/event/post/AbstractVisitEvent.java b/src/main/java/run/halo/app/event/post/AbstractVisitEvent.java index 1e93f2a21d..13f8483799 100644 --- a/src/main/java/run/halo/app/event/post/AbstractVisitEvent.java +++ b/src/main/java/run/halo/app/event/post/AbstractVisitEvent.java @@ -18,7 +18,7 @@ public abstract class AbstractVisitEvent extends ApplicationEvent { * Create a new ApplicationEvent. * * @param source the object on which the event initially occurred (never {@code null}) - * @param id id + * @param id id */ public AbstractVisitEvent(@NonNull Object source, @NonNull Integer id) { super(source); diff --git a/src/main/java/run/halo/app/event/post/SheetVisitEvent.java b/src/main/java/run/halo/app/event/post/SheetVisitEvent.java index 73f1dc6643..9aafb40bc4 100644 --- a/src/main/java/run/halo/app/event/post/SheetVisitEvent.java +++ b/src/main/java/run/halo/app/event/post/SheetVisitEvent.java @@ -11,7 +11,7 @@ public class SheetVisitEvent extends AbstractVisitEvent { /** * Create a new ApplicationEvent. * - * @param source the object on which the event initially occurred (never {@code null}) + * @param source the object on which the event initially occurred (never {@code null}) * @param sheetId sheet id must not be null */ public SheetVisitEvent(Object source, Integer sheetId) { diff --git a/src/main/java/run/halo/app/factory/StringToEnumConverterFactory.java b/src/main/java/run/halo/app/factory/StringToEnumConverterFactory.java index 8e7e040126..20a87cc1c2 100644 --- a/src/main/java/run/halo/app/factory/StringToEnumConverterFactory.java +++ b/src/main/java/run/halo/app/factory/StringToEnumConverterFactory.java @@ -1,8 +1,8 @@ package run.halo.app.factory; -import org.springframework.lang.NonNull; import org.springframework.core.convert.converter.Converter; import org.springframework.core.convert.converter.ConverterFactory; +import org.springframework.lang.NonNull; import org.springframework.stereotype.Component; /** @@ -19,7 +19,7 @@ public > Converter getConverter(@NonNull Class t } private static class StringToEnumConverter> - implements Converter { + implements Converter { private final Class enumType; diff --git a/src/main/java/run/halo/app/filter/CorsFilter.java b/src/main/java/run/halo/app/filter/CorsFilter.java index 978884f555..9883ee6b6a 100644 --- a/src/main/java/run/halo/app/filter/CorsFilter.java +++ b/src/main/java/run/halo/app/filter/CorsFilter.java @@ -1,23 +1,22 @@ package run.halo.app.filter; -import org.apache.commons.lang3.StringUtils; -import org.springframework.core.Ordered; -import org.springframework.core.annotation.Order; -import org.springframework.http.HttpHeaders; -import org.springframework.stereotype.Component; -import org.springframework.web.cors.CorsUtils; -import org.springframework.web.filter.GenericFilterBean; +import static run.halo.app.model.support.HaloConst.ADMIN_TOKEN_HEADER_NAME; +import static run.halo.app.model.support.HaloConst.API_ACCESS_KEY_HEADER_NAME; +import java.io.IOException; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import java.io.IOException; - -import static run.halo.app.model.support.HaloConst.ADMIN_TOKEN_HEADER_NAME; -import static run.halo.app.model.support.HaloConst.API_ACCESS_KEY_HEADER_NAME; +import org.apache.commons.lang3.StringUtils; +import org.springframework.core.Ordered; +import org.springframework.core.annotation.Order; +import org.springframework.http.HttpHeaders; +import org.springframework.stereotype.Component; +import org.springframework.web.cors.CorsUtils; +import org.springframework.web.filter.GenericFilterBean; /** * Filter for CORS. @@ -28,20 +27,25 @@ @Order(Ordered.HIGHEST_PRECEDENCE + 10) public class CorsFilter extends GenericFilterBean { - private final static String ALLOW_HEADERS = StringUtils.joinWith(",", HttpHeaders.CONTENT_TYPE, ADMIN_TOKEN_HEADER_NAME, API_ACCESS_KEY_HEADER_NAME); + private static final String ALLOW_HEADERS = StringUtils + .joinWith(",", HttpHeaders.CONTENT_TYPE, ADMIN_TOKEN_HEADER_NAME, + API_ACCESS_KEY_HEADER_NAME); @Override - public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) + throws IOException, ServletException { HttpServletRequest httpServletRequest = (HttpServletRequest) request; HttpServletResponse httpServletResponse = (HttpServletResponse) response; // Set customized header String originHeaderValue = httpServletRequest.getHeader(HttpHeaders.ORIGIN); if (StringUtils.isNotBlank(originHeaderValue)) { - httpServletResponse.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, originHeaderValue); + httpServletResponse + .setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, originHeaderValue); } httpServletResponse.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, ALLOW_HEADERS); - httpServletResponse.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET, POST, PUT, DELETE, OPTIONS"); + httpServletResponse + .setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET, POST, PUT, DELETE, OPTIONS"); httpServletResponse.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"); httpServletResponse.setHeader(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "3600"); diff --git a/src/main/java/run/halo/app/filter/LogFilter.java b/src/main/java/run/halo/app/filter/LogFilter.java index 538496ea82..0294f640e0 100644 --- a/src/main/java/run/halo/app/filter/LogFilter.java +++ b/src/main/java/run/halo/app/filter/LogFilter.java @@ -1,18 +1,17 @@ package run.halo.app.filter; import cn.hutool.extra.servlet.ServletUtil; +import java.io.IOException; +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; import lombok.extern.slf4j.Slf4j; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; import org.springframework.web.filter.OncePerRequestFilter; -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; - /** * Filter for logging. * @@ -24,14 +23,15 @@ public class LogFilter extends OncePerRequestFilter { @Override - protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, + FilterChain filterChain) throws ServletException, IOException { final String remoteAddr = ServletUtil.getClientIP(request); log.debug("Starting url: [{}], method: [{}], ip: [{}]", - request.getRequestURL(), - request.getMethod(), - remoteAddr); + request.getRequestURL(), + request.getMethod(), + remoteAddr); // Set start time final long startTime = System.currentTimeMillis(); @@ -40,10 +40,10 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse filterChain.doFilter(request, response); log.debug("Ending url: [{}], method: [{}], ip: [{}], status: [{}], usage: [{}] ms", - request.getRequestURL(), - request.getMethod(), - remoteAddr, - response.getStatus(), - System.currentTimeMillis() - startTime); + request.getRequestURL(), + request.getMethod(), + remoteAddr, + response.getStatus(), + System.currentTimeMillis() - startTime); } } diff --git a/src/main/java/run/halo/app/handler/file/AliOssFileHandler.java b/src/main/java/run/halo/app/handler/file/AliOssFileHandler.java index 2c10431245..3445ad4da7 100644 --- a/src/main/java/run/halo/app/handler/file/AliOssFileHandler.java +++ b/src/main/java/run/halo/app/handler/file/AliOssFileHandler.java @@ -1,13 +1,16 @@ package run.halo.app.handler.file; +import static run.halo.app.model.support.HaloConst.URL_SEPARATOR; + import com.aliyun.oss.OSS; import com.aliyun.oss.OSSClientBuilder; import com.aliyun.oss.model.DeleteObjectsRequest; import com.aliyun.oss.model.PutObjectResult; +import java.util.Objects; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; -import org.springframework.lang.NonNull; import org.springframework.http.MediaType; +import org.springframework.lang.NonNull; import org.springframework.stereotype.Component; import org.springframework.util.Assert; import org.springframework.web.multipart.MultipartFile; @@ -19,10 +22,6 @@ import run.halo.app.utils.FilenameUtils; import run.halo.app.utils.ImageUtils; -import java.util.Objects; - -import static run.halo.app.model.support.HaloConst.URL_SEPARATOR; - /** * Ali oss file handler. * @@ -45,15 +44,24 @@ public AliOssFileHandler(OptionService optionService) { Assert.notNull(file, "Multipart file must not be null"); // Get config - String protocol = optionService.getByPropertyOfNonNull(AliOssProperties.OSS_PROTOCOL).toString(); - String domain = optionService.getByPropertyOrDefault(AliOssProperties.OSS_DOMAIN, String.class, ""); - String source = optionService.getByPropertyOrDefault(AliOssProperties.OSS_SOURCE, String.class, ""); - String endPoint = optionService.getByPropertyOfNonNull(AliOssProperties.OSS_ENDPOINT).toString(); - String accessKey = optionService.getByPropertyOfNonNull(AliOssProperties.OSS_ACCESS_KEY).toString(); - String accessSecret = optionService.getByPropertyOfNonNull(AliOssProperties.OSS_ACCESS_SECRET).toString(); - String bucketName = optionService.getByPropertyOfNonNull(AliOssProperties.OSS_BUCKET_NAME).toString(); - String styleRule = optionService.getByPropertyOrDefault(AliOssProperties.OSS_STYLE_RULE, String.class, ""); - String thumbnailStyleRule = optionService.getByPropertyOrDefault(AliOssProperties.OSS_THUMBNAIL_STYLE_RULE, String.class, ""); + String protocol = + optionService.getByPropertyOfNonNull(AliOssProperties.OSS_PROTOCOL).toString(); + String domain = + optionService.getByPropertyOrDefault(AliOssProperties.OSS_DOMAIN, String.class, ""); + String source = + optionService.getByPropertyOrDefault(AliOssProperties.OSS_SOURCE, String.class, ""); + String endPoint = + optionService.getByPropertyOfNonNull(AliOssProperties.OSS_ENDPOINT).toString(); + String accessKey = + optionService.getByPropertyOfNonNull(AliOssProperties.OSS_ACCESS_KEY).toString(); + String accessSecret = + optionService.getByPropertyOfNonNull(AliOssProperties.OSS_ACCESS_SECRET).toString(); + String bucketName = + optionService.getByPropertyOfNonNull(AliOssProperties.OSS_BUCKET_NAME).toString(); + String styleRule = + optionService.getByPropertyOrDefault(AliOssProperties.OSS_STYLE_RULE, String.class, ""); + String thumbnailStyleRule = optionService + .getByPropertyOrDefault(AliOssProperties.OSS_THUMBNAIL_STYLE_RULE, String.class, ""); // Init OSS client OSS ossClient = new OSSClientBuilder().build(endPoint, accessKey, accessSecret); @@ -62,30 +70,31 @@ public AliOssFileHandler(OptionService optionService) { if (StringUtils.isNotEmpty(domain)) { basePath.append(domain) - .append(URL_SEPARATOR); + .append(URL_SEPARATOR); } else { basePath.append(bucketName) - .append(".") - .append(endPoint) - .append(URL_SEPARATOR); + .append(".") + .append(endPoint) + .append(URL_SEPARATOR); } try { - final String basename = FilenameUtils.getBasename(Objects.requireNonNull(file.getOriginalFilename())); + final String basename = + FilenameUtils.getBasename(Objects.requireNonNull(file.getOriginalFilename())); final String extension = FilenameUtils.getExtension(file.getOriginalFilename()); final String timestamp = String.valueOf(System.currentTimeMillis()); final StringBuilder upFilePath = new StringBuilder(); if (StringUtils.isNotEmpty(source)) { upFilePath.append(source) - .append(URL_SEPARATOR); + .append(URL_SEPARATOR); } upFilePath.append(basename) - .append("_") - .append(timestamp) - .append(".") - .append(extension); + .append("_") + .append(timestamp) + .append(".") + .append(extension); String filePath = StringUtils.join(basePath.toString(), upFilePath.toString()); @@ -93,8 +102,8 @@ public AliOssFileHandler(OptionService optionService) { // Upload final PutObjectResult putObjectResult = ossClient.putObject(bucketName, - upFilePath.toString(), - file.getInputStream()); + upFilePath.toString(), + file.getInputStream()); if (putObjectResult == null) { throw new FileOperationException("上传附件 " + file.getOriginalFilename() + " 到阿里云失败 "); @@ -103,9 +112,11 @@ public AliOssFileHandler(OptionService optionService) { // Response result final UploadResult uploadResult = new UploadResult(); uploadResult.setFilename(basename); - uploadResult.setFilePath(StringUtils.isBlank(styleRule) ? filePath : filePath + styleRule); + uploadResult + .setFilePath(StringUtils.isBlank(styleRule) ? filePath : filePath + styleRule); uploadResult.setKey(upFilePath.toString()); - uploadResult.setMediaType(MediaType.valueOf(Objects.requireNonNull(file.getContentType()))); + uploadResult + .setMediaType(MediaType.valueOf(Objects.requireNonNull(file.getContentType()))); uploadResult.setSuffix(extension); uploadResult.setSize(file.getSize()); @@ -113,14 +124,16 @@ public AliOssFileHandler(OptionService optionService) { if (ImageUtils.EXTENSION_ICO.equals(extension)) { return filePath; } else { - return StringUtils.isBlank(thumbnailStyleRule) ? filePath : filePath + thumbnailStyleRule; + return StringUtils.isBlank(thumbnailStyleRule) ? filePath : + filePath + thumbnailStyleRule; } }); log.info("Uploaded file: [{}] successfully", file.getOriginalFilename()); return uploadResult; } catch (Exception e) { - throw new FileOperationException("上传附件 " + file.getOriginalFilename() + " 到阿里云失败 ", e).setErrorData(file.getOriginalFilename()); + throw new FileOperationException("上传附件 " + file.getOriginalFilename() + " 到阿里云失败 ", e) + .setErrorData(file.getOriginalFilename()); } finally { ossClient.shutdown(); } @@ -131,10 +144,14 @@ public void delete(@NonNull String key) { Assert.notNull(key, "File key must not be blank"); // Get config - String endPoint = optionService.getByPropertyOfNonNull(AliOssProperties.OSS_ENDPOINT).toString(); - String accessKey = optionService.getByPropertyOfNonNull(AliOssProperties.OSS_ACCESS_KEY).toString(); - String accessSecret = optionService.getByPropertyOfNonNull(AliOssProperties.OSS_ACCESS_SECRET).toString(); - String bucketName = optionService.getByPropertyOfNonNull(AliOssProperties.OSS_BUCKET_NAME).toString(); + String endPoint = + optionService.getByPropertyOfNonNull(AliOssProperties.OSS_ENDPOINT).toString(); + String accessKey = + optionService.getByPropertyOfNonNull(AliOssProperties.OSS_ACCESS_KEY).toString(); + String accessSecret = + optionService.getByPropertyOfNonNull(AliOssProperties.OSS_ACCESS_SECRET).toString(); + String bucketName = + optionService.getByPropertyOfNonNull(AliOssProperties.OSS_BUCKET_NAME).toString(); // Init OSS client OSS ossClient = new OSSClientBuilder().build(endPoint, accessKey, accessSecret); diff --git a/src/main/java/run/halo/app/handler/file/BaiduBosFileHandler.java b/src/main/java/run/halo/app/handler/file/BaiduBosFileHandler.java index ec352f7cf0..0f1d239662 100644 --- a/src/main/java/run/halo/app/handler/file/BaiduBosFileHandler.java +++ b/src/main/java/run/halo/app/handler/file/BaiduBosFileHandler.java @@ -5,6 +5,7 @@ import com.baidubce.services.bos.BosClient; import com.baidubce.services.bos.BosClientConfiguration; import com.baidubce.services.bos.model.PutObjectResponse; +import java.util.Objects; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.http.MediaType; @@ -19,8 +20,6 @@ import run.halo.app.utils.FilenameUtils; import run.halo.app.utils.ImageUtils; -import java.util.Objects; - /** * Baidu bos file handler. * @@ -44,13 +43,20 @@ public UploadResult upload(MultipartFile file) { // Get config Object protocol = optionService.getByPropertyOfNonNull(BaiduBosProperties.BOS_PROTOCOL); - String domain = optionService.getByPropertyOrDefault(BaiduBosProperties.BOS_DOMAIN, String.class, ""); - String endPoint = optionService.getByPropertyOfNonNull(BaiduBosProperties.BOS_ENDPOINT).toString(); - String accessKey = optionService.getByPropertyOfNonNull(BaiduBosProperties.BOS_ACCESS_KEY).toString(); - String secretKey = optionService.getByPropertyOfNonNull(BaiduBosProperties.BOS_SECRET_KEY).toString(); - String bucketName = optionService.getByPropertyOfNonNull(BaiduBosProperties.BOS_BUCKET_NAME).toString(); - String styleRule = optionService.getByPropertyOrDefault(BaiduBosProperties.BOS_STYLE_RULE, String.class, ""); - String thumbnailStyleRule = optionService.getByPropertyOrDefault(BaiduBosProperties.BOS_THUMBNAIL_STYLE_RULE, String.class, ""); + String domain = + optionService.getByPropertyOrDefault(BaiduBosProperties.BOS_DOMAIN, String.class, ""); + String endPoint = + optionService.getByPropertyOfNonNull(BaiduBosProperties.BOS_ENDPOINT).toString(); + String accessKey = + optionService.getByPropertyOfNonNull(BaiduBosProperties.BOS_ACCESS_KEY).toString(); + String secretKey = + optionService.getByPropertyOfNonNull(BaiduBosProperties.BOS_SECRET_KEY).toString(); + String bucketName = + optionService.getByPropertyOfNonNull(BaiduBosProperties.BOS_BUCKET_NAME).toString(); + String styleRule = optionService + .getByPropertyOrDefault(BaiduBosProperties.BOS_STYLE_RULE, String.class, ""); + String thumbnailStyleRule = optionService + .getByPropertyOrDefault(BaiduBosProperties.BOS_THUMBNAIL_STYLE_RULE, String.class, ""); String source = StringUtils.join(protocol, bucketName, "." + endPoint); BosClientConfiguration config = new BosClientConfiguration(); @@ -63,14 +69,18 @@ public UploadResult upload(MultipartFile file) { domain = protocol + domain; try { - String basename = FilenameUtils.getBasename(Objects.requireNonNull(file.getOriginalFilename())); + String basename = + FilenameUtils.getBasename(Objects.requireNonNull(file.getOriginalFilename())); String extension = FilenameUtils.getExtension(file.getOriginalFilename()); String timestamp = String.valueOf(System.currentTimeMillis()); String upFilePath = StringUtils.join(basename, "_", timestamp, ".", extension); - String filePath = StringUtils.join(StringUtils.appendIfMissing(StringUtils.isNotBlank(domain) ? domain : source, "/"), upFilePath); + String filePath = StringUtils.join( + StringUtils.appendIfMissing(StringUtils.isNotBlank(domain) ? domain : source, "/"), + upFilePath); // Upload - PutObjectResponse putObjectResponseFromInputStream = client.putObject(bucketName, upFilePath, file.getInputStream()); + PutObjectResponse putObjectResponseFromInputStream = + client.putObject(bucketName, upFilePath, file.getInputStream()); if (putObjectResponseFromInputStream == null) { throw new FileOperationException("上传附件 " + file.getOriginalFilename() + " 到百度云失败 "); } @@ -78,9 +88,11 @@ public UploadResult upload(MultipartFile file) { // Response result UploadResult uploadResult = new UploadResult(); uploadResult.setFilename(basename); - uploadResult.setFilePath(StringUtils.isBlank(styleRule) ? filePath : filePath + styleRule); + uploadResult + .setFilePath(StringUtils.isBlank(styleRule) ? filePath : filePath + styleRule); uploadResult.setKey(upFilePath); - uploadResult.setMediaType(MediaType.valueOf(Objects.requireNonNull(file.getContentType()))); + uploadResult + .setMediaType(MediaType.valueOf(Objects.requireNonNull(file.getContentType()))); uploadResult.setSuffix(extension); uploadResult.setSize(file.getSize()); @@ -89,7 +101,8 @@ public UploadResult upload(MultipartFile file) { if (ImageUtils.EXTENSION_ICO.equals(extension)) { return filePath; } else { - return StringUtils.isBlank(thumbnailStyleRule) ? filePath : filePath + thumbnailStyleRule; + return StringUtils.isBlank(thumbnailStyleRule) ? filePath : + filePath + thumbnailStyleRule; } }); @@ -106,10 +119,14 @@ public void delete(String key) { Assert.notNull(key, "File key must not be blank"); // Get config - String endPoint = optionService.getByPropertyOfNonNull(BaiduBosProperties.BOS_ENDPOINT).toString(); - String accessKey = optionService.getByPropertyOfNonNull(BaiduBosProperties.BOS_ACCESS_KEY).toString(); - String secretKey = optionService.getByPropertyOfNonNull(BaiduBosProperties.BOS_SECRET_KEY).toString(); - String bucketName = optionService.getByPropertyOfNonNull(BaiduBosProperties.BOS_BUCKET_NAME).toString(); + String endPoint = + optionService.getByPropertyOfNonNull(BaiduBosProperties.BOS_ENDPOINT).toString(); + String accessKey = + optionService.getByPropertyOfNonNull(BaiduBosProperties.BOS_ACCESS_KEY).toString(); + String secretKey = + optionService.getByPropertyOfNonNull(BaiduBosProperties.BOS_SECRET_KEY).toString(); + String bucketName = + optionService.getByPropertyOfNonNull(BaiduBosProperties.BOS_BUCKET_NAME).toString(); BosClientConfiguration config = new BosClientConfiguration(); config.setCredentials(new DefaultBceCredentials(accessKey, secretKey)); diff --git a/src/main/java/run/halo/app/handler/file/FileHandler.java b/src/main/java/run/halo/app/handler/file/FileHandler.java index 9f3e9e34f3..3b01ff227e 100644 --- a/src/main/java/run/halo/app/handler/file/FileHandler.java +++ b/src/main/java/run/halo/app/handler/file/FileHandler.java @@ -1,5 +1,11 @@ package run.halo.app.handler.file; +import static run.halo.app.model.support.HaloConst.FILE_SEPARATOR; + +import java.io.IOException; +import java.io.InputStream; +import java.util.function.Supplier; +import javax.imageio.ImageReader; import org.apache.commons.lang3.StringUtils; import org.slf4j.LoggerFactory; import org.springframework.http.MediaType; @@ -12,13 +18,6 @@ import run.halo.app.model.support.UploadResult; import run.halo.app.utils.ImageUtils; -import javax.imageio.ImageReader; -import java.io.IOException; -import java.io.InputStream; -import java.util.function.Supplier; - -import static run.halo.app.model.support.HaloConst.FILE_SEPARATOR; - /** * File handler interface. * @@ -29,6 +28,19 @@ public interface FileHandler { MediaType IMAGE_TYPE = MediaType.valueOf("image/*"); + /** + * Normalize directory full name, ensure the end path separator. + * + * @param dir directory full name must not be blank + * @return normalized directory full name with end path separator + */ + @NonNull + static String normalizeDirectory(@NonNull String dir) { + Assert.hasText(dir, "Directory full name must not be blank"); + + return StringUtils.appendIfMissing(dir, FILE_SEPARATOR); + } + /** * Uploads file. * @@ -51,13 +63,13 @@ default boolean isImageType(@NonNull MultipartFile file) { } /** - * @param uploadResult updated result must not be null - * @param file multipart file must not be null + * @param uploadResult updated result must not be null + * @param file multipart file must not be null * @param thumbnailSupplier thumbnail supplier */ default void handleImageMetadata(@NonNull MultipartFile file, - @NonNull UploadResult uploadResult, - @Nullable Supplier thumbnailSupplier) { + @NonNull UploadResult uploadResult, + @Nullable Supplier thumbnailSupplier) { if (isImageType(file)) { // Handle image try (InputStream is = file.getInputStream()) { @@ -92,17 +104,4 @@ default void handleImageMetadata(@NonNull MultipartFile file, */ AttachmentType getAttachmentType(); - /** - * Normalize directory full name, ensure the end path separator. - * - * @param dir directory full name must not be blank - * @return normalized directory full name with end path separator - */ - @NonNull - static String normalizeDirectory(@NonNull String dir) { - Assert.hasText(dir, "Directory full name must not be blank"); - - return StringUtils.appendIfMissing(dir, FILE_SEPARATOR); - } - } \ No newline at end of file diff --git a/src/main/java/run/halo/app/handler/file/FileHandlers.java b/src/main/java/run/halo/app/handler/file/FileHandlers.java index 79c0bf9076..dc1095a250 100644 --- a/src/main/java/run/halo/app/handler/file/FileHandlers.java +++ b/src/main/java/run/halo/app/handler/file/FileHandlers.java @@ -1,5 +1,7 @@ package run.halo.app.handler.file; +import java.util.Collection; +import java.util.concurrent.ConcurrentHashMap; import lombok.extern.slf4j.Slf4j; import org.springframework.context.ApplicationContext; import org.springframework.lang.NonNull; @@ -14,9 +16,6 @@ import run.halo.app.model.enums.AttachmentType; import run.halo.app.model.support.UploadResult; -import java.util.Collection; -import java.util.concurrent.ConcurrentHashMap; - /** * File handler manager. * @@ -30,7 +29,8 @@ public class FileHandlers { /** * File handler container. */ - private final ConcurrentHashMap fileHandlers = new ConcurrentHashMap<>(16); + private final ConcurrentHashMap fileHandlers = + new ConcurrentHashMap<>(16); public FileHandlers(ApplicationContext applicationContext) { // Add all file handler @@ -41,13 +41,15 @@ public FileHandlers(ApplicationContext applicationContext) { /** * Uploads files. * - * @param file multipart file must not be null + * @param file multipart file must not be null * @param attachmentType attachment type must not be null * @return upload result - * @throws FileOperationException throws when fail to delete attachment or no available file handler to upload it + * @throws FileOperationException throws when fail to delete attachment or no available file + * handler to upload it */ @NonNull - public UploadResult upload(@NonNull MultipartFile file, @NonNull AttachmentType attachmentType) { + public UploadResult upload(@NonNull MultipartFile file, + @NonNull AttachmentType attachmentType) { return getSupportedType(attachmentType).upload(file); } @@ -55,12 +57,13 @@ public UploadResult upload(@NonNull MultipartFile file, @NonNull AttachmentType * Deletes attachment. * * @param attachment attachment detail must not be null - * @throws FileOperationException throws when fail to delete attachment or no available file handler to delete it + * @throws FileOperationException throws when fail to delete attachment or no available file + * handler to delete it */ public void delete(@NonNull Attachment attachment) { Assert.notNull(attachment, "Attachment must not be null"); getSupportedType(attachment.getType()) - .delete(attachment.getFileKey()); + .delete(attachment.getFileKey()); } /** @@ -83,9 +86,11 @@ public FileHandlers addFileHandlers(@Nullable Collection fileHandle } private FileHandler getSupportedType(AttachmentType type) { - FileHandler handler = fileHandlers.getOrDefault(type, fileHandlers.get(AttachmentType.LOCAL)); + FileHandler handler = + fileHandlers.getOrDefault(type, fileHandlers.get(AttachmentType.LOCAL)); if (handler == null) { - throw new FileOperationException("No available file handlers to operate the file").setErrorData(type); + throw new FileOperationException("No available file handlers to operate the file") + .setErrorData(type); } return handler; } diff --git a/src/main/java/run/halo/app/handler/file/HuaweiObsFileHandler.java b/src/main/java/run/halo/app/handler/file/HuaweiObsFileHandler.java index 4c15af9bac..28df79ae4e 100644 --- a/src/main/java/run/halo/app/handler/file/HuaweiObsFileHandler.java +++ b/src/main/java/run/halo/app/handler/file/HuaweiObsFileHandler.java @@ -1,11 +1,15 @@ package run.halo.app.handler.file; +import static run.halo.app.model.support.HaloConst.URL_SEPARATOR; + import com.obs.services.ObsClient; import com.obs.services.model.PutObjectResult; +import java.io.IOException; +import java.util.Objects; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; -import org.springframework.lang.NonNull; import org.springframework.http.MediaType; +import org.springframework.lang.NonNull; import org.springframework.stereotype.Component; import org.springframework.util.Assert; import org.springframework.web.multipart.MultipartFile; @@ -17,11 +21,6 @@ import run.halo.app.utils.FilenameUtils; import run.halo.app.utils.ImageUtils; -import java.io.IOException; -import java.util.Objects; - -import static run.halo.app.model.support.HaloConst.URL_SEPARATOR; - /** * Huawei obs file handler. * @@ -43,15 +42,24 @@ public HuaweiObsFileHandler(OptionService optionService) { Assert.notNull(file, "Multipart file must not be null"); // Get config - String protocol = optionService.getByPropertyOfNonNull(HuaweiObsProperties.OSS_PROTOCOL).toString(); - String domain = optionService.getByPropertyOrDefault(HuaweiObsProperties.OSS_DOMAIN, String.class, ""); - String source = optionService.getByPropertyOrDefault(HuaweiObsProperties.OSS_SOURCE, String.class, ""); - String endPoint = optionService.getByPropertyOfNonNull(HuaweiObsProperties.OSS_ENDPOINT).toString(); - String accessKey = optionService.getByPropertyOfNonNull(HuaweiObsProperties.OSS_ACCESS_KEY).toString(); - String accessSecret = optionService.getByPropertyOfNonNull(HuaweiObsProperties.OSS_ACCESS_SECRET).toString(); - String bucketName = optionService.getByPropertyOfNonNull(HuaweiObsProperties.OSS_BUCKET_NAME).toString(); - String styleRule = optionService.getByPropertyOrDefault(HuaweiObsProperties.OSS_STYLE_RULE, String.class, ""); - String thumbnailStyleRule = optionService.getByPropertyOrDefault(HuaweiObsProperties.OSS_THUMBNAIL_STYLE_RULE, String.class, ""); + String protocol = + optionService.getByPropertyOfNonNull(HuaweiObsProperties.OSS_PROTOCOL).toString(); + String domain = + optionService.getByPropertyOrDefault(HuaweiObsProperties.OSS_DOMAIN, String.class, ""); + String source = + optionService.getByPropertyOrDefault(HuaweiObsProperties.OSS_SOURCE, String.class, ""); + String endPoint = + optionService.getByPropertyOfNonNull(HuaweiObsProperties.OSS_ENDPOINT).toString(); + String accessKey = + optionService.getByPropertyOfNonNull(HuaweiObsProperties.OSS_ACCESS_KEY).toString(); + String accessSecret = + optionService.getByPropertyOfNonNull(HuaweiObsProperties.OSS_ACCESS_SECRET).toString(); + String bucketName = + optionService.getByPropertyOfNonNull(HuaweiObsProperties.OSS_BUCKET_NAME).toString(); + String styleRule = optionService + .getByPropertyOrDefault(HuaweiObsProperties.OSS_STYLE_RULE, String.class, ""); + String thumbnailStyleRule = optionService + .getByPropertyOrDefault(HuaweiObsProperties.OSS_THUMBNAIL_STYLE_RULE, String.class, ""); // Init OSS client final ObsClient obsClient = new ObsClient(accessKey, accessSecret, endPoint); @@ -60,37 +68,39 @@ public HuaweiObsFileHandler(OptionService optionService) { if (StringUtils.isNotEmpty(domain)) { basePath.append(domain) - .append(URL_SEPARATOR); + .append(URL_SEPARATOR); } else { basePath.append(bucketName) - .append(".") - .append(endPoint) - .append(URL_SEPARATOR); + .append(".") + .append(endPoint) + .append(URL_SEPARATOR); } try { - String basename = FilenameUtils.getBasename(Objects.requireNonNull(file.getOriginalFilename())); + String basename = + FilenameUtils.getBasename(Objects.requireNonNull(file.getOriginalFilename())); String extension = FilenameUtils.getExtension(file.getOriginalFilename()); String timestamp = String.valueOf(System.currentTimeMillis()); StringBuilder upFilePath = new StringBuilder(); if (StringUtils.isNotEmpty(source)) { upFilePath.append(source) - .append(URL_SEPARATOR); + .append(URL_SEPARATOR); } upFilePath.append(basename) - .append("_") - .append(timestamp) - .append(".") - .append(extension); + .append("_") + .append(timestamp) + .append(".") + .append(extension); String filePath = StringUtils.join(basePath.toString(), upFilePath.toString()); log.info(basePath.toString()); // Upload - PutObjectResult putObjectResult = obsClient.putObject(bucketName, upFilePath.toString(), file.getInputStream()); + PutObjectResult putObjectResult = + obsClient.putObject(bucketName, upFilePath.toString(), file.getInputStream()); if (putObjectResult == null) { throw new FileOperationException("上传附件 " + file.getOriginalFilename() + " 到华为云失败 "); } @@ -98,9 +108,11 @@ public HuaweiObsFileHandler(OptionService optionService) { // Response result UploadResult uploadResult = new UploadResult(); uploadResult.setFilename(basename); - uploadResult.setFilePath(StringUtils.isBlank(styleRule) ? filePath : filePath + styleRule); + uploadResult + .setFilePath(StringUtils.isBlank(styleRule) ? filePath : filePath + styleRule); uploadResult.setKey(upFilePath.toString()); - uploadResult.setMediaType(MediaType.valueOf(Objects.requireNonNull(file.getContentType()))); + uploadResult + .setMediaType(MediaType.valueOf(Objects.requireNonNull(file.getContentType()))); uploadResult.setSuffix(extension); uploadResult.setSize(file.getSize()); @@ -108,14 +120,16 @@ public HuaweiObsFileHandler(OptionService optionService) { if (ImageUtils.EXTENSION_ICO.equals(extension)) { return filePath; } else { - return StringUtils.isBlank(thumbnailStyleRule) ? filePath : filePath + thumbnailStyleRule; + return StringUtils.isBlank(thumbnailStyleRule) ? filePath : + filePath + thumbnailStyleRule; } }); log.info("Uploaded file: [{}] successfully", file.getOriginalFilename()); return uploadResult; } catch (Exception e) { - throw new FileOperationException("上传附件 " + file.getOriginalFilename() + " 到华为云失败 ", e).setErrorData(file.getOriginalFilename()); + throw new FileOperationException("上传附件 " + file.getOriginalFilename() + " 到华为云失败 ", e) + .setErrorData(file.getOriginalFilename()); } finally { try { obsClient.close(); @@ -130,10 +144,14 @@ public void delete(@NonNull String key) { Assert.notNull(key, "File key must not be blank"); // Get config - String endPoint = optionService.getByPropertyOfNonNull(HuaweiObsProperties.OSS_ENDPOINT).toString(); - String accessKey = optionService.getByPropertyOfNonNull(HuaweiObsProperties.OSS_ACCESS_KEY).toString(); - String accessSecret = optionService.getByPropertyOfNonNull(HuaweiObsProperties.OSS_ACCESS_SECRET).toString(); - String bucketName = optionService.getByPropertyOfNonNull(HuaweiObsProperties.OSS_BUCKET_NAME).toString(); + String endPoint = + optionService.getByPropertyOfNonNull(HuaweiObsProperties.OSS_ENDPOINT).toString(); + String accessKey = + optionService.getByPropertyOfNonNull(HuaweiObsProperties.OSS_ACCESS_KEY).toString(); + String accessSecret = + optionService.getByPropertyOfNonNull(HuaweiObsProperties.OSS_ACCESS_SECRET).toString(); + String bucketName = + optionService.getByPropertyOfNonNull(HuaweiObsProperties.OSS_BUCKET_NAME).toString(); // Init OSS client final ObsClient obsClient = new ObsClient(accessKey, accessSecret, endPoint); diff --git a/src/main/java/run/halo/app/handler/file/LocalFileHandler.java b/src/main/java/run/halo/app/handler/file/LocalFileHandler.java index c4a89e5b09..e2c8ae851c 100644 --- a/src/main/java/run/halo/app/handler/file/LocalFileHandler.java +++ b/src/main/java/run/halo/app/handler/file/LocalFileHandler.java @@ -1,5 +1,16 @@ package run.halo.app.handler.file; +import static run.halo.app.model.support.HaloConst.FILE_SEPARATOR; + +import java.awt.image.BufferedImage; +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Calendar; +import java.util.Objects; +import java.util.concurrent.locks.ReentrantLock; import lombok.extern.slf4j.Slf4j; import net.coobird.thumbnailator.Thumbnails; import org.springframework.http.MediaType; @@ -15,18 +26,6 @@ import run.halo.app.utils.HaloUtils; import run.halo.app.utils.ImageUtils; -import java.awt.image.BufferedImage; -import java.io.IOException; -import java.io.InputStream; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.Calendar; -import java.util.Objects; -import java.util.concurrent.locks.ReentrantLock; - -import static run.halo.app.model.support.HaloConst.FILE_SEPARATOR; - /** * Local file handler. * @@ -41,19 +40,19 @@ public class LocalFileHandler implements FileHandler { /** * Upload sub directory. */ - private final static String UPLOAD_SUB_DIR = "upload/"; + private static final String UPLOAD_SUB_DIR = "upload/"; - private final static String THUMBNAIL_SUFFIX = "-thumbnail"; + private static final String THUMBNAIL_SUFFIX = "-thumbnail"; /** * Thumbnail width. */ - private final static int THUMB_WIDTH = 256; + private static final int THUMB_WIDTH = 256; /** * Thumbnail height. */ - private final static int THUMB_HEIGHT = 256; + private static final int THUMB_HEIGHT = 256; private final OptionService optionService; @@ -62,7 +61,7 @@ public class LocalFileHandler implements FileHandler { private final ReentrantLock lock = new ReentrantLock(); public LocalFileHandler(OptionService optionService, - HaloProperties haloProperties) { + HaloProperties haloProperties) { this.optionService = optionService; // Get work dir @@ -104,7 +103,8 @@ public UploadResult upload(MultipartFile file) { // Build directory String subDir = UPLOAD_SUB_DIR + year + FILE_SEPARATOR + monthString + FILE_SEPARATOR; - String originalBasename = FilenameUtils.getBasename(Objects.requireNonNull(file.getOriginalFilename())); + String originalBasename = + FilenameUtils.getBasename(Objects.requireNonNull(file.getOriginalFilename())); // Get basename String basename = originalBasename + '-' + HaloUtils.randomUUIDWithoutDash(); @@ -112,7 +112,8 @@ public UploadResult upload(MultipartFile file) { // Get extension String extension = FilenameUtils.getExtension(file.getOriginalFilename()); - log.debug("Base name: [{}], extension: [{}] of original filename: [{}]", basename, extension, file.getOriginalFilename()); + log.debug("Base name: [{}], extension: [{}] of original filename: [{}]", basename, + extension, file.getOriginalFilename()); // Build sub file path String subFilePath = subDir + basename + '.' + extension; @@ -120,7 +121,8 @@ public UploadResult upload(MultipartFile file) { // Get upload path Path uploadPath = Paths.get(workDir, subFilePath); - log.info("Uploading file: [{}]to directory: [{}]", file.getOriginalFilename(), uploadPath.toString()); + log.info("Uploading file: [{}]to directory: [{}]", file.getOriginalFilename(), + uploadPath.toString()); try { // TODO Synchronize here @@ -137,7 +139,8 @@ public UploadResult upload(MultipartFile file) { uploadResult.setFilePath(subFilePath); uploadResult.setKey(subFilePath); uploadResult.setSuffix(extension); - uploadResult.setMediaType(MediaType.valueOf(Objects.requireNonNull(file.getContentType()))); + uploadResult + .setMediaType(MediaType.valueOf(Objects.requireNonNull(file.getContentType()))); uploadResult.setSize(file.getSize()); // TODO refactor this: if image is svg ext. extension @@ -160,7 +163,8 @@ public UploadResult upload(MultipartFile file) { return subFilePath; }); - log.info("Uploaded file: [{}] to directory: [{}] successfully", file.getOriginalFilename(), uploadPath.toString()); + log.info("Uploaded file: [{}] to directory: [{}] successfully", + file.getOriginalFilename(), uploadPath.toString()); return uploadResult; } catch (IOException e) { throw new FileOperationException("上传附件失败").setErrorData(uploadPath); @@ -206,7 +210,8 @@ public AttachmentType getAttachmentType() { return AttachmentType.LOCAL; } - private boolean generateThumbnail(BufferedImage originalImage, Path thumbPath, String extension) { + private boolean generateThumbnail(BufferedImage originalImage, Path thumbPath, + String extension) { Assert.notNull(originalImage, "Image must not be null"); Assert.notNull(thumbPath, "Thumb path must not be null"); @@ -216,8 +221,10 @@ private boolean generateThumbnail(BufferedImage originalImage, Path thumbPath, S Files.createFile(thumbPath); // Convert to thumbnail and copy the thumbnail log.debug("Trying to generate thumbnail: [{}]", thumbPath.toString()); - Thumbnails.of(originalImage).size(THUMB_WIDTH, THUMB_HEIGHT).keepAspectRatio(true).toFile(thumbPath.toFile()); - log.info("Generated thumbnail image, and wrote the thumbnail to [{}]", thumbPath.toString()); + Thumbnails.of(originalImage).size(THUMB_WIDTH, THUMB_HEIGHT).keepAspectRatio(true) + .toFile(thumbPath.toFile()); + log.info("Generated thumbnail image, and wrote the thumbnail to [{}]", + thumbPath.toString()); result = true; } catch (Throwable t) { // Ignore the error diff --git a/src/main/java/run/halo/app/handler/file/MinioFileHandler.java b/src/main/java/run/halo/app/handler/file/MinioFileHandler.java index 84c8ff5104..70c3139775 100644 --- a/src/main/java/run/halo/app/handler/file/MinioFileHandler.java +++ b/src/main/java/run/halo/app/handler/file/MinioFileHandler.java @@ -3,10 +3,11 @@ import io.minio.MinioClient; import io.minio.PutObjectArgs; import io.minio.RemoveObjectArgs; +import java.util.Objects; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; -import org.springframework.lang.NonNull; import org.springframework.http.MediaType; +import org.springframework.lang.NonNull; import org.springframework.stereotype.Component; import org.springframework.util.Assert; import org.springframework.web.multipart.MultipartFile; @@ -18,8 +19,6 @@ import run.halo.app.service.OptionService; import run.halo.app.utils.FilenameUtils; -import java.util.Objects; - /** * MinIO file handler. @@ -43,39 +42,47 @@ public UploadResult upload(@NonNull MultipartFile file) { Assert.notNull(file, "Multipart file must not be null"); // Get config String endpoint = optionService.getByPropertyOfNonNull(MinioProperties.ENDPOINT).toString(); - String accessKey = optionService.getByPropertyOfNonNull(MinioProperties.ACCESS_KEY).toString(); - String accessSecret = optionService.getByPropertyOfNonNull(MinioProperties.ACCESS_SECRET).toString(); - String bucketName = optionService.getByPropertyOfNonNull(MinioProperties.BUCKET_NAME).toString(); - String source = optionService.getByPropertyOrDefault(MinioProperties.SOURCE, String.class, ""); + String accessKey = + optionService.getByPropertyOfNonNull(MinioProperties.ACCESS_KEY).toString(); + String accessSecret = + optionService.getByPropertyOfNonNull(MinioProperties.ACCESS_SECRET).toString(); + String bucketName = + optionService.getByPropertyOfNonNull(MinioProperties.BUCKET_NAME).toString(); + String source = + optionService.getByPropertyOrDefault(MinioProperties.SOURCE, String.class, ""); endpoint = StringUtils.appendIfMissing(endpoint, HaloConst.URL_SEPARATOR); MinioClient minioClient = MinioClient.builder() - .endpoint(endpoint) - .credentials(accessKey, accessSecret) - .build(); + .endpoint(endpoint) + .credentials(accessKey, accessSecret) + .build(); try { - String basename = FilenameUtils.getBasename(Objects.requireNonNull(file.getOriginalFilename())); + String basename = + FilenameUtils.getBasename(Objects.requireNonNull(file.getOriginalFilename())); String extension = FilenameUtils.getExtension(file.getOriginalFilename()); String timestamp = String.valueOf(System.currentTimeMillis()); - String upFilePath = StringUtils.join(StringUtils.isNotBlank(source) ? source + HaloConst.URL_SEPARATOR : "", + String upFilePath = StringUtils + .join(StringUtils.isNotBlank(source) ? source + HaloConst.URL_SEPARATOR : "", basename, "_", timestamp, ".", extension); - String filePath = StringUtils.join(endpoint, bucketName, HaloConst.URL_SEPARATOR, upFilePath); + String filePath = + StringUtils.join(endpoint, bucketName, HaloConst.URL_SEPARATOR, upFilePath); PutObjectArgs putObjectArgs = PutObjectArgs.builder() - .contentType(file.getContentType()) - .bucket(bucketName) - .stream(file.getInputStream(), file.getSize(), -1) - .object(upFilePath) - .build(); + .contentType(file.getContentType()) + .bucket(bucketName) + .stream(file.getInputStream(), file.getSize(), -1) + .object(upFilePath) + .build(); minioClient.putObject(putObjectArgs); UploadResult uploadResult = new UploadResult(); uploadResult.setFilename(basename); uploadResult.setFilePath(filePath); uploadResult.setKey(upFilePath); - uploadResult.setMediaType(MediaType.valueOf(Objects.requireNonNull(file.getContentType()))); + uploadResult + .setMediaType(MediaType.valueOf(Objects.requireNonNull(file.getContentType()))); uploadResult.setSuffix(extension); uploadResult.setSize(file.getSize()); @@ -85,7 +92,8 @@ public UploadResult upload(@NonNull MultipartFile file) { return uploadResult; } catch (Exception e) { log.error("upload file to MINIO failed", e); - throw new FileOperationException("上传附件 " + file.getOriginalFilename() + " 到 MinIO 失败 ", e).setErrorData(e.getMessage()); + throw new FileOperationException("上传附件 " + file.getOriginalFilename() + " 到 MinIO 失败 ", + e).setErrorData(e.getMessage()); } } @@ -96,23 +104,27 @@ public void delete(@NonNull String key) { String endPoint = optionService.getByPropertyOfNonNull(MinioProperties.ENDPOINT).toString(); endPoint = StringUtils.appendIfMissing(endPoint, HaloConst.URL_SEPARATOR); - String accessKey = optionService.getByPropertyOfNonNull(MinioProperties.ACCESS_KEY).toString(); - String accessSecret = optionService.getByPropertyOfNonNull(MinioProperties.ACCESS_SECRET).toString(); - String bucketName = optionService.getByPropertyOfNonNull(MinioProperties.BUCKET_NAME).toString(); + String accessKey = + optionService.getByPropertyOfNonNull(MinioProperties.ACCESS_KEY).toString(); + String accessSecret = + optionService.getByPropertyOfNonNull(MinioProperties.ACCESS_SECRET).toString(); + String bucketName = + optionService.getByPropertyOfNonNull(MinioProperties.BUCKET_NAME).toString(); MinioClient minioClient = MinioClient.builder() - .endpoint(endPoint) - .credentials(accessKey, accessSecret) - .build(); + .endpoint(endPoint) + .credentials(accessKey, accessSecret) + .build(); try { minioClient.removeObject(RemoveObjectArgs.builder() - .bucket(bucketName) - .object(key) - .build()); + .bucket(bucketName) + .object(key) + .build()); } catch (Exception e) { log.error("delete MINIO file: [{}] failed", key, e); - throw new FileOperationException("附件 " + key + " 从 MinIO 删除失败", e).setErrorData(e.getMessage()); + throw new FileOperationException("附件 " + key + " 从 MinIO 删除失败", e) + .setErrorData(e.getMessage()); } } diff --git a/src/main/java/run/halo/app/handler/file/QiniuOssFileHandler.java b/src/main/java/run/halo/app/handler/file/QiniuOssFileHandler.java index 39dbd46209..1ddae4fd84 100644 --- a/src/main/java/run/halo/app/handler/file/QiniuOssFileHandler.java +++ b/src/main/java/run/halo/app/handler/file/QiniuOssFileHandler.java @@ -1,5 +1,10 @@ package run.halo.app.handler.file; +import static run.halo.app.model.support.HaloConst.FILE_SEPARATOR; +import static run.halo.app.model.support.HaloConst.TEMP_DIR; +import static run.halo.app.model.support.HaloConst.URL_SEPARATOR; +import static run.halo.app.utils.HaloUtils.ensureSuffix; + import com.qiniu.common.QiniuException; import com.qiniu.http.Response; import com.qiniu.storage.BucketManager; @@ -9,6 +14,10 @@ import com.qiniu.storage.persistent.FileRecorder; import com.qiniu.util.Auth; import com.qiniu.util.StringMap; +import java.io.IOException; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Objects; import lombok.Data; import lombok.NoArgsConstructor; import lombok.extern.slf4j.Slf4j; @@ -26,14 +35,6 @@ import run.halo.app.utils.ImageUtils; import run.halo.app.utils.JsonUtils; -import java.io.IOException; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.Objects; - -import static run.halo.app.model.support.HaloConst.*; -import static run.halo.app.utils.HaloUtils.ensureSuffix; - /** * Qiniu oss file handler. * @@ -57,14 +58,22 @@ public UploadResult upload(MultipartFile file) { Region region = optionService.getQiniuRegion(); - String accessKey = optionService.getByPropertyOfNonNull(QiniuOssProperties.OSS_ACCESS_KEY).toString(); - String secretKey = optionService.getByPropertyOfNonNull(QiniuOssProperties.OSS_SECRET_KEY).toString(); - String bucket = optionService.getByPropertyOfNonNull(QiniuOssProperties.OSS_BUCKET).toString(); - String protocol = optionService.getByPropertyOfNonNull(QiniuOssProperties.OSS_PROTOCOL).toString(); - String domain = optionService.getByPropertyOfNonNull(QiniuOssProperties.OSS_DOMAIN).toString(); - String source = optionService.getByPropertyOrDefault(QiniuOssProperties.OSS_SOURCE, String.class, ""); - String styleRule = optionService.getByPropertyOrDefault(QiniuOssProperties.OSS_STYLE_RULE, String.class, ""); - String thumbnailStyleRule = optionService.getByPropertyOrDefault(QiniuOssProperties.OSS_THUMBNAIL_STYLE_RULE, String.class, ""); + String accessKey = + optionService.getByPropertyOfNonNull(QiniuOssProperties.OSS_ACCESS_KEY).toString(); + String secretKey = + optionService.getByPropertyOfNonNull(QiniuOssProperties.OSS_SECRET_KEY).toString(); + String bucket = + optionService.getByPropertyOfNonNull(QiniuOssProperties.OSS_BUCKET).toString(); + String protocol = + optionService.getByPropertyOfNonNull(QiniuOssProperties.OSS_PROTOCOL).toString(); + String domain = + optionService.getByPropertyOfNonNull(QiniuOssProperties.OSS_DOMAIN).toString(); + String source = + optionService.getByPropertyOrDefault(QiniuOssProperties.OSS_SOURCE, String.class, ""); + String styleRule = optionService + .getByPropertyOrDefault(QiniuOssProperties.OSS_STYLE_RULE, String.class, ""); + String thumbnailStyleRule = optionService + .getByPropertyOrDefault(QiniuOssProperties.OSS_THUMBNAIL_STYLE_RULE, String.class, ""); // Create configuration Configuration configuration = new Configuration(region); @@ -73,7 +82,9 @@ public UploadResult upload(MultipartFile file) { Auth auth = Auth.create(accessKey, secretKey); // Build put plicy StringMap putPolicy = new StringMap(); - putPolicy.put("returnBody", "{\"key\":\"$(key)\",\"hash\":\"$(etag)\",\"size\":$(fsize),\"width\":$(imageInfo.width),\"height\":$(imageInfo.height)}"); + putPolicy.put("returnBody", + "{\"key\":\"$(key)\",\"hash\":\"$(etag)\",\"size\":$(fsize),\"width\":$(imageInfo" + + ".width),\"height\":$(imageInfo.height)}"); // Get upload token String uploadToken = auth.uploadToken(bucket, null, 60 * 60, putPolicy); @@ -81,30 +92,32 @@ public UploadResult upload(MultipartFile file) { Path tmpPath = Paths.get(ensureSuffix(TEMP_DIR, FILE_SEPARATOR), bucket); StringBuilder basePath = new StringBuilder(protocol) - .append(domain) - .append(URL_SEPARATOR); + .append(domain) + .append(URL_SEPARATOR); try { - String basename = FilenameUtils.getBasename(Objects.requireNonNull(file.getOriginalFilename())); + String basename = + FilenameUtils.getBasename(Objects.requireNonNull(file.getOriginalFilename())); String extension = FilenameUtils.getExtension(file.getOriginalFilename()); String timestamp = String.valueOf(System.currentTimeMillis()); StringBuilder upFilePath = new StringBuilder(); if (StringUtils.isNotEmpty(source)) { upFilePath.append(source) - .append(URL_SEPARATOR); + .append(URL_SEPARATOR); } upFilePath.append(basename) - .append("_") - .append(timestamp) - .append(".") - .append(extension); + .append("_") + .append(timestamp) + .append(".") + .append(extension); // Get file recorder for temp directory FileRecorder fileRecorder = new FileRecorder(tmpPath.toFile()); // Get upload manager UploadManager uploadManager = new UploadManager(configuration, fileRecorder); // Put the file - Response response = uploadManager.put(file.getInputStream(), upFilePath.toString(), uploadToken, null, null); + Response response = uploadManager + .put(file.getInputStream(), upFilePath.toString(), uploadToken, null, null); if (log.isDebugEnabled()) { log.debug("Qiniu oss response: [{}]", response.toString()); @@ -132,7 +145,8 @@ public UploadResult upload(MultipartFile file) { if (ImageUtils.EXTENSION_ICO.equals(extension)) { result.setThumbPath(filePath); } else { - result.setThumbPath(StringUtils.isBlank(thumbnailStyleRule) ? filePath : filePath + thumbnailStyleRule); + result.setThumbPath(StringUtils.isBlank(thumbnailStyleRule) ? filePath : + filePath + thumbnailStyleRule); } } @@ -152,9 +166,12 @@ public void delete(String key) { Region region = optionService.getQiniuRegion(); - String accessKey = optionService.getByPropertyOfNonNull(QiniuOssProperties.OSS_ACCESS_KEY).toString(); - String secretKey = optionService.getByPropertyOfNonNull(QiniuOssProperties.OSS_SECRET_KEY).toString(); - String bucket = optionService.getByPropertyOfNonNull(QiniuOssProperties.OSS_BUCKET).toString(); + String accessKey = + optionService.getByPropertyOfNonNull(QiniuOssProperties.OSS_ACCESS_KEY).toString(); + String secretKey = + optionService.getByPropertyOfNonNull(QiniuOssProperties.OSS_SECRET_KEY).toString(); + String bucket = + optionService.getByPropertyOfNonNull(QiniuOssProperties.OSS_BUCKET).toString(); // Create configuration Configuration configuration = new Configuration(region); diff --git a/src/main/java/run/halo/app/handler/file/SmmsFileHandler.java b/src/main/java/run/halo/app/handler/file/SmmsFileHandler.java index 71b6cd6a50..66b709efaa 100644 --- a/src/main/java/run/halo/app/handler/file/SmmsFileHandler.java +++ b/src/main/java/run/halo/app/handler/file/SmmsFileHandler.java @@ -1,10 +1,17 @@ package run.halo.app.handler.file; import com.fasterxml.jackson.annotation.JsonProperty; +import java.io.IOException; +import java.util.Collections; +import java.util.Objects; import lombok.Data; import lombok.NoArgsConstructor; import lombok.extern.slf4j.Slf4j; -import org.springframework.http.*; +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.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.lang.Nullable; import org.springframework.stereotype.Component; @@ -23,10 +30,6 @@ import run.halo.app.utils.FilenameUtils; import run.halo.app.utils.HttpClientUtils; -import java.io.IOException; -import java.util.Collections; -import java.util.Objects; - /** * Sm.ms file handler. * @@ -39,16 +42,16 @@ public class SmmsFileHandler implements FileHandler { @Deprecated - private final static String UPLOAD_API = "https://sm.ms/api/upload"; + private static final String UPLOAD_API = "https://sm.ms/api/upload"; - private final static String UPLOAD_API_V2 = "https://sm.ms/api/v2/upload"; + private static final String UPLOAD_API_V2 = "https://sm.ms/api/v2/upload"; @Deprecated - private final static String DELETE_API = "https://sm.ms/api/delete/%s"; + private static final String DELETE_API = "https://sm.ms/api/delete/%s"; - private final static String DELETE_API_V2 = "https://sm.ms/api/v2/delete/%s"; + private static final String DELETE_API_V2 = "https://sm.ms/api/v2/delete/%s"; - private final static String SUCCESS_CODE = "success"; + private static final String SUCCESS_CODE = "success"; private final RestTemplate httpsRestTemplate; @@ -57,12 +60,14 @@ public class SmmsFileHandler implements FileHandler { private final HttpHeaders headers = new HttpHeaders(); public SmmsFileHandler(RestTemplate httpsRestTemplate, - OptionService optionService) { + OptionService optionService) { this.httpsRestTemplate = httpsRestTemplate; this.optionService = optionService; - MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter(); - mappingJackson2HttpMessageConverter.setSupportedMediaTypes(Collections.singletonList(MediaType.ALL)); + MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = + new MappingJackson2HttpMessageConverter(); + mappingJackson2HttpMessageConverter + .setSupportedMediaTypes(Collections.singletonList(MediaType.ALL)); this.httpsRestTemplate.getMessageConverters().add(mappingJackson2HttpMessageConverter); } @@ -70,7 +75,8 @@ public SmmsFileHandler(RestTemplate httpsRestTemplate, public UploadResult upload(MultipartFile file) { Assert.notNull(file, "Multipart file must not be null"); - String apiSecretToken = optionService.getByPropertyOfNonNull(SmmsProperties.SMMS_API_SECRET_TOKEN).toString(); + String apiSecretToken = + optionService.getByPropertyOfNonNull(SmmsProperties.SMMS_API_SECRET_TOKEN).toString(); if (StringUtils.isEmpty(apiSecretToken)) { throw new ServiceException("请先设置 SM.MS 的 Secret Token"); @@ -88,23 +94,28 @@ public UploadResult upload(MultipartFile file) { LinkedMultiValueMap body = new LinkedMultiValueMap<>(); try { - body.add("smfile", new HttpClientUtils.MultipartFileResource(file.getBytes(), file.getOriginalFilename())); + body.add("smfile", new HttpClientUtils.MultipartFileResource(file.getBytes(), + file.getOriginalFilename())); } catch (IOException e) { log.error("Failed to get file input stream", e); - throw new FileOperationException("上传附件 " + file.getOriginalFilename() + " 到 SM.MS 失败", e); + throw new FileOperationException("上传附件 " + file.getOriginalFilename() + " 到 SM.MS 失败", + e); } body.add("format", "json"); - HttpEntity> httpEntity = new HttpEntity<>(body, headers); + HttpEntity> httpEntity = + new HttpEntity<>(body, headers); // Upload file - ResponseEntity mapResponseEntity = httpsRestTemplate.postForEntity(UPLOAD_API_V2, httpEntity, SmmsResponse.class); + ResponseEntity mapResponseEntity = + httpsRestTemplate.postForEntity(UPLOAD_API_V2, httpEntity, SmmsResponse.class); // Check status if (mapResponseEntity.getStatusCode().isError()) { log.error("Server response detail: [{}]", mapResponseEntity.toString()); - throw new FileOperationException("SM.MS 服务状态异常,状态码: " + mapResponseEntity.getStatusCodeValue()); + throw new FileOperationException( + "SM.MS 服务状态异常,状态码: " + mapResponseEntity.getStatusCodeValue()); } // Get smms response @@ -113,11 +124,14 @@ public UploadResult upload(MultipartFile file) { // Check error if (!isResponseSuccessfully(smmsResponse)) { log.error("Smms response detail: [{}]", smmsResponse); - throw new FileOperationException(smmsResponse == null ? "SM.MS 服务返回内容为空" : smmsResponse.getMessage()).setErrorData(smmsResponse); + throw new FileOperationException( + smmsResponse == null ? "SM.MS 服务返回内容为空" : smmsResponse.getMessage()) + .setErrorData(smmsResponse); } if (!smmsResponse.getSuccess()) { - throw new FileOperationException("上传请求失败:" + smmsResponse.getMessage()).setErrorData(smmsResponse); + throw new FileOperationException("上传请求失败:" + smmsResponse.getMessage()) + .setErrorData(smmsResponse); } // Get response data @@ -125,7 +139,8 @@ public UploadResult upload(MultipartFile file) { // Build result UploadResult result = new UploadResult(); - result.setFilename(FilenameUtils.getBasename(Objects.requireNonNull(file.getOriginalFilename()))); + result.setFilename( + FilenameUtils.getBasename(Objects.requireNonNull(file.getOriginalFilename()))); result.setSuffix(FilenameUtils.getExtension(file.getOriginalFilename())); result.setMediaType(MediaType.valueOf(Objects.requireNonNull(file.getContentType()))); @@ -151,7 +166,8 @@ public void delete(String key) { setHeaders(); // Delete the file - ResponseEntity responseEntity = httpsRestTemplate.exchange(url, HttpMethod.GET, new HttpEntity<>(null, headers), String.class); + ResponseEntity responseEntity = httpsRestTemplate + .exchange(url, HttpMethod.GET, new HttpEntity<>(null, headers), String.class); if (responseEntity.getStatusCode().isError()) { log.debug("Smms server response error: [{}]", responseEntity.toString()); @@ -184,7 +200,8 @@ private boolean isResponseSuccessfully(@Nullable SmmsResponse smmsResponse) { */ private void setHeaders() { headers.set(HttpHeaders.USER_AGENT, "Halo/" + HaloConst.HALO_VERSION); - headers.set(HttpHeaders.AUTHORIZATION, optionService.getByPropertyOfNonNull(SmmsProperties.SMMS_API_SECRET_TOKEN).toString()); + headers.set(HttpHeaders.AUTHORIZATION, + optionService.getByPropertyOfNonNull(SmmsProperties.SMMS_API_SECRET_TOKEN).toString()); } @Data diff --git a/src/main/java/run/halo/app/handler/file/TencentCosFileHandler.java b/src/main/java/run/halo/app/handler/file/TencentCosFileHandler.java index 0c02939495..c7305c7c6d 100644 --- a/src/main/java/run/halo/app/handler/file/TencentCosFileHandler.java +++ b/src/main/java/run/halo/app/handler/file/TencentCosFileHandler.java @@ -1,6 +1,8 @@ package run.halo.app.handler.file; +import static run.halo.app.model.support.HaloConst.URL_SEPARATOR; + import com.qcloud.cos.COSClient; import com.qcloud.cos.ClientConfig; import com.qcloud.cos.auth.BasicCOSCredentials; @@ -8,6 +10,7 @@ import com.qcloud.cos.model.ObjectMetadata; import com.qcloud.cos.model.PutObjectResult; import com.qcloud.cos.region.Region; +import java.util.Objects; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.http.MediaType; @@ -22,10 +25,6 @@ import run.halo.app.utils.FilenameUtils; import run.halo.app.utils.ImageUtils; -import java.util.Objects; - -import static run.halo.app.model.support.HaloConst.URL_SEPARATOR; - /** * Tencent cos file handler. * @@ -48,15 +47,25 @@ public UploadResult upload(MultipartFile file) { Assert.notNull(file, "Multipart file must not be null"); // Get config - String protocol = optionService.getByPropertyOfNonNull(TencentCosProperties.COS_PROTOCOL).toString(); - String domain = optionService.getByPropertyOrDefault(TencentCosProperties.COS_DOMAIN, String.class, ""); - String region = optionService.getByPropertyOfNonNull(TencentCosProperties.COS_REGION).toString(); - String secretId = optionService.getByPropertyOfNonNull(TencentCosProperties.COS_SECRET_ID).toString(); - String secretKey = optionService.getByPropertyOfNonNull(TencentCosProperties.COS_SECRET_KEY).toString(); - String bucketName = optionService.getByPropertyOfNonNull(TencentCosProperties.COS_BUCKET_NAME).toString(); - String source = optionService.getByPropertyOrDefault(TencentCosProperties.COS_SOURCE, String.class, ""); - String styleRule = optionService.getByPropertyOrDefault(TencentCosProperties.COS_STYLE_RULE, String.class, ""); - String thumbnailStyleRule = optionService.getByPropertyOrDefault(TencentCosProperties.COS_THUMBNAIL_STYLE_RULE, String.class, ""); + String protocol = + optionService.getByPropertyOfNonNull(TencentCosProperties.COS_PROTOCOL).toString(); + String domain = + optionService.getByPropertyOrDefault(TencentCosProperties.COS_DOMAIN, String.class, ""); + String region = + optionService.getByPropertyOfNonNull(TencentCosProperties.COS_REGION).toString(); + String secretId = + optionService.getByPropertyOfNonNull(TencentCosProperties.COS_SECRET_ID).toString(); + String secretKey = + optionService.getByPropertyOfNonNull(TencentCosProperties.COS_SECRET_KEY).toString(); + String bucketName = + optionService.getByPropertyOfNonNull(TencentCosProperties.COS_BUCKET_NAME).toString(); + String source = + optionService.getByPropertyOrDefault(TencentCosProperties.COS_SOURCE, String.class, ""); + String styleRule = optionService + .getByPropertyOrDefault(TencentCosProperties.COS_STYLE_RULE, String.class, ""); + String thumbnailStyleRule = optionService + .getByPropertyOrDefault(TencentCosProperties.COS_THUMBNAIL_STYLE_RULE, String.class, + ""); COSCredentials cred = new BasicCOSCredentials(secretId, secretKey); Region regionConfig = new Region(region); @@ -69,31 +78,32 @@ public UploadResult upload(MultipartFile file) { if (StringUtils.isNotEmpty(domain)) { basePath.append(domain) - .append(URL_SEPARATOR); + .append(URL_SEPARATOR); } else { basePath.append(bucketName) - .append(".cos.") - .append(region) - .append(".myqcloud.com") - .append(URL_SEPARATOR); + .append(".cos.") + .append(region) + .append(".myqcloud.com") + .append(URL_SEPARATOR); } try { - String basename = FilenameUtils.getBasename(Objects.requireNonNull(file.getOriginalFilename())); + String basename = + FilenameUtils.getBasename(Objects.requireNonNull(file.getOriginalFilename())); String extension = FilenameUtils.getExtension(file.getOriginalFilename()); String timestamp = String.valueOf(System.currentTimeMillis()); StringBuilder upFilePath = new StringBuilder(); if (StringUtils.isNotEmpty(source)) { upFilePath.append(source) - .append(URL_SEPARATOR); + .append(URL_SEPARATOR); } upFilePath.append(basename) - .append("_") - .append(timestamp) - .append(".") - .append(extension); + .append("_") + .append(timestamp) + .append(".") + .append(extension); String filePath = StringUtils.join(basePath.toString(), upFilePath.toString()); @@ -103,7 +113,9 @@ public UploadResult upload(MultipartFile file) { objectMetadata.setContentLength(file.getSize()); // 设置 Content type, 默认是 application/octet-stream objectMetadata.setContentType(file.getContentType()); - PutObjectResult putObjectResponseFromInputStream = cosClient.putObject(bucketName, upFilePath.toString(), file.getInputStream(), objectMetadata); + PutObjectResult putObjectResponseFromInputStream = cosClient + .putObject(bucketName, upFilePath.toString(), file.getInputStream(), + objectMetadata); if (putObjectResponseFromInputStream == null) { throw new FileOperationException("上传附件 " + file.getOriginalFilename() + " 到腾讯云失败 "); } @@ -111,9 +123,11 @@ public UploadResult upload(MultipartFile file) { // Response result UploadResult uploadResult = new UploadResult(); uploadResult.setFilename(basename); - uploadResult.setFilePath(StringUtils.isBlank(styleRule) ? filePath : filePath + styleRule); + uploadResult + .setFilePath(StringUtils.isBlank(styleRule) ? filePath : filePath + styleRule); uploadResult.setKey(upFilePath.toString()); - uploadResult.setMediaType(MediaType.valueOf(Objects.requireNonNull(file.getContentType()))); + uploadResult + .setMediaType(MediaType.valueOf(Objects.requireNonNull(file.getContentType()))); uploadResult.setSuffix(extension); uploadResult.setSize(file.getSize()); @@ -123,7 +137,8 @@ public UploadResult upload(MultipartFile file) { uploadResult.setThumbPath(filePath); return filePath; } else { - return StringUtils.isBlank(thumbnailStyleRule) ? filePath : filePath + thumbnailStyleRule; + return StringUtils.isBlank(thumbnailStyleRule) ? filePath : + filePath + thumbnailStyleRule; } }); return uploadResult; @@ -139,10 +154,14 @@ public void delete(String key) { Assert.notNull(key, "File key must not be blank"); // Get config - String region = optionService.getByPropertyOfNonNull(TencentCosProperties.COS_REGION).toString(); - String secretId = optionService.getByPropertyOfNonNull(TencentCosProperties.COS_SECRET_ID).toString(); - String secretKey = optionService.getByPropertyOfNonNull(TencentCosProperties.COS_SECRET_KEY).toString(); - String bucketName = optionService.getByPropertyOfNonNull(TencentCosProperties.COS_BUCKET_NAME).toString(); + String region = + optionService.getByPropertyOfNonNull(TencentCosProperties.COS_REGION).toString(); + String secretId = + optionService.getByPropertyOfNonNull(TencentCosProperties.COS_SECRET_ID).toString(); + String secretKey = + optionService.getByPropertyOfNonNull(TencentCosProperties.COS_SECRET_KEY).toString(); + String bucketName = + optionService.getByPropertyOfNonNull(TencentCosProperties.COS_BUCKET_NAME).toString(); COSCredentials cred = new BasicCOSCredentials(secretId, secretKey); Region regionConfig = new Region(region); diff --git a/src/main/java/run/halo/app/handler/file/UpOssFileHandler.java b/src/main/java/run/halo/app/handler/file/UpOssFileHandler.java index f52b770963..e8dc537efc 100644 --- a/src/main/java/run/halo/app/handler/file/UpOssFileHandler.java +++ b/src/main/java/run/halo/app/handler/file/UpOssFileHandler.java @@ -2,6 +2,10 @@ import com.upyun.RestManager; import com.upyun.UpException; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; import lombok.extern.slf4j.Slf4j; import okhttp3.Response; import org.apache.commons.lang3.StringUtils; @@ -18,11 +22,6 @@ import run.halo.app.utils.FilenameUtils; import run.halo.app.utils.ImageUtils; -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; -import java.util.Objects; - /** * Up oss file handler. * @@ -45,14 +44,19 @@ public UploadResult upload(MultipartFile file) { Assert.notNull(file, "Multipart file must not be null"); String source = optionService.getByPropertyOfNonNull(UpOssProperties.OSS_SOURCE).toString(); - String password = optionService.getByPropertyOfNonNull(UpOssProperties.OSS_PASSWORD).toString(); + String password = + optionService.getByPropertyOfNonNull(UpOssProperties.OSS_PASSWORD).toString(); String bucket = optionService.getByPropertyOfNonNull(UpOssProperties.OSS_BUCKET).toString(); - String protocol = optionService.getByPropertyOfNonNull(UpOssProperties.OSS_PROTOCOL).toString(); + String protocol = + optionService.getByPropertyOfNonNull(UpOssProperties.OSS_PROTOCOL).toString(); String domain = optionService.getByPropertyOfNonNull(UpOssProperties.OSS_DOMAIN).toString(); - String operator = optionService.getByPropertyOfNonNull(UpOssProperties.OSS_OPERATOR).toString(); + String operator = + optionService.getByPropertyOfNonNull(UpOssProperties.OSS_OPERATOR).toString(); // style rule can be null - String styleRule = optionService.getByPropertyOrDefault(UpOssProperties.OSS_STYLE_RULE, String.class, ""); - String thumbnailStyleRule = optionService.getByPropertyOrDefault(UpOssProperties.OSS_THUMBNAIL_STYLE_RULE, String.class, ""); + String styleRule = + optionService.getByPropertyOrDefault(UpOssProperties.OSS_STYLE_RULE, String.class, ""); + String thumbnailStyleRule = optionService + .getByPropertyOrDefault(UpOssProperties.OSS_THUMBNAIL_STYLE_RULE, String.class, ""); RestManager manager = new RestManager(bucket, operator, password); manager.setTimeout(60 * 10); @@ -62,19 +66,22 @@ public UploadResult upload(MultipartFile file) { try { // Get file basename - String basename = FilenameUtils.getBasename(Objects.requireNonNull(file.getOriginalFilename())); + String basename = + FilenameUtils.getBasename(Objects.requireNonNull(file.getOriginalFilename())); // Get file extension String extension = FilenameUtils.getExtension(file.getOriginalFilename()); // Get md5 value of the file String md5OfFile = DigestUtils.md5DigestAsHex(file.getInputStream()); // Build file path - String upFilePath = StringUtils.appendIfMissing(source, "/") + md5OfFile + '.' + extension; + String upFilePath = + StringUtils.appendIfMissing(source, "/") + md5OfFile + '.' + extension; // Set md5Content params.put(RestManager.PARAMS.CONTENT_MD5.getValue(), md5OfFile); // Write file Response result = manager.writeFile(upFilePath, file.getInputStream(), params); if (!result.isSuccessful()) { - throw new FileOperationException("上传附件 " + file.getOriginalFilename() + " 到又拍云失败" + upFilePath); + throw new FileOperationException( + "上传附件 " + file.getOriginalFilename() + " 到又拍云失败" + upFilePath); } String filePath = protocol + StringUtils.removeEnd(domain, "/") + upFilePath; @@ -82,9 +89,11 @@ public UploadResult upload(MultipartFile file) { // Build upload result UploadResult uploadResult = new UploadResult(); uploadResult.setFilename(basename); - uploadResult.setFilePath(StringUtils.isBlank(styleRule) ? filePath : filePath + styleRule); + uploadResult + .setFilePath(StringUtils.isBlank(styleRule) ? filePath : filePath + styleRule); uploadResult.setKey(upFilePath); - uploadResult.setMediaType(MediaType.valueOf(Objects.requireNonNull(file.getContentType()))); + uploadResult + .setMediaType(MediaType.valueOf(Objects.requireNonNull(file.getContentType()))); uploadResult.setSuffix(extension); uploadResult.setSize(file.getSize()); @@ -94,7 +103,8 @@ public UploadResult upload(MultipartFile file) { uploadResult.setThumbPath(filePath); return filePath; } else { - return StringUtils.isBlank(thumbnailStyleRule) ? filePath : filePath + thumbnailStyleRule; + return StringUtils.isBlank(thumbnailStyleRule) ? filePath : + filePath + thumbnailStyleRule; } }); return uploadResult; @@ -108,9 +118,11 @@ public void delete(String key) { Assert.notNull(key, "File key must not be blank"); // Get config - String password = optionService.getByPropertyOfNonNull(UpOssProperties.OSS_PASSWORD).toString(); + String password = + optionService.getByPropertyOfNonNull(UpOssProperties.OSS_PASSWORD).toString(); String bucket = optionService.getByPropertyOfNonNull(UpOssProperties.OSS_BUCKET).toString(); - String operator = optionService.getByPropertyOfNonNull(UpOssProperties.OSS_OPERATOR).toString(); + String operator = + optionService.getByPropertyOfNonNull(UpOssProperties.OSS_OPERATOR).toString(); RestManager manager = new RestManager(bucket, operator, password); manager.setTimeout(60 * 10); diff --git a/src/main/java/run/halo/app/handler/migrate/HaloMigrateHandler.java b/src/main/java/run/halo/app/handler/migrate/HaloMigrateHandler.java index d55495fe51..8eca159934 100644 --- a/src/main/java/run/halo/app/handler/migrate/HaloMigrateHandler.java +++ b/src/main/java/run/halo/app/handler/migrate/HaloMigrateHandler.java @@ -1,12 +1,11 @@ package run.halo.app.handler.migrate; +import java.io.IOException; import org.springframework.stereotype.Component; import org.springframework.web.multipart.MultipartFile; import run.halo.app.model.enums.MigrateType; import run.halo.app.service.BackupService; -import java.io.IOException; - /** * @author ryanwang * @date 2020-03-14 diff --git a/src/main/java/run/halo/app/handler/migrate/MigrateHandlers.java b/src/main/java/run/halo/app/handler/migrate/MigrateHandlers.java index 325c8fe923..fb61b1550a 100644 --- a/src/main/java/run/halo/app/handler/migrate/MigrateHandlers.java +++ b/src/main/java/run/halo/app/handler/migrate/MigrateHandlers.java @@ -1,5 +1,7 @@ package run.halo.app.handler.migrate; +import java.util.Collection; +import java.util.LinkedList; import lombok.extern.slf4j.Slf4j; import org.springframework.context.ApplicationContext; import org.springframework.lang.NonNull; @@ -11,9 +13,6 @@ import run.halo.app.exception.FileOperationException; import run.halo.app.model.enums.MigrateType; -import java.util.Collection; -import java.util.LinkedList; - /** * Migrate handler manager. * @@ -46,7 +45,8 @@ public void upload(@NonNull MultipartFile file, @NonNull MigrateType migrateType } } - throw new FileOperationException("No available migrate handler to migrate the file").setErrorData(migrateType); + throw new FileOperationException("No available migrate handler to migrate the file") + .setErrorData(migrateType); } /** @@ -56,7 +56,8 @@ public void upload(@NonNull MultipartFile file, @NonNull MigrateType migrateType * @return current migrate handlers */ @NonNull - private MigrateHandlers addMigrateHandlers(@Nullable Collection migrateHandlers) { + private MigrateHandlers addMigrateHandlers( + @Nullable Collection migrateHandlers) { if (!CollectionUtils.isEmpty(migrateHandlers)) { this.migrateHandlers.addAll(migrateHandlers); } diff --git a/src/main/java/run/halo/app/handler/theme/config/ThemeConfigResolver.java b/src/main/java/run/halo/app/handler/theme/config/ThemeConfigResolver.java index 6118ae46ba..7ce4328cb5 100644 --- a/src/main/java/run/halo/app/handler/theme/config/ThemeConfigResolver.java +++ b/src/main/java/run/halo/app/handler/theme/config/ThemeConfigResolver.java @@ -1,10 +1,9 @@ package run.halo.app.handler.theme.config; -import org.springframework.lang.NonNull; -import run.halo.app.handler.theme.config.support.Group; - import java.io.IOException; import java.util.List; +import org.springframework.lang.NonNull; +import run.halo.app.handler.theme.config.support.Group; /** * Theme config resolver interface. diff --git a/src/main/java/run/halo/app/handler/theme/config/ThemePropertyResolver.java b/src/main/java/run/halo/app/handler/theme/config/ThemePropertyResolver.java index 8c3c8db021..fec244703c 100644 --- a/src/main/java/run/halo/app/handler/theme/config/ThemePropertyResolver.java +++ b/src/main/java/run/halo/app/handler/theme/config/ThemePropertyResolver.java @@ -1,10 +1,9 @@ package run.halo.app.handler.theme.config; +import java.io.IOException; import org.springframework.lang.NonNull; import run.halo.app.handler.theme.config.support.ThemeProperty; -import java.io.IOException; - /** * Theme file resolver. * diff --git a/src/main/java/run/halo/app/handler/theme/config/impl/YamlThemeConfigResolverImpl.java b/src/main/java/run/halo/app/handler/theme/config/impl/YamlThemeConfigResolverImpl.java index aed539068d..316a99264b 100644 --- a/src/main/java/run/halo/app/handler/theme/config/impl/YamlThemeConfigResolverImpl.java +++ b/src/main/java/run/halo/app/handler/theme/config/impl/YamlThemeConfigResolverImpl.java @@ -2,6 +2,11 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; +import java.io.IOException; +import java.util.Collections; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; import lombok.extern.slf4j.Slf4j; import org.springframework.lang.Nullable; import org.springframework.stereotype.Service; @@ -12,12 +17,6 @@ import run.halo.app.model.enums.DataType; import run.halo.app.model.enums.InputType; -import java.io.IOException; -import java.util.Collections; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; - /** * Theme configuration resolver. * @@ -114,7 +113,8 @@ private List handleItems(@Nullable Object items) { item.setLabel(itemMap.getOrDefault("label", item.getName()).toString()); Object dataType = itemMap.getOrDefault("data-type", itemMap.get("dataType")); item.setType(InputType.typeOf(itemMap.get("type"))); - item.setDataType(item.getType().equals(InputType.SWITCH) ? DataType.BOOL : DataType.typeOf(dataType)); + item.setDataType(item.getType().equals(InputType.SWITCH) ? DataType.BOOL : + DataType.typeOf(dataType)); item.setDefaultValue(itemMap.get("default")); item.setPlaceholder(itemMap.getOrDefault("placeholder", "").toString()); item.setDescription(itemMap.getOrDefault("description", "").toString()); @@ -141,7 +141,8 @@ private List handleItems(@Nullable Object items) { item.setLabel(itemMap.getOrDefault("label", item.getName()).toString()); Object dataType = itemMap.getOrDefault("data-type", itemMap.get("dataType")); item.setType(InputType.typeOf(itemMap.get("type"))); - item.setDataType(item.getType().equals(InputType.SWITCH) ? DataType.BOOL : DataType.typeOf(dataType)); + item.setDataType(item.getType().equals(InputType.SWITCH) ? DataType.BOOL : + DataType.typeOf(dataType)); item.setDefaultValue(itemMap.get("default")); item.setPlaceholder(itemMap.getOrDefault("placeholder", "").toString()); item.setDescription(itemMap.getOrDefault("description", "").toString()); diff --git a/src/main/java/run/halo/app/handler/theme/config/impl/YamlThemePropertyResolver.java b/src/main/java/run/halo/app/handler/theme/config/impl/YamlThemePropertyResolver.java index d42e590504..46492ee13c 100644 --- a/src/main/java/run/halo/app/handler/theme/config/impl/YamlThemePropertyResolver.java +++ b/src/main/java/run/halo/app/handler/theme/config/impl/YamlThemePropertyResolver.java @@ -1,5 +1,6 @@ package run.halo.app.handler.theme.config.impl; +import java.io.IOException; import org.springframework.lang.NonNull; import org.springframework.stereotype.Service; import org.springframework.util.Assert; @@ -7,8 +8,6 @@ import run.halo.app.handler.theme.config.support.ThemeProperty; import run.halo.app.theme.YamlResolver; -import java.io.IOException; - /** * Yaml theme file resolver. * diff --git a/src/main/java/run/halo/app/handler/theme/config/support/Group.java b/src/main/java/run/halo/app/handler/theme/config/support/Group.java index e8f78037cf..68e80dbf20 100644 --- a/src/main/java/run/halo/app/handler/theme/config/support/Group.java +++ b/src/main/java/run/halo/app/handler/theme/config/support/Group.java @@ -1,8 +1,7 @@ package run.halo.app.handler.theme.config.support; -import lombok.Data; - import java.util.List; +import lombok.Data; /** * Theme configuration: group entity. diff --git a/src/main/java/run/halo/app/handler/theme/config/support/Item.java b/src/main/java/run/halo/app/handler/theme/config/support/Item.java index 1e31c2495f..c32fd3d653 100644 --- a/src/main/java/run/halo/app/handler/theme/config/support/Item.java +++ b/src/main/java/run/halo/app/handler/theme/config/support/Item.java @@ -1,12 +1,11 @@ package run.halo.app.handler.theme.config.support; +import java.util.List; +import java.util.Objects; import lombok.Data; import run.halo.app.model.enums.DataType; import run.halo.app.model.enums.InputType; -import java.util.List; -import java.util.Objects; - /** * Theme configuration: item entity * diff --git a/src/main/java/run/halo/app/handler/theme/config/support/ThemeProperty.java b/src/main/java/run/halo/app/handler/theme/config/support/ThemeProperty.java index eaf5722b88..263e13dc52 100644 --- a/src/main/java/run/halo/app/handler/theme/config/support/ThemeProperty.java +++ b/src/main/java/run/halo/app/handler/theme/config/support/ThemeProperty.java @@ -1,9 +1,8 @@ package run.halo.app.handler.theme.config.support; -import lombok.Data; - import java.util.Objects; import java.util.Set; +import lombok.Data; /** * Theme property. diff --git a/src/main/java/run/halo/app/listener/StartedListener.java b/src/main/java/run/halo/app/listener/StartedListener.java index 5c95abc5be..49fc9f0609 100644 --- a/src/main/java/run/halo/app/listener/StartedListener.java +++ b/src/main/java/run/halo/app/listener/StartedListener.java @@ -1,5 +1,17 @@ package run.halo.app.listener; +import java.io.IOException; +import java.net.URI; +import java.nio.file.FileSystem; +import java.nio.file.FileSystemNotFoundException; +import java.nio.file.FileSystems; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.sql.Connection; +import java.sql.DatabaseMetaData; +import java.sql.SQLException; +import java.util.Collections; import lombok.extern.slf4j.Slf4j; import org.flywaydb.core.Flyway; import org.flywaydb.core.internal.jdbc.JdbcUtils; @@ -22,14 +34,6 @@ import run.halo.app.service.ThemeService; import run.halo.app.utils.FileUtils; -import java.io.IOException; -import java.net.URI; -import java.nio.file.*; -import java.sql.Connection; -import java.sql.DatabaseMetaData; -import java.sql.SQLException; -import java.util.Collections; - /** * The method executed after the application is started. * @@ -75,9 +79,13 @@ public void onApplicationEvent(ApplicationStartedEvent event) { private void printStartInfo() { String blogUrl = optionService.getBlogBaseUrl(); log.info(AnsiOutput.toString(AnsiColor.BRIGHT_BLUE, "Halo started at ", blogUrl)); - log.info(AnsiOutput.toString(AnsiColor.BRIGHT_BLUE, "Halo admin started at ", blogUrl, "/", haloProperties.getAdminPath())); + log.info(AnsiOutput + .toString(AnsiColor.BRIGHT_BLUE, "Halo admin started at ", blogUrl, "/", + haloProperties.getAdminPath())); if (!haloProperties.isDocDisabled()) { - log.debug(AnsiOutput.toString(AnsiColor.BRIGHT_BLUE, "Halo api doc was enabled at ", blogUrl, "/swagger-ui.html")); + log.debug(AnsiOutput + .toString(AnsiColor.BRIGHT_BLUE, "Halo api doc was enabled at ", blogUrl, + "/swagger-ui.html")); } log.info(AnsiOutput.toString(AnsiColor.BRIGHT_YELLOW, "Halo has started successfully!")); } @@ -89,12 +97,12 @@ private void migrate() throws SQLException { log.info("Starting migrate database..."); Flyway flyway = Flyway - .configure() - .locations("classpath:/migration") - .baselineVersion("1") - .baselineOnMigrate(true) - .dataSource(url, username, password) - .load(); + .configure() + .locations("classpath:/migration") + .baselineVersion("1") + .baselineOnMigrate(true) + .dataSource(url, username, password) + .load(); flyway.repair(); flyway.migrate(); @@ -105,7 +113,8 @@ private void migrate() throws SQLException { DatabaseMetaData databaseMetaData = JdbcUtils.getDatabaseMetaData(connection); // Gets database product name - HaloConst.DATABASE_PRODUCT_NAME = databaseMetaData.getDatabaseProductName() + " " + databaseMetaData.getDatabaseProductVersion(); + HaloConst.DATABASE_PRODUCT_NAME = databaseMetaData.getDatabaseProductName() + " " + + databaseMetaData.getDatabaseProductVersion(); // Close connection. connection.close(); @@ -118,7 +127,8 @@ private void migrate() throws SQLException { */ private void initThemes() { // Whether the blog has initialized - Boolean isInstalled = optionService.getByPropertyOrDefault(PrimaryProperties.IS_INSTALLED, Boolean.class, false); + Boolean isInstalled = optionService + .getByPropertyOrDefault(PrimaryProperties.IS_INSTALLED, Boolean.class, false); try { String themeClassPath = ResourceUtils.CLASSPATH_URL_PREFIX + ThemeService.THEME_FOLDER; diff --git a/src/main/java/run/halo/app/listener/comment/CommentEventListener.java b/src/main/java/run/halo/app/listener/comment/CommentEventListener.java index bb32d937fa..f3e79de6d1 100644 --- a/src/main/java/run/halo/app/listener/comment/CommentEventListener.java +++ b/src/main/java/run/halo/app/listener/comment/CommentEventListener.java @@ -2,6 +2,8 @@ import cn.hutool.core.lang.Validator; import cn.hutool.core.text.StrBuilder; +import java.util.HashMap; +import java.util.Map; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.context.event.EventListener; @@ -12,12 +14,21 @@ import run.halo.app.exception.ServiceException; import run.halo.app.mail.MailService; import run.halo.app.model.dto.post.BasePostMinimalDTO; -import run.halo.app.model.entity.*; +import run.halo.app.model.entity.Journal; +import run.halo.app.model.entity.JournalComment; +import run.halo.app.model.entity.PostComment; +import run.halo.app.model.entity.SheetComment; +import run.halo.app.model.entity.User; import run.halo.app.model.properties.CommentProperties; -import run.halo.app.service.*; - -import java.util.HashMap; -import java.util.Map; +import run.halo.app.service.JournalCommentService; +import run.halo.app.service.JournalService; +import run.halo.app.service.OptionService; +import run.halo.app.service.PostCommentService; +import run.halo.app.service.PostService; +import run.halo.app.service.SheetCommentService; +import run.halo.app.service.SheetService; +import run.halo.app.service.ThemeService; +import run.halo.app.service.UserService; /** * PostComment event listener. @@ -50,7 +61,11 @@ public class CommentEventListener { private final ThemeService themeService; - public CommentEventListener(MailService mailService, OptionService optionService, PostCommentService postCommentService, SheetCommentService sheetCommentService, JournalCommentService journalCommentService, PostService postService, SheetService sheetService, JournalService journalService, UserService userService, ThemeService themeService) { + public CommentEventListener(MailService mailService, OptionService optionService, + PostCommentService postCommentService, SheetCommentService sheetCommentService, + JournalCommentService journalCommentService, PostService postService, + SheetService sheetService, JournalService journalService, UserService userService, + ThemeService themeService) { this.mailService = mailService; this.optionService = optionService; this.postCommentService = postCommentService; @@ -71,14 +86,16 @@ public CommentEventListener(MailService mailService, OptionService optionService @Async @EventListener public void handleCommentNewEvent(CommentNewEvent newEvent) { - Boolean newCommentNotice = optionService.getByPropertyOrDefault(CommentProperties.NEW_NOTICE, Boolean.class, false); + Boolean newCommentNotice = optionService + .getByPropertyOrDefault(CommentProperties.NEW_NOTICE, Boolean.class, false); if (!newCommentNotice) { // Skip mailing return; } - User user = userService.getCurrentUser().orElseThrow(() -> new ServiceException("未查询到博主信息")); + User user = + userService.getCurrentUser().orElseThrow(() -> new ServiceException("未查询到博主信息")); Map data = new HashMap<>(); @@ -92,32 +109,36 @@ public void handleCommentNewEvent(CommentNewEvent newEvent) { log.debug("Got post comment: [{}]", postComment); - BasePostMinimalDTO post = postService.convertToMinimal(postService.getById(postComment.getPostId())); + BasePostMinimalDTO post = + postService.convertToMinimal(postService.getById(postComment.getPostId())); - data.put("pageFullPath", enabledAbsolutePath ? post.getFullPath() : optionService.getBlogBaseUrl() + post.getFullPath()); + data.put("pageFullPath", enabledAbsolutePath ? post.getFullPath() : + optionService.getBlogBaseUrl() + post.getFullPath()); data.put("pageTitle", post.getTitle()); data.put("author", postComment.getAuthor()); data.put("content", postComment.getContent()); subject.append("您的博客文章《") - .append(post.getTitle()) - .append("》有了新的评论。"); + .append(post.getTitle()) + .append("》有了新的评论。"); } else if (newEvent.getSource() instanceof SheetCommentService) { SheetComment sheetComment = sheetCommentService.getById(newEvent.getCommentId()); log.debug("Got sheet comment: [{}]", sheetComment); - BasePostMinimalDTO sheet = sheetService.convertToMinimal(sheetService.getById(sheetComment.getPostId())); + BasePostMinimalDTO sheet = + sheetService.convertToMinimal(sheetService.getById(sheetComment.getPostId())); - data.put("pageFullPath", enabledAbsolutePath ? sheet.getFullPath() : optionService.getBlogBaseUrl() + sheet.getFullPath()); + data.put("pageFullPath", enabledAbsolutePath ? sheet.getFullPath() : + optionService.getBlogBaseUrl() + sheet.getFullPath()); data.put("pageTitle", sheet.getTitle()); data.put("author", sheetComment.getAuthor()); data.put("content", sheetComment.getContent()); subject.append("您的博客页面《") - .append(sheet.getTitle()) - .append("》有了新的评论。"); + .append(sheet.getTitle()) + .append("》有了新的评论。"); } else if (newEvent.getSource() instanceof JournalCommentService) { JournalComment journalComment = journalCommentService.getById(newEvent.getCommentId()); @@ -126,8 +147,8 @@ public void handleCommentNewEvent(CommentNewEvent newEvent) { Journal journal = journalService.getById(journalComment.getPostId()); StrBuilder url = new StrBuilder(optionService.getBlogBaseUrl()) - .append("/") - .append(optionService.getJournalsPrefix()); + .append("/") + .append(optionService.getJournalsPrefix()); data.put("pageFullPath", url.toString()); data.put("pageTitle", journal.getCreateTime()); data.put("author", journalComment.getAuthor()); @@ -153,7 +174,8 @@ public void handleCommentNewEvent(CommentNewEvent newEvent) { @Async @EventListener public void handleCommentReplyEvent(CommentReplyEvent replyEvent) { - Boolean replyCommentNotice = optionService.getByPropertyOrDefault(CommentProperties.REPLY_NOTICE, Boolean.class, false); + Boolean replyCommentNotice = optionService + .getByPropertyOrDefault(CommentProperties.REPLY_NOTICE, Boolean.class, false); if (!replyCommentNotice) { // Skip mailing @@ -178,7 +200,8 @@ public void handleCommentReplyEvent(CommentReplyEvent replyEvent) { PostComment baseComment = postCommentService.getById(postComment.getParentId()); - if (StringUtils.isEmpty(baseComment.getEmail()) && !Validator.isEmail(baseComment.getEmail())) { + if (StringUtils.isEmpty(baseComment.getEmail()) + && !Validator.isEmail(baseComment.getEmail())) { return; } @@ -188,9 +211,11 @@ public void handleCommentReplyEvent(CommentReplyEvent replyEvent) { baseAuthorEmail = baseComment.getEmail(); - BasePostMinimalDTO post = postService.convertToMinimal(postService.getById(postComment.getPostId())); + BasePostMinimalDTO post = + postService.convertToMinimal(postService.getById(postComment.getPostId())); - data.put("pageFullPath", enabledAbsolutePath ? post.getFullPath() : optionService.getBlogBaseUrl() + post.getFullPath()); + data.put("pageFullPath", enabledAbsolutePath ? post.getFullPath() : + optionService.getBlogBaseUrl() + post.getFullPath()); data.put("pageTitle", post.getTitle()); data.put("baseAuthor", baseComment.getAuthor()); data.put("baseContent", baseComment.getContent()); @@ -198,17 +223,18 @@ public void handleCommentReplyEvent(CommentReplyEvent replyEvent) { data.put("replyContent", postComment.getContent()); subject.append("您在【") - .append(blogTitle) - .append("】评论的文章《") - .append(post.getTitle()) - .append("》有了新的评论。"); + .append(blogTitle) + .append("】评论的文章《") + .append(post.getTitle()) + .append("》有了新的评论。"); } else if (replyEvent.getSource() instanceof SheetCommentService) { SheetComment sheetComment = sheetCommentService.getById(replyEvent.getCommentId()); SheetComment baseComment = sheetCommentService.getById(sheetComment.getParentId()); - if (StringUtils.isEmpty(baseComment.getEmail()) && !Validator.isEmail(baseComment.getEmail())) { + if (StringUtils.isEmpty(baseComment.getEmail()) + && !Validator.isEmail(baseComment.getEmail())) { return; } @@ -218,9 +244,11 @@ public void handleCommentReplyEvent(CommentReplyEvent replyEvent) { baseAuthorEmail = baseComment.getEmail(); - BasePostMinimalDTO sheet = sheetService.convertToMinimal(sheetService.getById(sheetComment.getPostId())); + BasePostMinimalDTO sheet = + sheetService.convertToMinimal(sheetService.getById(sheetComment.getPostId())); - data.put("pageFullPath", enabledAbsolutePath ? sheet.getFullPath() : optionService.getBlogBaseUrl() + sheet.getFullPath()); + data.put("pageFullPath", enabledAbsolutePath ? sheet.getFullPath() : + optionService.getBlogBaseUrl() + sheet.getFullPath()); data.put("pageTitle", sheet.getTitle()); data.put("baseAuthor", baseComment.getAuthor()); data.put("baseContent", baseComment.getContent()); @@ -228,16 +256,19 @@ public void handleCommentReplyEvent(CommentReplyEvent replyEvent) { data.put("replyContent", sheetComment.getContent()); subject.append("您在【") - .append(blogTitle) - .append("】评论的页面《") - .append(sheet.getTitle()) - .append("》有了新的评论。"); + .append(blogTitle) + .append("】评论的页面《") + .append(sheet.getTitle()) + .append("》有了新的评论。"); } else if (replyEvent.getSource() instanceof JournalCommentService) { - JournalComment journalComment = journalCommentService.getById(replyEvent.getCommentId()); + JournalComment journalComment = + journalCommentService.getById(replyEvent.getCommentId()); - JournalComment baseComment = journalCommentService.getById(journalComment.getParentId()); + JournalComment baseComment = + journalCommentService.getById(journalComment.getParentId()); - if (StringUtils.isEmpty(baseComment.getEmail()) && !Validator.isEmail(baseComment.getEmail())) { + if (StringUtils.isEmpty(baseComment.getEmail()) + && !Validator.isEmail(baseComment.getEmail())) { return; } @@ -250,8 +281,8 @@ public void handleCommentReplyEvent(CommentReplyEvent replyEvent) { Journal journal = journalService.getById(journalComment.getPostId()); StrBuilder url = new StrBuilder(optionService.getBlogBaseUrl()) - .append("/") - .append(optionService.getJournalsPrefix()); + .append("/") + .append(optionService.getJournalsPrefix()); data.put("pageFullPath", url); data.put("pageTitle", journal.getContent()); data.put("baseAuthor", baseComment.getAuthor()); @@ -260,9 +291,9 @@ public void handleCommentReplyEvent(CommentReplyEvent replyEvent) { data.put("replyContent", journalComment.getContent()); subject.append("您在【") - .append(blogTitle) - .append("】评论的日志") - .append("有了新的评论。"); + .append(blogTitle) + .append("】评论的日志") + .append("有了新的评论。"); } String template = "common/mail_template/mail_reply.ftl"; diff --git a/src/main/java/run/halo/app/listener/freemarker/FreemarkerConfigAwareListener.java b/src/main/java/run/halo/app/listener/freemarker/FreemarkerConfigAwareListener.java index 0964f2edca..c8d12f1c93 100644 --- a/src/main/java/run/halo/app/listener/freemarker/FreemarkerConfigAwareListener.java +++ b/src/main/java/run/halo/app/listener/freemarker/FreemarkerConfigAwareListener.java @@ -42,10 +42,10 @@ public class FreemarkerConfigAwareListener { private final UserService userService; public FreemarkerConfigAwareListener(OptionService optionService, - Configuration configuration, - ThemeService themeService, - ThemeSettingService themeSettingService, - UserService userService) { + Configuration configuration, + ThemeService themeService, + ThemeSettingService themeSettingService, + UserService userService) { this.optionService = optionService; this.configuration = configuration; this.themeService = themeService; @@ -55,7 +55,8 @@ public FreemarkerConfigAwareListener(OptionService optionService, @EventListener @Order(Ordered.HIGHEST_PRECEDENCE + 1) - public void onApplicationStartedEvent(ApplicationStartedEvent applicationStartedEvent) throws TemplateModelException { + public void onApplicationStartedEvent(ApplicationStartedEvent applicationStartedEvent) + throws TemplateModelException { log.debug("Received application started event"); loadThemeConfig(); @@ -64,7 +65,8 @@ public void onApplicationStartedEvent(ApplicationStartedEvent applicationStarted } @EventListener - public void onThemeActivatedEvent(ThemeActivatedEvent themeActivatedEvent) throws TemplateModelException { + public void onThemeActivatedEvent(ThemeActivatedEvent themeActivatedEvent) + throws TemplateModelException { log.debug("Received theme activated event"); loadThemeConfig(); @@ -107,12 +109,19 @@ private void loadOptionsConfig() throws TemplateModelException { configuration.setSharedVariable("context", context); configuration.setSharedVariable("version", HaloConst.HALO_VERSION); - configuration.setSharedVariable("globalAbsolutePathEnabled", optionService.isEnabledAbsolutePath()); + configuration + .setSharedVariable("globalAbsolutePathEnabled", optionService.isEnabledAbsolutePath()); configuration.setSharedVariable("blog_title", optionService.getBlogTitle()); configuration.setSharedVariable("blog_url", blogBaseUrl); - configuration.setSharedVariable("blog_logo", optionService.getByPropertyOrDefault(BlogProperties.BLOG_LOGO, String.class, BlogProperties.BLOG_LOGO.defaultValue())); - configuration.setSharedVariable("seo_keywords", optionService.getByPropertyOrDefault(SeoProperties.KEYWORDS, String.class, SeoProperties.KEYWORDS.defaultValue())); - configuration.setSharedVariable("seo_description", optionService.getByPropertyOrDefault(SeoProperties.DESCRIPTION, String.class, SeoProperties.DESCRIPTION.defaultValue())); + configuration.setSharedVariable("blog_logo", optionService + .getByPropertyOrDefault(BlogProperties.BLOG_LOGO, String.class, + BlogProperties.BLOG_LOGO.defaultValue())); + configuration.setSharedVariable("seo_keywords", optionService + .getByPropertyOrDefault(SeoProperties.KEYWORDS, String.class, + SeoProperties.KEYWORDS.defaultValue())); + configuration.setSharedVariable("seo_description", optionService + .getByPropertyOrDefault(SeoProperties.DESCRIPTION, String.class, + SeoProperties.DESCRIPTION.defaultValue())); configuration.setSharedVariable("rss_url", blogBaseUrl + "/rss.xml"); configuration.setSharedVariable("atom_url", blogBaseUrl + "/atom.xml"); @@ -120,9 +129,12 @@ private void loadOptionsConfig() throws TemplateModelException { configuration.setSharedVariable("sitemap_html_url", blogBaseUrl + "/sitemap.html"); configuration.setSharedVariable("links_url", context + optionService.getLinksPrefix()); configuration.setSharedVariable("photos_url", context + optionService.getPhotosPrefix()); - configuration.setSharedVariable("journals_url", context + optionService.getJournalsPrefix()); - configuration.setSharedVariable("archives_url", context + optionService.getArchivesPrefix()); - configuration.setSharedVariable("categories_url", context + optionService.getCategoriesPrefix()); + configuration + .setSharedVariable("journals_url", context + optionService.getJournalsPrefix()); + configuration + .setSharedVariable("archives_url", context + optionService.getArchivesPrefix()); + configuration + .setSharedVariable("categories_url", context + optionService.getCategoriesPrefix()); configuration.setSharedVariable("tags_url", context + optionService.getTagsPrefix()); log.debug("Loaded options"); @@ -131,7 +143,9 @@ private void loadOptionsConfig() throws TemplateModelException { private void loadThemeConfig() { // Get current activated theme. themeService.fetchActivatedTheme().ifPresent(activatedTheme -> { - String themeBasePath = (optionService.isEnabledAbsolutePath() ? optionService.getBlogBaseUrl() : "") + "/themes/" + activatedTheme.getFolderName(); + String themeBasePath = + (optionService.isEnabledAbsolutePath() ? optionService.getBlogBaseUrl() : "") + + "/themes/" + activatedTheme.getFolderName(); try { configuration.setSharedVariable("theme", activatedTheme); @@ -140,7 +154,8 @@ private void loadThemeConfig() { configuration.setSharedVariable("theme_base", themeBasePath); - configuration.setSharedVariable("settings", themeSettingService.listAsMapBy(themeService.getActivatedThemeId())); + configuration.setSharedVariable("settings", + themeSettingService.listAsMapBy(themeService.getActivatedThemeId())); log.debug("Loaded theme and settings"); } catch (TemplateModelException e) { log.error("Failed to set shared variable!", e); diff --git a/src/main/java/run/halo/app/listener/post/AbstractVisitEventListener.java b/src/main/java/run/halo/app/listener/post/AbstractVisitEventListener.java index 0d1fbf6a48..258b8fa023 100644 --- a/src/main/java/run/halo/app/listener/post/AbstractVisitEventListener.java +++ b/src/main/java/run/halo/app/listener/post/AbstractVisitEventListener.java @@ -1,14 +1,17 @@ package run.halo.app.listener.post; +import java.util.Map; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.LinkedBlockingQueue; import lombok.NonNull; import lombok.extern.slf4j.Slf4j; import org.springframework.util.Assert; import run.halo.app.event.post.AbstractVisitEvent; import run.halo.app.service.base.BasePostService; -import java.util.Map; -import java.util.concurrent.*; - /** * Abstract visit event listener. * @@ -47,7 +50,7 @@ protected AbstractVisitEventListener(BasePostService basePostService) { * Handle visit event. * * @param event visit event must not be null - * @throws InterruptedException + * @throws InterruptedException interrupted exception */ protected void handleVisitEvent(@NonNull AbstractVisitEvent event) throws InterruptedException { Assert.notNull(event, "Visit event must not be null"); @@ -58,7 +61,8 @@ protected void handleVisitEvent(@NonNull AbstractVisitEvent event) throws Interr log.debug("Received a visit event, post id: [{}]", id); // Get post visit queue - BlockingQueue postVisitQueue = visitQueueMap.computeIfAbsent(id, this::createEmptyQueue); + BlockingQueue postVisitQueue = + visitQueueMap.computeIfAbsent(id, this::createEmptyQueue); visitTaskMap.computeIfAbsent(id, this::createPostVisitTask); @@ -108,7 +112,9 @@ public void run() { log.debug("Increased visits for post id: [{}]", postId); } catch (InterruptedException e) { - log.debug("Post visit task: " + Thread.currentThread().getName() + " was interrupted", e); + log.debug( + "Post visit task: " + Thread.currentThread().getName() + " was interrupted", + e); // Ignore this exception } } diff --git a/src/main/java/run/halo/app/mail/AbstractMailService.java b/src/main/java/run/halo/app/mail/AbstractMailService.java index e4a88f0039..8431c218b2 100644 --- a/src/main/java/run/halo/app/mail/AbstractMailService.java +++ b/src/main/java/run/halo/app/mail/AbstractMailService.java @@ -1,5 +1,12 @@ package run.halo.app.mail; +import java.io.UnsupportedEncodingException; +import java.util.Arrays; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import javax.mail.MessagingException; +import javax.mail.internet.InternetAddress; +import javax.mail.internet.MimeMessage; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.lang.NonNull; @@ -12,14 +19,6 @@ import run.halo.app.model.properties.EmailProperties; import run.halo.app.service.OptionService; -import javax.mail.MessagingException; -import javax.mail.internet.InternetAddress; -import javax.mail.internet.MimeMessage; -import java.io.UnsupportedEncodingException; -import java.util.Arrays; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - /** * Abstract mail service. * @@ -80,11 +79,14 @@ protected void sendMailTemplate(@Nullable Callback callback) { } // check if mail is enable - Boolean emailEnabled = optionService.getByPropertyOrDefault(EmailProperties.ENABLED, Boolean.class); + Boolean emailEnabled = + optionService.getByPropertyOrDefault(EmailProperties.ENABLED, Boolean.class); if (!emailEnabled) { // If disabled - log.info("Email has been disabled by yourself, you can re-enable it through email settings on admin page."); + log.info( + "Email has been disabled by yourself, you can re-enable it through email settings" + + " on admin page."); return; } @@ -107,9 +109,9 @@ protected void sendMailTemplate(@Nullable Callback callback) { mailSender.send(mimeMessage); log.info("Sent an email to [{}] successfully, subject: [{}], sent date: [{}]", - Arrays.toString(mimeMessage.getAllRecipients()), - mimeMessage.getSubject(), - mimeMessage.getSentDate()); + Arrays.toString(mimeMessage.getAllRecipients()), + mimeMessage.getSubject(), + mimeMessage.getSentDate()); } catch (Exception e) { throw new EmailException("邮件发送失败,请检查 SMTP 服务配置是否正确", e); } @@ -118,7 +120,7 @@ protected void sendMailTemplate(@Nullable Callback callback) { /** * Send mail template if executor service is enable. * - * @param callback callback message handler + * @param callback callback message handler * @param tryToAsync if the send procedure should try to asynchronous */ protected void sendMailTemplate(boolean tryToAsync, @Nullable Callback callback) { @@ -156,12 +158,14 @@ private synchronized JavaMailSender getMailSender() { * @return from-name internet address * @throws UnsupportedEncodingException throws when you give a wrong character encoding */ - private synchronized InternetAddress getFromAddress(@NonNull JavaMailSender javaMailSender) throws UnsupportedEncodingException { + private synchronized InternetAddress getFromAddress(@NonNull JavaMailSender javaMailSender) + throws UnsupportedEncodingException { Assert.notNull(javaMailSender, "Java mail sender must not be null"); if (StringUtils.isBlank(this.cachedFromName)) { // set personal name - this.cachedFromName = optionService.getByPropertyOfNonNull(EmailProperties.FROM_NAME).toString(); + this.cachedFromName = + optionService.getByPropertyOfNonNull(EmailProperties.FROM_NAME).toString(); } if (javaMailSender instanceof JavaMailSenderImpl) { @@ -170,10 +174,12 @@ private synchronized InternetAddress getFromAddress(@NonNull JavaMailSender java String username = mailSender.getUsername(); // build internet address - return new InternetAddress(username, this.cachedFromName, mailSender.getDefaultEncoding()); + return new InternetAddress(username, this.cachedFromName, + mailSender.getDefaultEncoding()); } - throw new UnsupportedOperationException("Unsupported java mail sender: " + javaMailSender.getClass().getName()); + throw new UnsupportedOperationException( + "Unsupported java mail sender: " + javaMailSender.getClass().getName()); } /** @@ -188,11 +194,16 @@ private synchronized MailProperties getMailProperties() { MailProperties mailProperties = new MailProperties(log.isDebugEnabled()); // set properties - mailProperties.setHost(optionService.getByPropertyOrDefault(EmailProperties.HOST, String.class)); - mailProperties.setPort(optionService.getByPropertyOrDefault(EmailProperties.SSL_PORT, Integer.class)); - mailProperties.setUsername(optionService.getByPropertyOrDefault(EmailProperties.USERNAME, String.class)); - mailProperties.setPassword(optionService.getByPropertyOrDefault(EmailProperties.PASSWORD, String.class)); - mailProperties.setProtocol(optionService.getByPropertyOrDefault(EmailProperties.PROTOCOL, String.class)); + mailProperties + .setHost(optionService.getByPropertyOrDefault(EmailProperties.HOST, String.class)); + mailProperties.setPort( + optionService.getByPropertyOrDefault(EmailProperties.SSL_PORT, Integer.class)); + mailProperties.setUsername( + optionService.getByPropertyOrDefault(EmailProperties.USERNAME, String.class)); + mailProperties.setPassword( + optionService.getByPropertyOrDefault(EmailProperties.PASSWORD, String.class)); + mailProperties.setProtocol( + optionService.getByPropertyOrDefault(EmailProperties.PROTOCOL, String.class)); this.cachedMailProperties = mailProperties; } diff --git a/src/main/java/run/halo/app/mail/MailProperties.java b/src/main/java/run/halo/app/mail/MailProperties.java index 9b869d446c..b8bf2e0e9e 100644 --- a/src/main/java/run/halo/app/mail/MailProperties.java +++ b/src/main/java/run/halo/app/mail/MailProperties.java @@ -1,10 +1,9 @@ package run.halo.app.mail; -import org.apache.commons.lang3.StringUtils; - import java.util.HashMap; import java.util.Map; +import org.apache.commons.lang3.StringUtils; /** * Mail properties. diff --git a/src/main/java/run/halo/app/mail/MailSenderFactory.java b/src/main/java/run/halo/app/mail/MailSenderFactory.java index d98514f6e9..57a7153a75 100644 --- a/src/main/java/run/halo/app/mail/MailSenderFactory.java +++ b/src/main/java/run/halo/app/mail/MailSenderFactory.java @@ -1,5 +1,6 @@ package run.halo.app.mail; +import java.util.Properties; import org.springframework.boot.autoconfigure.mail.MailProperties; import org.springframework.lang.NonNull; import org.springframework.mail.javamail.JavaMailSender; @@ -7,8 +8,6 @@ import org.springframework.util.Assert; import org.springframework.util.CollectionUtils; -import java.util.Properties; - /** * Java mail sender factory. * @@ -34,7 +33,8 @@ public JavaMailSender getMailSender(@NonNull MailProperties mailProperties) { return mailSender; } - private void setProperties(@NonNull JavaMailSenderImpl mailSender, @NonNull MailProperties mailProperties) { + private void setProperties(@NonNull JavaMailSenderImpl mailSender, + @NonNull MailProperties mailProperties) { mailSender.setHost(mailProperties.getHost()); mailSender.setPort(mailProperties.getPort()); mailSender.setUsername(mailProperties.getUsername()); diff --git a/src/main/java/run/halo/app/mail/MailService.java b/src/main/java/run/halo/app/mail/MailService.java index 8ce7d78c64..070b3c8b04 100644 --- a/src/main/java/run/halo/app/mail/MailService.java +++ b/src/main/java/run/halo/app/mail/MailService.java @@ -13,7 +13,7 @@ public interface MailService { /** * Send a simple email * - * @param to recipient + * @param to recipient * @param subject subject * @param content content */ @@ -22,23 +22,25 @@ public interface MailService { /** * Send a email with html * - * @param to recipient - * @param subject subject - * @param content content + * @param to recipient + * @param subject subject + * @param content content * @param templateName template name */ - void sendTemplateMail(String to, String subject, Map content, String templateName); + void sendTemplateMail(String to, String subject, Map content, + String templateName); /** * Send mail with attachments * - * @param to recipient - * @param subject subject - * @param content content - * @param templateName template name + * @param to recipient + * @param subject subject + * @param content content + * @param templateName template name * @param attachFilePath attachment full path name */ - void sendAttachMail(String to, String subject, Map content, String templateName, String attachFilePath); + void sendAttachMail(String to, String subject, Map content, String templateName, + String attachFilePath); /** * Test email server connection. diff --git a/src/main/java/run/halo/app/mail/MailServiceImpl.java b/src/main/java/run/halo/app/mail/MailServiceImpl.java index 05e4c1aebf..6ffd238a43 100644 --- a/src/main/java/run/halo/app/mail/MailServiceImpl.java +++ b/src/main/java/run/halo/app/mail/MailServiceImpl.java @@ -1,6 +1,9 @@ package run.halo.app.mail; import freemarker.template.Template; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Map; import lombok.extern.slf4j.Slf4j; import org.springframework.context.ApplicationListener; import org.springframework.stereotype.Service; @@ -9,10 +12,6 @@ import run.halo.app.event.options.OptionUpdatedEvent; import run.halo.app.service.OptionService; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.Map; - /** * Mail service implementation. * @@ -22,12 +21,13 @@ */ @Slf4j @Service -public class MailServiceImpl extends AbstractMailService implements ApplicationListener { +public class MailServiceImpl extends AbstractMailService + implements ApplicationListener { private final FreeMarkerConfigurer freeMarker; public MailServiceImpl(FreeMarkerConfigurer freeMarker, - OptionService optionService) { + OptionService optionService) { super(optionService); this.freeMarker = freeMarker; } @@ -42,11 +42,13 @@ public void sendTextMail(String to, String subject, String content) { } @Override - public void sendTemplateMail(String to, String subject, Map content, String templateName) { + public void sendTemplateMail(String to, String subject, Map content, + String templateName) { sendMailTemplate(true, messageHelper -> { // build message content with freemarker Template template = freeMarker.getConfiguration().getTemplate(templateName); - String contentResult = FreeMarkerTemplateUtils.processTemplateIntoString(template, content); + String contentResult = + FreeMarkerTemplateUtils.processTemplateIntoString(template, content); messageHelper.setSubject(subject); messageHelper.setTo(to); @@ -55,12 +57,14 @@ public void sendTemplateMail(String to, String subject, Map cont } @Override - public void sendAttachMail(String to, String subject, Map content, String templateName, String attachFilePath) { + public void sendAttachMail(String to, String subject, Map content, + String templateName, String attachFilePath) { sendMailTemplate(true, messageHelper -> { messageHelper.setSubject(subject); messageHelper.setTo(to); Path attachmentPath = Paths.get(attachFilePath); - messageHelper.addAttachment(attachmentPath.getFileName().toString(), attachmentPath.toFile()); + messageHelper + .addAttachment(attachmentPath.getFileName().toString(), attachmentPath.toFile()); }); } diff --git a/src/main/java/run/halo/app/model/dto/AttachmentDTO.java b/src/main/java/run/halo/app/model/dto/AttachmentDTO.java index 74549eada7..d70adb2153 100644 --- a/src/main/java/run/halo/app/model/dto/AttachmentDTO.java +++ b/src/main/java/run/halo/app/model/dto/AttachmentDTO.java @@ -1,12 +1,11 @@ package run.halo.app.model.dto; +import java.util.Date; import lombok.Data; import run.halo.app.model.dto.base.OutputConverter; import run.halo.app.model.entity.Attachment; import run.halo.app.model.enums.AttachmentType; -import java.util.Date; - /** * Attachment output dto. * diff --git a/src/main/java/run/halo/app/model/dto/BaseCommentDTO.java b/src/main/java/run/halo/app/model/dto/BaseCommentDTO.java index 2f7bfa786a..eef45e0a63 100644 --- a/src/main/java/run/halo/app/model/dto/BaseCommentDTO.java +++ b/src/main/java/run/halo/app/model/dto/BaseCommentDTO.java @@ -1,5 +1,6 @@ package run.halo.app.model.dto; +import java.util.Date; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.ToString; @@ -7,8 +8,6 @@ import run.halo.app.model.entity.BaseComment; import run.halo.app.model.enums.CommentStatus; -import java.util.Date; - /** * Base comment output dto. * diff --git a/src/main/java/run/halo/app/model/dto/BaseMetaDTO.java b/src/main/java/run/halo/app/model/dto/BaseMetaDTO.java index b1322fd57d..61b180ed4d 100644 --- a/src/main/java/run/halo/app/model/dto/BaseMetaDTO.java +++ b/src/main/java/run/halo/app/model/dto/BaseMetaDTO.java @@ -1,13 +1,12 @@ package run.halo.app.model.dto; +import java.util.Date; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.ToString; import run.halo.app.model.dto.base.OutputConverter; import run.halo.app.model.entity.BaseMeta; -import java.util.Date; - /** * Base meta Dto. * diff --git a/src/main/java/run/halo/app/model/dto/CategoryDTO.java b/src/main/java/run/halo/app/model/dto/CategoryDTO.java index 697035b165..a77d794895 100644 --- a/src/main/java/run/halo/app/model/dto/CategoryDTO.java +++ b/src/main/java/run/halo/app/model/dto/CategoryDTO.java @@ -1,13 +1,12 @@ package run.halo.app.model.dto; +import java.util.Date; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.ToString; import run.halo.app.model.dto.base.OutputConverter; import run.halo.app.model.entity.Category; -import java.util.Date; - /** * Category output dto. * diff --git a/src/main/java/run/halo/app/model/dto/JournalDTO.java b/src/main/java/run/halo/app/model/dto/JournalDTO.java index 996c855c76..eb6c68e205 100644 --- a/src/main/java/run/halo/app/model/dto/JournalDTO.java +++ b/src/main/java/run/halo/app/model/dto/JournalDTO.java @@ -1,12 +1,11 @@ package run.halo.app.model.dto; +import java.util.Date; import lombok.Data; import run.halo.app.model.dto.base.OutputConverter; import run.halo.app.model.entity.Journal; import run.halo.app.model.enums.JournalType; -import java.util.Date; - /** * Journal dto. * diff --git a/src/main/java/run/halo/app/model/dto/LogDTO.java b/src/main/java/run/halo/app/model/dto/LogDTO.java index 54841fbd14..7068bac4eb 100644 --- a/src/main/java/run/halo/app/model/dto/LogDTO.java +++ b/src/main/java/run/halo/app/model/dto/LogDTO.java @@ -1,5 +1,6 @@ package run.halo.app.model.dto; +import java.util.Date; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.ToString; @@ -7,8 +8,6 @@ import run.halo.app.model.entity.Log; import run.halo.app.model.enums.LogType; -import java.util.Date; - /** * @author johnniang * @date 3/19/19 diff --git a/src/main/java/run/halo/app/model/dto/OptionSimpleDTO.java b/src/main/java/run/halo/app/model/dto/OptionSimpleDTO.java index d28e5b3eae..50adcefe1b 100644 --- a/src/main/java/run/halo/app/model/dto/OptionSimpleDTO.java +++ b/src/main/java/run/halo/app/model/dto/OptionSimpleDTO.java @@ -1,11 +1,10 @@ package run.halo.app.model.dto; +import java.util.Date; import lombok.Data; import lombok.EqualsAndHashCode; import run.halo.app.model.enums.OptionType; -import java.util.Date; - /** * Option list output dto. * diff --git a/src/main/java/run/halo/app/model/dto/PhotoDTO.java b/src/main/java/run/halo/app/model/dto/PhotoDTO.java index 3d6be15ad6..09b2397464 100644 --- a/src/main/java/run/halo/app/model/dto/PhotoDTO.java +++ b/src/main/java/run/halo/app/model/dto/PhotoDTO.java @@ -1,11 +1,10 @@ package run.halo.app.model.dto; +import java.util.Date; import lombok.Data; import run.halo.app.model.dto.base.OutputConverter; import run.halo.app.model.entity.Photo; -import java.util.Date; - /** * @author ryanwang * @date 2019-03-21 diff --git a/src/main/java/run/halo/app/model/dto/StatisticWithUserDTO.java b/src/main/java/run/halo/app/model/dto/StatisticWithUserDTO.java index c7014aab7e..078231fbe3 100644 --- a/src/main/java/run/halo/app/model/dto/StatisticWithUserDTO.java +++ b/src/main/java/run/halo/app/model/dto/StatisticWithUserDTO.java @@ -12,7 +12,8 @@ */ @Data @EqualsAndHashCode(callSuper = true) -public class StatisticWithUserDTO extends StatisticDTO implements OutputConverter { +public class StatisticWithUserDTO extends StatisticDTO + implements OutputConverter { private UserDTO user; } diff --git a/src/main/java/run/halo/app/model/dto/TagDTO.java b/src/main/java/run/halo/app/model/dto/TagDTO.java index cb197980ab..a58a2103fb 100644 --- a/src/main/java/run/halo/app/model/dto/TagDTO.java +++ b/src/main/java/run/halo/app/model/dto/TagDTO.java @@ -1,11 +1,10 @@ package run.halo.app.model.dto; +import java.util.Date; import lombok.Data; import run.halo.app.model.dto.base.OutputConverter; import run.halo.app.model.entity.Tag; -import java.util.Date; - /** * Tag output dto. * diff --git a/src/main/java/run/halo/app/model/dto/UserDTO.java b/src/main/java/run/halo/app/model/dto/UserDTO.java index 6606d03d79..7b1c1d2504 100644 --- a/src/main/java/run/halo/app/model/dto/UserDTO.java +++ b/src/main/java/run/halo/app/model/dto/UserDTO.java @@ -1,5 +1,6 @@ package run.halo.app.model.dto; +import java.util.Date; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.ToString; @@ -7,8 +8,6 @@ import run.halo.app.model.entity.User; import run.halo.app.model.enums.MFAType; -import java.util.Date; - /** * User output dto. * diff --git a/src/main/java/run/halo/app/model/dto/base/InputConverter.java b/src/main/java/run/halo/app/model/dto/base/InputConverter.java index d013e57624..5cf7286581 100644 --- a/src/main/java/run/halo/app/model/dto/base/InputConverter.java +++ b/src/main/java/run/halo/app/model/dto/base/InputConverter.java @@ -1,18 +1,17 @@ package run.halo.app.model.dto.base; +import java.lang.reflect.ParameterizedType; +import java.util.Objects; import org.springframework.lang.Nullable; import run.halo.app.utils.BeanUtils; import run.halo.app.utils.ReflectionUtils; -import java.lang.reflect.ParameterizedType; -import java.util.Objects; - /** * Converter interface for input DTO. * * @author johnniang */ -public interface InputConverter { +public interface InputConverter { /** * Convert to domain.(shallow) @@ -20,14 +19,15 @@ public interface InputConverter { * @return new domain with same value(not null) */ @SuppressWarnings("unchecked") - default DOMAIN convertTo() { + default D convertTo() { // Get parameterized type ParameterizedType currentType = parameterizedType(); // Assert not equal - Objects.requireNonNull(currentType, "Cannot fetch actual type because parameterized type is null"); + Objects.requireNonNull(currentType, + "Cannot fetch actual type because parameterized type is null"); - Class domainClass = (Class) currentType.getActualTypeArguments()[0]; + Class domainClass = (Class) currentType.getActualTypeArguments()[0]; return BeanUtils.transformFrom(this, domainClass); } @@ -37,7 +37,7 @@ default DOMAIN convertTo() { * * @param domain updated domain */ - default void update(DOMAIN domain) { + default void update(D domain) { BeanUtils.updateProperties(this, domain); } diff --git a/src/main/java/run/halo/app/model/dto/base/OutputConverter.java b/src/main/java/run/halo/app/model/dto/base/OutputConverter.java index 72038fb793..d4622fd853 100644 --- a/src/main/java/run/halo/app/model/dto/base/OutputConverter.java +++ b/src/main/java/run/halo/app/model/dto/base/OutputConverter.java @@ -1,19 +1,19 @@ package run.halo.app.model.dto.base; -import org.springframework.lang.NonNull; - import static run.halo.app.utils.BeanUtils.updateProperties; +import org.springframework.lang.NonNull; + /** * Converter interface for output DTO. * * The implementation type must be equal to DTO type * - * @param the implementation class type - * @param domain type + * @param the implementation class type + * @param domain type * @author johnniang */ -public interface OutputConverter, DOMAIN> { +public interface OutputConverter, D> { /** * Convert from domain.(shallow) @@ -23,7 +23,7 @@ public interface OutputConverter, DOMAI */ @SuppressWarnings("unchecked") @NonNull - default T convertFrom(@NonNull DOMAIN domain) { + default T convertFrom(@NonNull D domain) { updateProperties(domain, this); diff --git a/src/main/java/run/halo/app/model/dto/post/BasePostMinimalDTO.java b/src/main/java/run/halo/app/model/dto/post/BasePostMinimalDTO.java index 4491753990..b09897fd1d 100644 --- a/src/main/java/run/halo/app/model/dto/post/BasePostMinimalDTO.java +++ b/src/main/java/run/halo/app/model/dto/post/BasePostMinimalDTO.java @@ -1,5 +1,6 @@ package run.halo.app.model.dto.post; +import java.util.Date; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.ToString; @@ -8,8 +9,6 @@ import run.halo.app.model.enums.PostEditorType; import run.halo.app.model.enums.PostStatus; -import java.util.Date; - /** * Base post minimal output dto. * diff --git a/src/main/java/run/halo/app/model/entity/Attachment.java b/src/main/java/run/halo/app/model/entity/Attachment.java index e3cd2d9068..47c6b1ec84 100644 --- a/src/main/java/run/halo/app/model/entity/Attachment.java +++ b/src/main/java/run/halo/app/model/entity/Attachment.java @@ -1,5 +1,12 @@ package run.halo.app.model.entity; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Index; +import javax.persistence.Table; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.ToString; @@ -7,8 +14,6 @@ import org.hibernate.annotations.GenericGenerator; import run.halo.app.model.enums.AttachmentType; -import javax.persistence.*; - /** * Attachment entity * @@ -18,15 +23,16 @@ @Data @Entity @Table(name = "attachments", indexes = { - @Index(name = "attachments_media_type", columnList = "media_type"), - @Index(name = "attachments_create_time", columnList = "create_time")}) + @Index(name = "attachments_media_type", columnList = "media_type"), + @Index(name = "attachments_create_time", columnList = "create_time")}) @ToString @EqualsAndHashCode(callSuper = true) public class Attachment extends BaseEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY, generator = "custom-id") - @GenericGenerator(name = "custom-id", strategy = "run.halo.app.model.entity.support.CustomIdGenerator") + @GenericGenerator(name = "custom-id", strategy = "run.halo.app.model.entity.support" + + ".CustomIdGenerator") private Integer id; /** diff --git a/src/main/java/run/halo/app/model/entity/BaseComment.java b/src/main/java/run/halo/app/model/entity/BaseComment.java index cc7cba4b8a..4c8bdd3e87 100644 --- a/src/main/java/run/halo/app/model/entity/BaseComment.java +++ b/src/main/java/run/halo/app/model/entity/BaseComment.java @@ -1,5 +1,14 @@ package run.halo.app.model.entity; +import javax.persistence.Column; +import javax.persistence.DiscriminatorColumn; +import javax.persistence.DiscriminatorType; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Index; +import javax.persistence.Table; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.ToString; @@ -8,8 +17,6 @@ import run.halo.app.model.enums.CommentStatus; import run.halo.app.utils.ServiceUtils; -import javax.persistence.*; - /** * Base comment entity. * @@ -20,17 +27,19 @@ @Data @Entity(name = "BaseComment") @Table(name = "comments", indexes = { - @Index(name = "comments_post_id", columnList = "post_id"), - @Index(name = "comments_type_status", columnList = "type, status"), - @Index(name = "comments_parent_id", columnList = "parent_id")}) -@DiscriminatorColumn(name = "type", discriminatorType = DiscriminatorType.INTEGER, columnDefinition = "int default 0") + @Index(name = "comments_post_id", columnList = "post_id"), + @Index(name = "comments_type_status", columnList = "type, status"), + @Index(name = "comments_parent_id", columnList = "parent_id")}) +@DiscriminatorColumn(name = "type", discriminatorType = DiscriminatorType.INTEGER, + columnDefinition = "int default 0") @ToString(callSuper = true) @EqualsAndHashCode(callSuper = true) public class BaseComment extends BaseEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY, generator = "custom-id") - @GenericGenerator(name = "custom-id", strategy = "run.halo.app.model.entity.support.CustomIdGenerator") + @GenericGenerator(name = "custom-id", strategy = "run.halo.app.model.entity.support" + + ".CustomIdGenerator") private Long id; /** diff --git a/src/main/java/run/halo/app/model/entity/BaseEntity.java b/src/main/java/run/halo/app/model/entity/BaseEntity.java index 4429f9d734..43370dd86e 100644 --- a/src/main/java/run/halo/app/model/entity/BaseEntity.java +++ b/src/main/java/run/halo/app/model/entity/BaseEntity.java @@ -1,13 +1,18 @@ package run.halo.app.model.entity; +import java.util.Date; +import javax.persistence.Column; +import javax.persistence.MappedSuperclass; +import javax.persistence.PrePersist; +import javax.persistence.PreRemove; +import javax.persistence.PreUpdate; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.ToString; import run.halo.app.utils.DateUtils; -import javax.persistence.*; -import java.util.Date; - /** * Base entity. * diff --git a/src/main/java/run/halo/app/model/entity/BaseMeta.java b/src/main/java/run/halo/app/model/entity/BaseMeta.java index 6a42a8d2bf..1149e8da6e 100644 --- a/src/main/java/run/halo/app/model/entity/BaseMeta.java +++ b/src/main/java/run/halo/app/model/entity/BaseMeta.java @@ -1,13 +1,19 @@ package run.halo.app.model.entity; +import javax.persistence.Column; +import javax.persistence.DiscriminatorColumn; +import javax.persistence.DiscriminatorType; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.ToString; import org.hibernate.annotations.GenericGenerator; -import javax.persistence.*; - /** * Base meta entity. * @@ -18,14 +24,16 @@ @Data @Entity(name = "BaseMeta") @Table(name = "metas") -@DiscriminatorColumn(name = "type", discriminatorType = DiscriminatorType.INTEGER, columnDefinition = "int default 0") +@DiscriminatorColumn(name = "type", discriminatorType = DiscriminatorType.INTEGER, + columnDefinition = "int default 0") @ToString(callSuper = true) @EqualsAndHashCode(callSuper = true) public class BaseMeta extends BaseEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY, generator = "custom-id") - @GenericGenerator(name = "custom-id", strategy = "run.halo.app.model.entity.support.CustomIdGenerator") + @GenericGenerator(name = "custom-id", strategy = "run.halo.app.model.entity.support" + + ".CustomIdGenerator") private Long id; /** diff --git a/src/main/java/run/halo/app/model/entity/BasePost.java b/src/main/java/run/halo/app/model/entity/BasePost.java index 8eb2705426..8fbac2cad3 100644 --- a/src/main/java/run/halo/app/model/entity/BasePost.java +++ b/src/main/java/run/halo/app/model/entity/BasePost.java @@ -1,5 +1,18 @@ package run.halo.app.model.entity; +import java.util.Date; +import javax.persistence.Column; +import javax.persistence.DiscriminatorColumn; +import javax.persistence.DiscriminatorType; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Index; +import javax.persistence.Lob; +import javax.persistence.Table; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.ToString; @@ -8,9 +21,6 @@ import run.halo.app.model.enums.PostEditorType; import run.halo.app.model.enums.PostStatus; -import javax.persistence.*; -import java.util.Date; - /** * Post base entity. * @@ -21,16 +31,18 @@ @Data @Entity(name = "BasePost") @Table(name = "posts", indexes = { - @Index(name = "posts_type_status", columnList = "type, status"), - @Index(name = "posts_create_time", columnList = "create_time")}) -@DiscriminatorColumn(name = "type", discriminatorType = DiscriminatorType.INTEGER, columnDefinition = "int default 0") + @Index(name = "posts_type_status", columnList = "type, status"), + @Index(name = "posts_create_time", columnList = "create_time")}) +@DiscriminatorColumn(name = "type", discriminatorType = DiscriminatorType.INTEGER, + columnDefinition = "int default 0") @ToString(callSuper = true) @EqualsAndHashCode(callSuper = true) public class BasePost extends BaseEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY, generator = "custom-id") - @GenericGenerator(name = "custom-id", strategy = "run.halo.app.model.entity.support.CustomIdGenerator") + @GenericGenerator(name = "custom-id", strategy = "run.halo.app.model.entity.support" + + ".CustomIdGenerator") private Integer id; /** diff --git a/src/main/java/run/halo/app/model/entity/Category.java b/src/main/java/run/halo/app/model/entity/Category.java index 9b644a50df..96b56367b8 100644 --- a/src/main/java/run/halo/app/model/entity/Category.java +++ b/src/main/java/run/halo/app/model/entity/Category.java @@ -1,13 +1,18 @@ package run.halo.app.model.entity; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Index; +import javax.persistence.Table; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.ToString; import org.hibernate.annotations.ColumnDefault; import org.hibernate.annotations.GenericGenerator; -import javax.persistence.*; - /** * Category entity. * @@ -18,15 +23,16 @@ @Data @Entity @Table(name = "categories", indexes = { - @Index(name = "categories_name", columnList = "name"), - @Index(name = "categories_parent_id", columnList = "parent_id")}) + @Index(name = "categories_name", columnList = "name"), + @Index(name = "categories_parent_id", columnList = "parent_id")}) @ToString @EqualsAndHashCode(callSuper = true) public class Category extends BaseEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY, generator = "custom-id") - @GenericGenerator(name = "custom-id", strategy = "run.halo.app.model.entity.support.CustomIdGenerator") + @GenericGenerator(name = "custom-id", + strategy = "run.halo.app.model.entity.support.CustomIdGenerator") private Integer id; /** diff --git a/src/main/java/run/halo/app/model/entity/CommentBlackList.java b/src/main/java/run/halo/app/model/entity/CommentBlackList.java index 0b56153b86..6ea83215a6 100644 --- a/src/main/java/run/halo/app/model/entity/CommentBlackList.java +++ b/src/main/java/run/halo/app/model/entity/CommentBlackList.java @@ -1,10 +1,20 @@ package run.halo.app.model.entity; -import lombok.*; -import org.hibernate.annotations.GenericGenerator; - -import javax.persistence.*; import java.util.Date; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.NoArgsConstructor; +import org.hibernate.annotations.GenericGenerator; /** * comment_black_list @@ -22,7 +32,8 @@ public class CommentBlackList extends BaseEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY, generator = "custom-id") - @GenericGenerator(name = "custom-id", strategy = "run.halo.app.model.entity.support.CustomIdGenerator") + @GenericGenerator(name = "custom-id", + strategy = "run.halo.app.model.entity.support.CustomIdGenerator") private Long id; @Column(name = "ip_address", length = 127, nullable = false) diff --git a/src/main/java/run/halo/app/model/entity/Journal.java b/src/main/java/run/halo/app/model/entity/Journal.java index 226c8f1686..2ad77fc15f 100644 --- a/src/main/java/run/halo/app/model/entity/Journal.java +++ b/src/main/java/run/halo/app/model/entity/Journal.java @@ -1,5 +1,12 @@ package run.halo.app.model.entity; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Lob; +import javax.persistence.Table; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.ToString; @@ -7,8 +14,6 @@ import org.hibernate.annotations.GenericGenerator; import run.halo.app.model.enums.JournalType; -import javax.persistence.*; - /** * Journal entity * @@ -25,7 +30,8 @@ public class Journal extends BaseEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY, generator = "custom-id") - @GenericGenerator(name = "custom-id", strategy = "run.halo.app.model.entity.support.CustomIdGenerator") + @GenericGenerator(name = "custom-id", + strategy = "run.halo.app.model.entity.support.CustomIdGenerator") private Integer id; @Column(name = "source_content", nullable = false) diff --git a/src/main/java/run/halo/app/model/entity/Link.java b/src/main/java/run/halo/app/model/entity/Link.java index c0206b80b9..f8dfcd751b 100644 --- a/src/main/java/run/halo/app/model/entity/Link.java +++ b/src/main/java/run/halo/app/model/entity/Link.java @@ -1,13 +1,18 @@ package run.halo.app.model.entity; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Index; +import javax.persistence.Table; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.ToString; import org.hibernate.annotations.ColumnDefault; import org.hibernate.annotations.GenericGenerator; -import javax.persistence.*; - /** * Link entity * @@ -23,7 +28,8 @@ public class Link extends BaseEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY, generator = "custom-id") - @GenericGenerator(name = "custom-id", strategy = "run.halo.app.model.entity.support.CustomIdGenerator") + @GenericGenerator(name = "custom-id", + strategy = "run.halo.app.model.entity.support.CustomIdGenerator") private Integer id; /** diff --git a/src/main/java/run/halo/app/model/entity/Log.java b/src/main/java/run/halo/app/model/entity/Log.java index 5513d9d238..d8b7f6cb44 100644 --- a/src/main/java/run/halo/app/model/entity/Log.java +++ b/src/main/java/run/halo/app/model/entity/Log.java @@ -1,14 +1,19 @@ package run.halo.app.model.entity; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Index; +import javax.persistence.Table; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.ToString; import org.hibernate.annotations.GenericGenerator; import run.halo.app.model.enums.LogType; -import javax.persistence.*; - /** * Log entity. * @@ -23,7 +28,8 @@ public class Log extends BaseEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY, generator = "custom-id") - @GenericGenerator(name = "custom-id", strategy = "run.halo.app.model.entity.support.CustomIdGenerator") + @GenericGenerator(name = "custom-id", + strategy = "run.halo.app.model.entity.support.CustomIdGenerator") private Long id; /** diff --git a/src/main/java/run/halo/app/model/entity/Menu.java b/src/main/java/run/halo/app/model/entity/Menu.java index 700fa6dc76..1a6fcaaabc 100644 --- a/src/main/java/run/halo/app/model/entity/Menu.java +++ b/src/main/java/run/halo/app/model/entity/Menu.java @@ -1,13 +1,18 @@ package run.halo.app.model.entity; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Index; +import javax.persistence.Table; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.ToString; import org.hibernate.annotations.ColumnDefault; import org.hibernate.annotations.GenericGenerator; -import javax.persistence.*; - /** * Menu entity * @@ -17,15 +22,16 @@ @Data @Entity @Table(name = "menus", indexes = { - @Index(name = "menus_parent_id", columnList = "parent_id"), - @Index(name = "menus_name", columnList = "name")}) + @Index(name = "menus_parent_id", columnList = "parent_id"), + @Index(name = "menus_name", columnList = "name")}) @ToString @EqualsAndHashCode(callSuper = true) public class Menu extends BaseEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY, generator = "custom-id") - @GenericGenerator(name = "custom-id", strategy = "run.halo.app.model.entity.support.CustomIdGenerator") + @GenericGenerator(name = "custom-id", + strategy = "run.halo.app.model.entity.support.CustomIdGenerator") private Integer id; /** diff --git a/src/main/java/run/halo/app/model/entity/Option.java b/src/main/java/run/halo/app/model/entity/Option.java index 63ae25eb84..e0209d943d 100644 --- a/src/main/java/run/halo/app/model/entity/Option.java +++ b/src/main/java/run/halo/app/model/entity/Option.java @@ -1,5 +1,12 @@ package run.halo.app.model.entity; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Lob; +import javax.persistence.Table; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; @@ -8,8 +15,6 @@ import org.hibernate.annotations.GenericGenerator; import run.halo.app.model.enums.OptionType; -import javax.persistence.*; - /** * Setting entity. * @@ -27,7 +32,8 @@ public class Option extends BaseEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY, generator = "custom-id") - @GenericGenerator(name = "custom-id", strategy = "run.halo.app.model.entity.support.CustomIdGenerator") + @GenericGenerator(name = "custom-id", + strategy = "run.halo.app.model.entity.support.CustomIdGenerator") private Integer id; /** diff --git a/src/main/java/run/halo/app/model/entity/Photo.java b/src/main/java/run/halo/app/model/entity/Photo.java index d2f10c888c..d127ba1432 100644 --- a/src/main/java/run/halo/app/model/entity/Photo.java +++ b/src/main/java/run/halo/app/model/entity/Photo.java @@ -1,13 +1,20 @@ package run.halo.app.model.entity; +import java.util.Date; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Index; +import javax.persistence.Table; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.ToString; import org.hibernate.annotations.GenericGenerator; -import javax.persistence.*; -import java.util.Date; - /** * Photo entity * @@ -17,15 +24,16 @@ @Data @Entity @Table(name = "photos", indexes = { - @Index(name = "photos_team", columnList = "team"), - @Index(name = "photos_create_time", columnList = "create_time")}) + @Index(name = "photos_team", columnList = "team"), + @Index(name = "photos_create_time", columnList = "create_time")}) @ToString @EqualsAndHashCode(callSuper = true) public class Photo extends BaseEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY, generator = "custom-id") - @GenericGenerator(name = "custom-id", strategy = "run.halo.app.model.entity.support.CustomIdGenerator") + @GenericGenerator(name = "custom-id", + strategy = "run.halo.app.model.entity.support.CustomIdGenerator") private Integer id; /** diff --git a/src/main/java/run/halo/app/model/entity/PostCategory.java b/src/main/java/run/halo/app/model/entity/PostCategory.java index 37ce6aac6f..dc58d79cce 100644 --- a/src/main/java/run/halo/app/model/entity/PostCategory.java +++ b/src/main/java/run/halo/app/model/entity/PostCategory.java @@ -1,14 +1,19 @@ package run.halo.app.model.entity; +import java.util.Objects; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Index; +import javax.persistence.Table; import lombok.Getter; import lombok.RequiredArgsConstructor; import lombok.Setter; import lombok.ToString; import org.hibernate.annotations.GenericGenerator; -import javax.persistence.*; -import java.util.Objects; - /** * Post category entity. * @@ -20,13 +25,14 @@ @RequiredArgsConstructor @Entity @Table(name = "post_categories", indexes = { - @Index(name = "post_categories_post_id", columnList = "post_id"), - @Index(name = "post_categories_category_id", columnList = "category_id")}) + @Index(name = "post_categories_post_id", columnList = "post_id"), + @Index(name = "post_categories_category_id", columnList = "category_id")}) public class PostCategory extends BaseEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY, generator = "custom-id") - @GenericGenerator(name = "custom-id", strategy = "run.halo.app.model.entity.support.CustomIdGenerator") + @GenericGenerator(name = "custom-id", + strategy = "run.halo.app.model.entity.support.CustomIdGenerator") private Integer id; /** @@ -50,8 +56,8 @@ public boolean equals(Object o) { return false; } PostCategory that = (PostCategory) o; - return categoryId.equals(that.categoryId) && - postId.equals(that.postId); + return categoryId.equals(that.categoryId) + && postId.equals(that.postId); } @Override diff --git a/src/main/java/run/halo/app/model/entity/PostMeta.java b/src/main/java/run/halo/app/model/entity/PostMeta.java index edd7bd0dfd..d0b28cb8cd 100644 --- a/src/main/java/run/halo/app/model/entity/PostMeta.java +++ b/src/main/java/run/halo/app/model/entity/PostMeta.java @@ -1,9 +1,8 @@ package run.halo.app.model.entity; -import lombok.EqualsAndHashCode; - import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; +import lombok.EqualsAndHashCode; /** * PostMeta entity. diff --git a/src/main/java/run/halo/app/model/entity/PostTag.java b/src/main/java/run/halo/app/model/entity/PostTag.java index 6efec49abe..c6bab0dc89 100644 --- a/src/main/java/run/halo/app/model/entity/PostTag.java +++ b/src/main/java/run/halo/app/model/entity/PostTag.java @@ -1,14 +1,19 @@ package run.halo.app.model.entity; +import java.util.Objects; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Index; +import javax.persistence.Table; import lombok.Getter; import lombok.RequiredArgsConstructor; import lombok.Setter; import lombok.ToString; import org.hibernate.annotations.GenericGenerator; -import javax.persistence.*; -import java.util.Objects; - /** * Post tag entity. * @@ -21,13 +26,14 @@ @RequiredArgsConstructor @Entity @Table(name = "post_tags", indexes = { - @Index(name = "post_tags_post_id", columnList = "post_id"), - @Index(name = "post_tags_tag_id", columnList = "tag_id")}) + @Index(name = "post_tags_post_id", columnList = "post_id"), + @Index(name = "post_tags_tag_id", columnList = "tag_id")}) public class PostTag extends BaseEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY, generator = "custom-id") - @GenericGenerator(name = "custom-id", strategy = "run.halo.app.model.entity.support.CustomIdGenerator") + @GenericGenerator(name = "custom-id", + strategy = "run.halo.app.model.entity.support.CustomIdGenerator") private Integer id; /** @@ -51,8 +57,8 @@ public boolean equals(Object o) { return false; } PostTag postTag = (PostTag) o; - return Objects.equals(postId, postTag.postId) && - Objects.equals(tagId, postTag.tagId); + return Objects.equals(postId, postTag.postId) + && Objects.equals(tagId, postTag.tagId); } @Override diff --git a/src/main/java/run/halo/app/model/entity/SheetMeta.java b/src/main/java/run/halo/app/model/entity/SheetMeta.java index fcbad2d694..c48600a85e 100644 --- a/src/main/java/run/halo/app/model/entity/SheetMeta.java +++ b/src/main/java/run/halo/app/model/entity/SheetMeta.java @@ -1,9 +1,8 @@ package run.halo.app.model.entity; -import lombok.EqualsAndHashCode; - import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; +import lombok.EqualsAndHashCode; /** * SheetMeta entity. diff --git a/src/main/java/run/halo/app/model/entity/Tag.java b/src/main/java/run/halo/app/model/entity/Tag.java index a63f9dcb3c..4dae125fd9 100644 --- a/src/main/java/run/halo/app/model/entity/Tag.java +++ b/src/main/java/run/halo/app/model/entity/Tag.java @@ -1,12 +1,17 @@ package run.halo.app.model.entity; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Index; +import javax.persistence.Table; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.ToString; import org.hibernate.annotations.GenericGenerator; -import javax.persistence.*; - /** * Tag entity * @@ -22,7 +27,8 @@ public class Tag extends BaseEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY, generator = "custom-id") - @GenericGenerator(name = "custom-id", strategy = "run.halo.app.model.entity.support.CustomIdGenerator") + @GenericGenerator(name = "custom-id", + strategy = "run.halo.app.model.entity.support.CustomIdGenerator") private Integer id; /** diff --git a/src/main/java/run/halo/app/model/entity/ThemeSetting.java b/src/main/java/run/halo/app/model/entity/ThemeSetting.java index d1ed62b56c..378c2c932a 100644 --- a/src/main/java/run/halo/app/model/entity/ThemeSetting.java +++ b/src/main/java/run/halo/app/model/entity/ThemeSetting.java @@ -1,12 +1,18 @@ package run.halo.app.model.entity; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Index; +import javax.persistence.Lob; +import javax.persistence.Table; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.ToString; import org.hibernate.annotations.GenericGenerator; -import javax.persistence.*; - /** * Theme setting entity. * @@ -16,15 +22,16 @@ @Data @Entity @Table(name = "theme_settings", indexes = { - @Index(name = "theme_settings_setting_key", columnList = "setting_key"), - @Index(name = "theme_settings_theme_id", columnList = "theme_id")}) + @Index(name = "theme_settings_setting_key", columnList = "setting_key"), + @Index(name = "theme_settings_theme_id", columnList = "theme_id")}) @ToString(callSuper = true) @EqualsAndHashCode(callSuper = true) public class ThemeSetting extends BaseEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY, generator = "custom-id") - @GenericGenerator(name = "custom-id", strategy = "run.halo.app.model.entity.support.CustomIdGenerator") + @GenericGenerator(name = "custom-id", + strategy = "run.halo.app.model.entity.support.CustomIdGenerator") private Integer id; /** diff --git a/src/main/java/run/halo/app/model/entity/User.java b/src/main/java/run/halo/app/model/entity/User.java index e61e2affd0..eec808bd6a 100644 --- a/src/main/java/run/halo/app/model/entity/User.java +++ b/src/main/java/run/halo/app/model/entity/User.java @@ -1,5 +1,14 @@ package run.halo.app.model.entity; +import java.util.Date; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.ToString; @@ -7,9 +16,6 @@ import run.halo.app.model.enums.MFAType; import run.halo.app.utils.DateUtils; -import javax.persistence.*; -import java.util.Date; - /** * User entity * diff --git a/src/main/java/run/halo/app/model/entity/support/CustomIdGenerator.java b/src/main/java/run/halo/app/model/entity/support/CustomIdGenerator.java index 3e3105e6ed..336f9c7339 100644 --- a/src/main/java/run/halo/app/model/entity/support/CustomIdGenerator.java +++ b/src/main/java/run/halo/app/model/entity/support/CustomIdGenerator.java @@ -1,11 +1,10 @@ package run.halo.app.model.entity.support; +import java.io.Serializable; import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.id.IdentityGenerator; import run.halo.app.utils.ReflectionUtils; -import java.io.Serializable; - /** * @author ryanwang * @date 2020-03-16 diff --git a/src/main/java/run/halo/app/model/enums/StaticDeployType.java b/src/main/java/run/halo/app/model/enums/StaticDeployType.java index a57df9b75f..babc4623cd 100644 --- a/src/main/java/run/halo/app/model/enums/StaticDeployType.java +++ b/src/main/java/run/halo/app/model/enums/StaticDeployType.java @@ -9,7 +9,8 @@ public enum StaticDeployType implements ValueEnum { /** - * Deploy static pages in remote git repository, such as github pages,gitee pages,coding pages.etc. + * Deploy static pages in remote git repository, such as github pages,gitee pages,coding + * pages.etc. */ GIT(0), diff --git a/src/main/java/run/halo/app/model/enums/ValueEnum.java b/src/main/java/run/halo/app/model/enums/ValueEnum.java index 8b2be9c375..2139710afc 100644 --- a/src/main/java/run/halo/app/model/enums/ValueEnum.java +++ b/src/main/java/run/halo/app/model/enums/ValueEnum.java @@ -1,8 +1,7 @@ package run.halo.app.model.enums; -import org.springframework.util.Assert; - import java.util.stream.Stream; +import org.springframework.util.Assert; /** * Interface for value enum. @@ -16,9 +15,9 @@ public interface ValueEnum { * Converts value to corresponding enum. * * @param enumType enum type - * @param value database value - * @param value generic - * @param enum generic + * @param value database value + * @param value generic + * @param enum generic * @return corresponding enum */ static > E valueToEnum(Class enumType, V value) { @@ -27,9 +26,9 @@ static > E valueToEnum(Class enumType, V value) { Assert.isTrue(enumType.isEnum(), "type must be an enum type"); return Stream.of(enumType.getEnumConstants()) - .filter(item -> item.getValue().equals(value)) - .findFirst() - .orElseThrow(() -> new IllegalArgumentException("unknown database value: " + value)); + .filter(item -> item.getValue().equals(value)) + .findFirst() + .orElseThrow(() -> new IllegalArgumentException("unknown database value: " + value)); } /** diff --git a/src/main/java/run/halo/app/model/enums/converter/AbstractConverter.java b/src/main/java/run/halo/app/model/enums/converter/AbstractConverter.java index d0d5ebc956..efa6378a57 100644 --- a/src/main/java/run/halo/app/model/enums/converter/AbstractConverter.java +++ b/src/main/java/run/halo/app/model/enums/converter/AbstractConverter.java @@ -1,11 +1,10 @@ package run.halo.app.model.enums.converter; -import run.halo.app.model.enums.ValueEnum; -import run.halo.app.utils.ReflectionUtils; - -import javax.persistence.AttributeConverter; import java.lang.reflect.Type; import java.util.Objects; +import javax.persistence.AttributeConverter; +import run.halo.app.model.enums.ValueEnum; +import run.halo.app.utils.ReflectionUtils; /** * Abstract converter. @@ -15,14 +14,16 @@ * @author johnniang * @date 12/6/18 */ -public abstract class AbstractConverter, V> implements AttributeConverter { +public abstract class AbstractConverter, V> + implements AttributeConverter { private final Class clazz; @SuppressWarnings("unchecked") protected AbstractConverter() { Type enumType = Objects.requireNonNull( - ReflectionUtils.getParameterizedTypeBySuperClass(AbstractConverter.class, this.getClass()) + ReflectionUtils + .getParameterizedTypeBySuperClass(AbstractConverter.class, this.getClass()) ).getActualTypeArguments()[0]; this.clazz = (Class) enumType; } diff --git a/src/main/java/run/halo/app/model/enums/converter/AttachmentTypeConverter.java b/src/main/java/run/halo/app/model/enums/converter/AttachmentTypeConverter.java index cf41493716..37019d49bd 100644 --- a/src/main/java/run/halo/app/model/enums/converter/AttachmentTypeConverter.java +++ b/src/main/java/run/halo/app/model/enums/converter/AttachmentTypeConverter.java @@ -1,8 +1,7 @@ package run.halo.app.model.enums.converter; -import run.halo.app.model.enums.AttachmentType; - import javax.persistence.Converter; +import run.halo.app.model.enums.AttachmentType; /** * Attachment type converter diff --git a/src/main/java/run/halo/app/model/enums/converter/CommentStatusConverter.java b/src/main/java/run/halo/app/model/enums/converter/CommentStatusConverter.java index 77e28d673c..c44fbc37e6 100644 --- a/src/main/java/run/halo/app/model/enums/converter/CommentStatusConverter.java +++ b/src/main/java/run/halo/app/model/enums/converter/CommentStatusConverter.java @@ -1,8 +1,7 @@ package run.halo.app.model.enums.converter; -import run.halo.app.model.enums.CommentStatus; - import javax.persistence.Converter; +import run.halo.app.model.enums.CommentStatus; /** * PostComment status converter. diff --git a/src/main/java/run/halo/app/model/enums/converter/DataTypeConverter.java b/src/main/java/run/halo/app/model/enums/converter/DataTypeConverter.java index fc633c6b60..a8a8acf63b 100644 --- a/src/main/java/run/halo/app/model/enums/converter/DataTypeConverter.java +++ b/src/main/java/run/halo/app/model/enums/converter/DataTypeConverter.java @@ -1,8 +1,7 @@ package run.halo.app.model.enums.converter; -import run.halo.app.model.enums.DataType; - import javax.persistence.Converter; +import run.halo.app.model.enums.DataType; /** * Data type converter. diff --git a/src/main/java/run/halo/app/model/enums/converter/LogTypeConverter.java b/src/main/java/run/halo/app/model/enums/converter/LogTypeConverter.java index fab227fe91..7ee6d49f9f 100644 --- a/src/main/java/run/halo/app/model/enums/converter/LogTypeConverter.java +++ b/src/main/java/run/halo/app/model/enums/converter/LogTypeConverter.java @@ -1,8 +1,7 @@ package run.halo.app.model.enums.converter; -import run.halo.app.model.enums.LogType; - import javax.persistence.Converter; +import run.halo.app.model.enums.LogType; /** * Log type converter. diff --git a/src/main/java/run/halo/app/model/enums/converter/PostStatusConverter.java b/src/main/java/run/halo/app/model/enums/converter/PostStatusConverter.java index 6e8fad90bf..f3f3dc415b 100644 --- a/src/main/java/run/halo/app/model/enums/converter/PostStatusConverter.java +++ b/src/main/java/run/halo/app/model/enums/converter/PostStatusConverter.java @@ -1,8 +1,7 @@ package run.halo.app.model.enums.converter; -import run.halo.app.model.enums.PostStatus; - import javax.persistence.Converter; +import run.halo.app.model.enums.PostStatus; /** * PostStatus converter. diff --git a/src/main/java/run/halo/app/model/enums/converter/PostTypeConverter.java b/src/main/java/run/halo/app/model/enums/converter/PostTypeConverter.java index b3815ed589..bd2a299000 100644 --- a/src/main/java/run/halo/app/model/enums/converter/PostTypeConverter.java +++ b/src/main/java/run/halo/app/model/enums/converter/PostTypeConverter.java @@ -1,8 +1,7 @@ package run.halo.app.model.enums.converter; -import run.halo.app.model.enums.PostType; - import javax.persistence.Converter; +import run.halo.app.model.enums.PostType; /** * PostType converter. diff --git a/src/main/java/run/halo/app/model/params/AttachmentParam.java b/src/main/java/run/halo/app/model/params/AttachmentParam.java index 95e4f29da9..a6dfb5a077 100644 --- a/src/main/java/run/halo/app/model/params/AttachmentParam.java +++ b/src/main/java/run/halo/app/model/params/AttachmentParam.java @@ -1,12 +1,11 @@ package run.halo.app.model.params; +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Size; import lombok.Data; import run.halo.app.model.dto.base.InputConverter; import run.halo.app.model.entity.Attachment; -import javax.validation.constraints.NotBlank; -import javax.validation.constraints.Size; - /** * Attachment params. * diff --git a/src/main/java/run/halo/app/model/params/BaseCommentParam.java b/src/main/java/run/halo/app/model/params/BaseCommentParam.java index 81cf4ca4dd..4536a4a2aa 100644 --- a/src/main/java/run/halo/app/model/params/BaseCommentParam.java +++ b/src/main/java/run/halo/app/model/params/BaseCommentParam.java @@ -1,15 +1,14 @@ package run.halo.app.model.params; -import lombok.Data; -import org.hibernate.validator.constraints.URL; -import run.halo.app.model.dto.base.InputConverter; -import run.halo.app.utils.ReflectionUtils; - +import java.lang.reflect.ParameterizedType; import javax.validation.constraints.Email; import javax.validation.constraints.Min; import javax.validation.constraints.NotBlank; import javax.validation.constraints.Size; -import java.lang.reflect.ParameterizedType; +import lombok.Data; +import org.hibernate.validator.constraints.URL; +import run.halo.app.model.dto.base.InputConverter; +import run.halo.app.utils.ReflectionUtils; /** * Base Comment param. @@ -48,6 +47,7 @@ public abstract class BaseCommentParam implements InputConverter implements InputConverter { @Override public ParameterizedType parameterizedType() { - return ReflectionUtils.getParameterizedTypeBySuperClass(BaseMetaParam.class, this.getClass()); + return ReflectionUtils + .getParameterizedTypeBySuperClass(BaseMetaParam.class, this.getClass()); } } diff --git a/src/main/java/run/halo/app/model/params/CategoryParam.java b/src/main/java/run/halo/app/model/params/CategoryParam.java index f789a7ea97..cc33d764c1 100644 --- a/src/main/java/run/halo/app/model/params/CategoryParam.java +++ b/src/main/java/run/halo/app/model/params/CategoryParam.java @@ -1,14 +1,13 @@ package run.halo.app.model.params; +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Size; import lombok.Data; import org.apache.commons.lang3.StringUtils; import run.halo.app.model.dto.base.InputConverter; import run.halo.app.model.entity.Category; import run.halo.app.utils.SlugUtils; -import javax.validation.constraints.NotBlank; -import javax.validation.constraints.Size; - /** * Category param. * diff --git a/src/main/java/run/halo/app/model/params/InstallParam.java b/src/main/java/run/halo/app/model/params/InstallParam.java index f6739514b3..9cea9fb56a 100644 --- a/src/main/java/run/halo/app/model/params/InstallParam.java +++ b/src/main/java/run/halo/app/model/params/InstallParam.java @@ -1,11 +1,10 @@ package run.halo.app.model.params; +import javax.validation.constraints.NotBlank; import lombok.Data; import lombok.EqualsAndHashCode; import run.halo.app.model.support.CreateCheck; -import javax.validation.constraints.NotBlank; - /** * Install parameters. * diff --git a/src/main/java/run/halo/app/model/params/JournalParam.java b/src/main/java/run/halo/app/model/params/JournalParam.java index 7e5bd1ab1d..9499997214 100644 --- a/src/main/java/run/halo/app/model/params/JournalParam.java +++ b/src/main/java/run/halo/app/model/params/JournalParam.java @@ -1,12 +1,11 @@ package run.halo.app.model.params; +import javax.validation.constraints.NotBlank; import lombok.Data; import run.halo.app.model.dto.base.InputConverter; import run.halo.app.model.entity.Journal; import run.halo.app.model.enums.JournalType; -import javax.validation.constraints.NotBlank; - /** * Journal param. * diff --git a/src/main/java/run/halo/app/model/params/LinkParam.java b/src/main/java/run/halo/app/model/params/LinkParam.java index 629e401102..716d8fec14 100644 --- a/src/main/java/run/halo/app/model/params/LinkParam.java +++ b/src/main/java/run/halo/app/model/params/LinkParam.java @@ -1,14 +1,13 @@ package run.halo.app.model.params; +import javax.validation.constraints.Min; +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Size; import lombok.Data; import org.hibernate.validator.constraints.URL; import run.halo.app.model.dto.base.InputConverter; import run.halo.app.model.entity.Link; -import javax.validation.constraints.Min; -import javax.validation.constraints.NotBlank; -import javax.validation.constraints.Size; - /** * Link param. * diff --git a/src/main/java/run/halo/app/model/params/LogParam.java b/src/main/java/run/halo/app/model/params/LogParam.java index f4a46e1879..1cfb9b31dd 100644 --- a/src/main/java/run/halo/app/model/params/LogParam.java +++ b/src/main/java/run/halo/app/model/params/LogParam.java @@ -1,5 +1,8 @@ package run.halo.app.model.params; +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Size; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @@ -7,10 +10,6 @@ import run.halo.app.model.entity.Log; import run.halo.app.model.enums.LogType; -import javax.validation.constraints.NotBlank; -import javax.validation.constraints.NotNull; -import javax.validation.constraints.Size; - /** * @author johnniang * @date 19-4-21 diff --git a/src/main/java/run/halo/app/model/params/LoginParam.java b/src/main/java/run/halo/app/model/params/LoginParam.java index bb72d10900..e0950dc905 100644 --- a/src/main/java/run/halo/app/model/params/LoginParam.java +++ b/src/main/java/run/halo/app/model/params/LoginParam.java @@ -1,10 +1,9 @@ package run.halo.app.model.params; -import lombok.Data; -import lombok.ToString; - import javax.validation.constraints.NotBlank; import javax.validation.constraints.Size; +import lombok.Data; +import lombok.ToString; /** * Login param. diff --git a/src/main/java/run/halo/app/model/params/MailParam.java b/src/main/java/run/halo/app/model/params/MailParam.java index 64733d823c..c82f531f5f 100644 --- a/src/main/java/run/halo/app/model/params/MailParam.java +++ b/src/main/java/run/halo/app/model/params/MailParam.java @@ -1,9 +1,8 @@ package run.halo.app.model.params; -import lombok.Data; - import javax.validation.constraints.Email; import javax.validation.constraints.NotBlank; +import lombok.Data; /** * Journal query params. diff --git a/src/main/java/run/halo/app/model/params/MenuParam.java b/src/main/java/run/halo/app/model/params/MenuParam.java index 480eba05cc..e1a7f619eb 100644 --- a/src/main/java/run/halo/app/model/params/MenuParam.java +++ b/src/main/java/run/halo/app/model/params/MenuParam.java @@ -1,14 +1,13 @@ package run.halo.app.model.params; +import javax.validation.constraints.Min; +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Size; import lombok.Data; import lombok.ToString; import run.halo.app.model.dto.base.InputConverter; import run.halo.app.model.entity.Menu; -import javax.validation.constraints.Min; -import javax.validation.constraints.NotBlank; -import javax.validation.constraints.Size; - /** * Menu param. * diff --git a/src/main/java/run/halo/app/model/params/MultiFactorAuthParam.java b/src/main/java/run/halo/app/model/params/MultiFactorAuthParam.java index 834e37fd1f..26e350211e 100644 --- a/src/main/java/run/halo/app/model/params/MultiFactorAuthParam.java +++ b/src/main/java/run/halo/app/model/params/MultiFactorAuthParam.java @@ -1,10 +1,9 @@ package run.halo.app.model.params; -import lombok.Data; -import run.halo.app.model.enums.MFAType; - import javax.validation.constraints.NotBlank; import javax.validation.constraints.Size; +import lombok.Data; +import run.halo.app.model.enums.MFAType; /** * Multi-Factor Auth Param. diff --git a/src/main/java/run/halo/app/model/params/OptionParam.java b/src/main/java/run/halo/app/model/params/OptionParam.java index 85e37bae06..d0276bdfb0 100644 --- a/src/main/java/run/halo/app/model/params/OptionParam.java +++ b/src/main/java/run/halo/app/model/params/OptionParam.java @@ -1,13 +1,12 @@ package run.halo.app.model.params; +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Size; import lombok.Data; import run.halo.app.model.dto.base.InputConverter; import run.halo.app.model.entity.Option; import run.halo.app.model.enums.OptionType; -import javax.validation.constraints.NotBlank; -import javax.validation.constraints.Size; - /** * Optional param. * diff --git a/src/main/java/run/halo/app/model/params/PasswordParam.java b/src/main/java/run/halo/app/model/params/PasswordParam.java index 2239a18fa5..268ad8a922 100644 --- a/src/main/java/run/halo/app/model/params/PasswordParam.java +++ b/src/main/java/run/halo/app/model/params/PasswordParam.java @@ -1,9 +1,8 @@ package run.halo.app.model.params; -import lombok.Data; - import javax.validation.constraints.NotBlank; import javax.validation.constraints.Size; +import lombok.Data; /** * User password param. diff --git a/src/main/java/run/halo/app/model/params/PhotoParam.java b/src/main/java/run/halo/app/model/params/PhotoParam.java index f0f71b7c5e..73e6d46f13 100644 --- a/src/main/java/run/halo/app/model/params/PhotoParam.java +++ b/src/main/java/run/halo/app/model/params/PhotoParam.java @@ -1,12 +1,11 @@ package run.halo.app.model.params; +import java.util.Date; +import javax.validation.constraints.NotBlank; import lombok.Data; import run.halo.app.model.dto.base.InputConverter; import run.halo.app.model.entity.Photo; -import javax.validation.constraints.NotBlank; -import java.util.Date; - /** * Post param. * diff --git a/src/main/java/run/halo/app/model/params/PostParam.java b/src/main/java/run/halo/app/model/params/PostParam.java index 85de44ba59..9048f91c55 100644 --- a/src/main/java/run/halo/app/model/params/PostParam.java +++ b/src/main/java/run/halo/app/model/params/PostParam.java @@ -1,5 +1,11 @@ package run.halo.app.model.params; +import java.util.Date; +import java.util.HashSet; +import java.util.Set; +import javax.validation.constraints.Min; +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Size; import lombok.Data; import org.apache.commons.lang3.StringUtils; import org.springframework.util.CollectionUtils; @@ -10,13 +16,6 @@ import run.halo.app.model.enums.PostStatus; import run.halo.app.utils.SlugUtils; -import javax.validation.constraints.Min; -import javax.validation.constraints.NotBlank; -import javax.validation.constraints.Size; -import java.util.Date; -import java.util.HashSet; -import java.util.Set; - /** * Post param. * diff --git a/src/main/java/run/halo/app/model/params/ResetPasswordParam.java b/src/main/java/run/halo/app/model/params/ResetPasswordParam.java index 998e5db0e3..688ceb9d24 100644 --- a/src/main/java/run/halo/app/model/params/ResetPasswordParam.java +++ b/src/main/java/run/halo/app/model/params/ResetPasswordParam.java @@ -1,8 +1,7 @@ package run.halo.app.model.params; -import lombok.Data; - import javax.validation.constraints.NotBlank; +import lombok.Data; /** * Reset password params. diff --git a/src/main/java/run/halo/app/model/params/SheetParam.java b/src/main/java/run/halo/app/model/params/SheetParam.java index 9fa1eb1871..b0b994fed8 100644 --- a/src/main/java/run/halo/app/model/params/SheetParam.java +++ b/src/main/java/run/halo/app/model/params/SheetParam.java @@ -1,5 +1,11 @@ package run.halo.app.model.params; +import java.util.Date; +import java.util.HashSet; +import java.util.Set; +import javax.validation.constraints.Min; +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Size; import lombok.Data; import org.apache.commons.lang3.StringUtils; import org.springframework.util.CollectionUtils; @@ -10,13 +16,6 @@ import run.halo.app.model.enums.PostStatus; import run.halo.app.utils.SlugUtils; -import javax.validation.constraints.Min; -import javax.validation.constraints.NotBlank; -import javax.validation.constraints.Size; -import java.util.Date; -import java.util.HashSet; -import java.util.Set; - /** * Sheet param. * diff --git a/src/main/java/run/halo/app/model/params/TagParam.java b/src/main/java/run/halo/app/model/params/TagParam.java index 6792c6db7e..8be796ae72 100644 --- a/src/main/java/run/halo/app/model/params/TagParam.java +++ b/src/main/java/run/halo/app/model/params/TagParam.java @@ -1,14 +1,13 @@ package run.halo.app.model.params; +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Size; import lombok.Data; import org.apache.commons.lang3.StringUtils; import run.halo.app.model.dto.base.InputConverter; import run.halo.app.model.entity.Tag; import run.halo.app.utils.SlugUtils; -import javax.validation.constraints.NotBlank; -import javax.validation.constraints.Size; - /** * Tag param. * diff --git a/src/main/java/run/halo/app/model/params/UserParam.java b/src/main/java/run/halo/app/model/params/UserParam.java index 789b3db50f..8b892a5d72 100644 --- a/src/main/java/run/halo/app/model/params/UserParam.java +++ b/src/main/java/run/halo/app/model/params/UserParam.java @@ -1,16 +1,15 @@ package run.halo.app.model.params; +import javax.validation.constraints.Email; +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Null; +import javax.validation.constraints.Size; import lombok.Data; import run.halo.app.model.dto.base.InputConverter; import run.halo.app.model.entity.User; import run.halo.app.model.support.CreateCheck; import run.halo.app.model.support.UpdateCheck; -import javax.validation.constraints.Email; -import javax.validation.constraints.NotBlank; -import javax.validation.constraints.Null; -import javax.validation.constraints.Size; - /** * User param. * @@ -25,22 +24,26 @@ public class UserParam implements InputConverter { private String username; @NotBlank(message = "用户昵称不能为空", groups = {CreateCheck.class, UpdateCheck.class}) - @Size(max = 255, message = "用户昵称的字符长度不能超过 {max}", groups = {CreateCheck.class, UpdateCheck.class}) + @Size(max = 255, message = "用户昵称的字符长度不能超过 {max}", groups = {CreateCheck.class, + UpdateCheck.class}) private String nickname; @Email(message = "电子邮件地址的格式不正确", groups = {CreateCheck.class, UpdateCheck.class}) @NotBlank(message = "电子邮件地址不能为空", groups = {CreateCheck.class, UpdateCheck.class}) - @Size(max = 127, message = "电子邮件的字符长度不能超过 {max}", groups = {CreateCheck.class, UpdateCheck.class}) + @Size(max = 127, message = "电子邮件的字符长度不能超过 {max}", groups = {CreateCheck.class, + UpdateCheck.class}) private String email; @Null(groups = UpdateCheck.class) @Size(min = 8, max = 100, message = "密码的字符长度必须在 {min} - {max} 之间", groups = {CreateCheck.class}) private String password; - @Size(max = 1023, message = "头像链接地址的字符长度不能超过 {max}", groups = {CreateCheck.class, UpdateCheck.class}) + @Size(max = 1023, message = "头像链接地址的字符长度不能超过 {max}", groups = {CreateCheck.class, + UpdateCheck.class}) private String avatar; - @Size(max = 1023, message = "用户描述的字符长度不能超过 {max}", groups = {CreateCheck.class, UpdateCheck.class}) + @Size(max = 1023, message = "用户描述的字符长度不能超过 {max}", groups = {CreateCheck.class, + UpdateCheck.class}) private String description; } diff --git a/src/main/java/run/halo/app/model/properties/CommentProperties.java b/src/main/java/run/halo/app/model/properties/CommentProperties.java index be9cfa2a16..189bf20024 100644 --- a/src/main/java/run/halo/app/model/properties/CommentProperties.java +++ b/src/main/java/run/halo/app/model/properties/CommentProperties.java @@ -47,7 +47,8 @@ public enum CommentProperties implements PropertyEnum { /** * Dependent comment js. */ - INTERNAL_PLUGIN_JS("comment_internal_plugin_js", String.class, "//cdn.jsdelivr.net/npm/halo-comment@latest/dist/halo-comment.min.js"), + INTERNAL_PLUGIN_JS("comment_internal_plugin_js", String.class, + "//cdn.jsdelivr.net/npm/halo-comment@latest/dist/halo-comment.min.js"), COMMENT_BAN_TIME("comment_ban_time", Integer.class, "10"), diff --git a/src/main/java/run/halo/app/model/properties/PermalinkProperties.java b/src/main/java/run/halo/app/model/properties/PermalinkProperties.java index 8151280fb8..5ab5cd7c56 100644 --- a/src/main/java/run/halo/app/model/properties/PermalinkProperties.java +++ b/src/main/java/run/halo/app/model/properties/PermalinkProperties.java @@ -14,12 +14,14 @@ public enum PermalinkProperties implements PropertyEnum { /** * Post Permalink type. */ - POST_PERMALINK_TYPE("post_permalink_type", PostPermalinkType.class, PostPermalinkType.DEFAULT.name()), + POST_PERMALINK_TYPE("post_permalink_type", PostPermalinkType.class, + PostPermalinkType.DEFAULT.name()), /** * Sheet Permalink type. */ - SHEET_PERMALINK_TYPE("sheet_permalink_type", SheetPermalinkType.class, SheetPermalinkType.SECONDARY.name()), + SHEET_PERMALINK_TYPE("sheet_permalink_type", SheetPermalinkType.class, + SheetPermalinkType.SECONDARY.name()), /** * Categories prefix diff --git a/src/main/java/run/halo/app/model/properties/PostProperties.java b/src/main/java/run/halo/app/model/properties/PostProperties.java index b1280737fc..b78c86a0e2 100644 --- a/src/main/java/run/halo/app/model/properties/PostProperties.java +++ b/src/main/java/run/halo/app/model/properties/PostProperties.java @@ -54,7 +54,8 @@ public enum PostProperties implements PropertyEnum { /** * Recycled post retention time unit. */ - RECYCLED_POST_RETENTION_TIMEUNIT("recycled_post_retention_timeunit", TimeUnit.class, TimeUnit.DAY.name()); + RECYCLED_POST_RETENTION_TIMEUNIT("recycled_post_retention_timeunit", TimeUnit.class, + TimeUnit.DAY.name()); private final String value; diff --git a/src/main/java/run/halo/app/model/properties/PropertyEnum.java b/src/main/java/run/halo/app/model/properties/PropertyEnum.java index 5e5535757f..a95192232b 100644 --- a/src/main/java/run/halo/app/model/properties/PropertyEnum.java +++ b/src/main/java/run/halo/app/model/properties/PropertyEnum.java @@ -1,16 +1,15 @@ package run.halo.app.model.properties; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; import org.apache.commons.lang3.StringUtils; import org.springframework.lang.NonNull; import org.springframework.lang.Nullable; import org.springframework.util.Assert; import run.halo.app.model.enums.ValueEnum; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; - /** * Property enum. * @@ -24,8 +23,8 @@ public interface PropertyEnum extends ValueEnum { * Converts to value with corresponding type * * @param value string value must not be blank - * @param type property value type must not be null - * @param property value type + * @param type property value type must not be null + * @param property value type * @return property value */ @SuppressWarnings("unchecked") @@ -66,13 +65,14 @@ static T convertTo(@NonNull String value, @NonNull Class type) { } // Should never happen - throw new UnsupportedOperationException("Unsupported convention for blog property type:" + type.getName() + " provided"); + throw new UnsupportedOperationException( + "Unsupported convention for blog property type:" + type.getName() + " provided"); } /** * Converts to value with corresponding type * - * @param value value + * @param value value * @param propertyEnum property enum must not be null * @return property value */ @@ -103,8 +103,8 @@ static Object convertTo(@Nullable String value, @NonNull PropertyEnum propertyEn * Converts to enum. * * @param value string value must not be null - * @param type propertye value enum type must not be null - * @param property value enum type + * @param type propertye value enum type must not be null + * @param property value enum type * @return property enum value or null */ @Nullable @@ -130,16 +130,16 @@ static boolean isSupportedType(Class type) { return false; } return type.isAssignableFrom(String.class) - || type.isAssignableFrom(Number.class) - || type.isAssignableFrom(Integer.class) - || type.isAssignableFrom(Long.class) - || type.isAssignableFrom(Boolean.class) - || type.isAssignableFrom(Short.class) - || type.isAssignableFrom(Byte.class) - || type.isAssignableFrom(Double.class) - || type.isAssignableFrom(Float.class) - || type.isAssignableFrom(Enum.class) - || type.isAssignableFrom(ValueEnum.class); + || type.isAssignableFrom(Number.class) + || type.isAssignableFrom(Integer.class) + || type.isAssignableFrom(Long.class) + || type.isAssignableFrom(Boolean.class) + || type.isAssignableFrom(Short.class) + || type.isAssignableFrom(Byte.class) + || type.isAssignableFrom(Double.class) + || type.isAssignableFrom(Float.class) + || type.isAssignableFrom(Enum.class) + || type.isAssignableFrom(ValueEnum.class); } static Map getValuePropertyEnumMap() { @@ -192,7 +192,7 @@ static Map getValuePropertyEnumMap() { * Default value with given type. * * @param propertyType property type must not be null - * @param property type + * @param property type * @return default value with given type */ @Nullable diff --git a/src/main/java/run/halo/app/model/support/BaseResponse.java b/src/main/java/run/halo/app/model/support/BaseResponse.java index 8e220faf12..155136b923 100644 --- a/src/main/java/run/halo/app/model/support/BaseResponse.java +++ b/src/main/java/run/halo/app/model/support/BaseResponse.java @@ -1,6 +1,10 @@ package run.halo.app.model.support; -import lombok.*; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.NoArgsConstructor; +import lombok.ToString; import org.springframework.http.HttpStatus; import org.springframework.lang.NonNull; import org.springframework.lang.Nullable; @@ -46,7 +50,7 @@ public BaseResponse(Integer status, String message, T data) { /** * Creates an ok result with message and data. (Default status is 200) * - * @param data result data + * @param data result data * @param message result message * @return ok result with message and data */ @@ -70,7 +74,7 @@ public static BaseResponse ok(@Nullable String message) { * Creates an ok result with data only. (Default message is OK, status is 200) * * @param data data to response - * @param data type + * @param data type * @return base response with data */ public static BaseResponse ok(@NonNull T data) { diff --git a/src/main/java/run/halo/app/model/support/CommentPage.java b/src/main/java/run/halo/app/model/support/CommentPage.java index 7a27146c3f..234f237752 100644 --- a/src/main/java/run/halo/app/model/support/CommentPage.java +++ b/src/main/java/run/halo/app/model/support/CommentPage.java @@ -1,13 +1,12 @@ package run.halo.app.model.support; +import java.util.List; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.ToString; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.Pageable; -import java.util.List; - /** * PostComment page implementation. * diff --git a/src/main/java/run/halo/app/model/support/HaloConst.java b/src/main/java/run/halo/app/model/support/HaloConst.java index 603ac524cd..93ce573e6c 100644 --- a/src/main/java/run/halo/app/model/support/HaloConst.java +++ b/src/main/java/run/halo/app/model/support/HaloConst.java @@ -1,9 +1,8 @@ package run.halo.app.model.support; -import org.springframework.http.HttpHeaders; - import java.io.File; import java.util.Optional; +import org.springframework.http.HttpHeaders; /** *
@@ -18,38 +17,38 @@ public class HaloConst {
     /**
      * User home directory.
      */
-    public final static String USER_HOME = System.getProperties().getProperty("user.home");
+    public static final String USER_HOME = System.getProperties().getProperty("user.home");
 
     /**
      * Temporary directory.
      */
-    public final static String TEMP_DIR = "/tmp/run.halo.app";
+    public static final String TEMP_DIR = "/tmp/run.halo.app";
 
-    public final static String PROTOCOL_HTTPS = "https://";
+    public static final String PROTOCOL_HTTPS = "https://";
 
-    public final static String PROTOCOL_HTTP = "http://";
+    public static final String PROTOCOL_HTTP = "http://";
 
-    public final static String URL_SEPARATOR = "/";
+    public static final String URL_SEPARATOR = "/";
 
     /**
      * Halo backup prefix.
      */
-    public final static String HALO_BACKUP_PREFIX = "halo-backup-";
+    public static final String HALO_BACKUP_PREFIX = "halo-backup-";
 
     /**
      * Halo backup markdown prefix.
      */
-    public final static String HALO_BACKUP_MARKDOWN_PREFIX = "halo-backup-markdown-";
+    public static final String HALO_BACKUP_MARKDOWN_PREFIX = "halo-backup-markdown-";
 
     /**
      * Halo data export prefix.
      */
-    public final static String HALO_DATA_EXPORT_PREFIX = "halo-data-export-";
+    public static final String HALO_DATA_EXPORT_PREFIX = "halo-data-export-";
 
     /**
      * Default theme name.
      */
-    public final static String DEFAULT_THEME_ID = "caicai_anatole";
+    public static final String DEFAULT_THEME_ID = "caicai_anatole";
 
     /**
      * Default error path.
@@ -80,7 +79,10 @@ public class HaloConst {
     /**
      * 网易云音乐 iframe 代码
      */
-    public static final String NETEASE_MUSIC_IFRAME = "";
+    public static final String NETEASE_MUSIC_IFRAME =
+        "";
     /**
      * 网易云音乐短代码正则表达式
      */
@@ -92,11 +94,15 @@ public class HaloConst {
     /**
      * 哔哩哔哩视频 iframe 代码
      */
-    public static final String BILIBILI_VIDEO_IFRAME = "";
+    public static final String BILIBILI_VIDEO_IFRAME =
+        "";
     /**
      * 哔哩哔哩视频正则表达式
      */
-    public static final String BILIBILI_VIDEO_REG_PATTERN = "\\[bilibili:(\\d+)\\,(\\d+)\\,(\\d+)\\]";
+    public static final String BILIBILI_VIDEO_REG_PATTERN =
+        "\\[bilibili:(\\d+)\\,(\\d+)\\,(\\d+)\\]";
     /**
      * YouTube 视频短代码前缀
      */
@@ -104,7 +110,10 @@ public class HaloConst {
     /**
      * YouTube 视频 iframe 代码
      */
-    public static final String YOUTUBE_VIDEO_IFRAME = "";
+    public static final String YOUTUBE_VIDEO_IFRAME =
+        "";
     /**
      * YouTube 视频正则表达式
      */
@@ -112,21 +121,25 @@ public class HaloConst {
     /**
      * Content token header name.
      */
-    public final static String API_ACCESS_KEY_HEADER_NAME = "API-" + HttpHeaders.AUTHORIZATION;
+    public static final String API_ACCESS_KEY_HEADER_NAME = "API-" + HttpHeaders.AUTHORIZATION;
     /**
      * Admin token header name.
      */
-    public final static String ADMIN_TOKEN_HEADER_NAME = "ADMIN-" + HttpHeaders.AUTHORIZATION;
+    public static final String ADMIN_TOKEN_HEADER_NAME = "ADMIN-" + HttpHeaders.AUTHORIZATION;
     /**
      * Admin token param name.
      */
-    public final static String ADMIN_TOKEN_QUERY_NAME = "admin_token";
+    public static final String ADMIN_TOKEN_QUERY_NAME = "admin_token";
+    /**
+     * Temporary token.
+     */
+    public static final String TEMP_TOKEN = "temp_token";
     /**
      * Content api token param name
      */
-    public final static String API_ACCESS_KEY_QUERY_NAME = "api_access_key";
-    public final static String ONE_TIME_TOKEN_QUERY_NAME = "ott";
-    public final static String ONE_TIME_TOKEN_HEADER_NAME = "ott";
+    public static final String API_ACCESS_KEY_QUERY_NAME = "api_access_key";
+    public static final String ONE_TIME_TOKEN_QUERY_NAME = "ott";
+    public static final String ONE_TIME_TOKEN_HEADER_NAME = "ott";
     /**
      * Version constant. (Available in production environment)
      */
@@ -144,6 +157,7 @@ public class HaloConst {
 
     static {
         // Set version
-        HALO_VERSION = Optional.ofNullable(HaloConst.class.getPackage().getImplementationVersion()).orElse(UNKNOWN_VERSION);
+        HALO_VERSION = Optional.ofNullable(HaloConst.class.getPackage().getImplementationVersion())
+            .orElse(UNKNOWN_VERSION);
     }
 }
diff --git a/src/main/java/run/halo/app/model/support/Pagination.java b/src/main/java/run/halo/app/model/support/Pagination.java
index 1459cd286a..ea112f004f 100644
--- a/src/main/java/run/halo/app/model/support/Pagination.java
+++ b/src/main/java/run/halo/app/model/support/Pagination.java
@@ -1,8 +1,7 @@
 package run.halo.app.model.support;
 
-import lombok.Data;
-
 import java.util.List;
+import lombok.Data;
 
 /**
  * @author ryanwang
diff --git a/src/main/java/run/halo/app/model/support/StaticFile.java b/src/main/java/run/halo/app/model/support/StaticFile.java
index c7f05e6933..03dfbf63eb 100644
--- a/src/main/java/run/halo/app/model/support/StaticFile.java
+++ b/src/main/java/run/halo/app/model/support/StaticFile.java
@@ -1,10 +1,9 @@
 package run.halo.app.model.support;
 
-import lombok.Data;
-import lombok.ToString;
-
 import java.util.Comparator;
 import java.util.List;
+import lombok.Data;
+import lombok.ToString;
 
 /**
  * Static file.
diff --git a/src/main/java/run/halo/app/model/support/StaticPageFile.java b/src/main/java/run/halo/app/model/support/StaticPageFile.java
index f92139d1ad..0b5d04d5fa 100644
--- a/src/main/java/run/halo/app/model/support/StaticPageFile.java
+++ b/src/main/java/run/halo/app/model/support/StaticPageFile.java
@@ -1,9 +1,8 @@
 package run.halo.app.model.support;
 
-import lombok.Data;
-
 import java.util.Comparator;
 import java.util.List;
+import lombok.Data;
 
 /**
  * Static page dto.
diff --git a/src/main/java/run/halo/app/model/support/ThemeFile.java b/src/main/java/run/halo/app/model/support/ThemeFile.java
index ac70473d6a..fda7e130f8 100644
--- a/src/main/java/run/halo/app/model/support/ThemeFile.java
+++ b/src/main/java/run/halo/app/model/support/ThemeFile.java
@@ -1,10 +1,9 @@
 package run.halo.app.model.support;
 
-import lombok.Data;
-import lombok.ToString;
-
 import java.util.Comparator;
 import java.util.List;
+import lombok.Data;
+import lombok.ToString;
 
 /**
  * Theme file.
diff --git a/src/main/java/run/halo/app/model/vo/ArchiveMonthVO.java b/src/main/java/run/halo/app/model/vo/ArchiveMonthVO.java
index 87321a26fb..ab6a27b286 100644
--- a/src/main/java/run/halo/app/model/vo/ArchiveMonthVO.java
+++ b/src/main/java/run/halo/app/model/vo/ArchiveMonthVO.java
@@ -1,11 +1,10 @@
 package run.halo.app.model.vo;
 
+import java.util.Comparator;
 import lombok.Data;
 import lombok.EqualsAndHashCode;
 import lombok.ToString;
 
-import java.util.Comparator;
-
 /**
  * Month archive vo.
  *
diff --git a/src/main/java/run/halo/app/model/vo/ArchiveYearVO.java b/src/main/java/run/halo/app/model/vo/ArchiveYearVO.java
index 30b3f16f7f..dcdc0c3eab 100644
--- a/src/main/java/run/halo/app/model/vo/ArchiveYearVO.java
+++ b/src/main/java/run/halo/app/model/vo/ArchiveYearVO.java
@@ -1,12 +1,11 @@
 package run.halo.app.model.vo;
 
+import java.util.Comparator;
+import java.util.List;
 import lombok.Data;
 import lombok.EqualsAndHashCode;
 import lombok.ToString;
 
-import java.util.Comparator;
-import java.util.List;
-
 /**
  * Year archive vo.
  *
diff --git a/src/main/java/run/halo/app/model/vo/BaseCommentVO.java b/src/main/java/run/halo/app/model/vo/BaseCommentVO.java
index 7077539f26..f495ffdd71 100644
--- a/src/main/java/run/halo/app/model/vo/BaseCommentVO.java
+++ b/src/main/java/run/halo/app/model/vo/BaseCommentVO.java
@@ -1,12 +1,11 @@
 package run.halo.app.model.vo;
 
+import java.util.List;
 import lombok.Data;
 import lombok.EqualsAndHashCode;
 import lombok.ToString;
 import run.halo.app.model.dto.BaseCommentDTO;
 
-import java.util.List;
-
 /**
  * Base comment vo.
  *
diff --git a/src/main/java/run/halo/app/model/vo/CategoryVO.java b/src/main/java/run/halo/app/model/vo/CategoryVO.java
index 658060e5ac..aef84b74e4 100644
--- a/src/main/java/run/halo/app/model/vo/CategoryVO.java
+++ b/src/main/java/run/halo/app/model/vo/CategoryVO.java
@@ -1,12 +1,11 @@
 package run.halo.app.model.vo;
 
+import java.util.List;
 import lombok.Data;
 import lombok.EqualsAndHashCode;
 import lombok.ToString;
 import run.halo.app.model.dto.CategoryDTO;
 
-import java.util.List;
-
 /**
  * Category vo.
  *
diff --git a/src/main/java/run/halo/app/model/vo/LinkTeamVO.java b/src/main/java/run/halo/app/model/vo/LinkTeamVO.java
index 600d111956..a99c758eca 100644
--- a/src/main/java/run/halo/app/model/vo/LinkTeamVO.java
+++ b/src/main/java/run/halo/app/model/vo/LinkTeamVO.java
@@ -1,11 +1,10 @@
 package run.halo.app.model.vo;
 
+import java.util.List;
 import lombok.Data;
 import lombok.ToString;
 import run.halo.app.model.dto.LinkDTO;
 
-import java.util.List;
-
 /**
  * Link team vo.
  *
diff --git a/src/main/java/run/halo/app/model/vo/MenuTeamVO.java b/src/main/java/run/halo/app/model/vo/MenuTeamVO.java
index ef11c3f783..f744a738ec 100644
--- a/src/main/java/run/halo/app/model/vo/MenuTeamVO.java
+++ b/src/main/java/run/halo/app/model/vo/MenuTeamVO.java
@@ -1,11 +1,10 @@
 package run.halo.app.model.vo;
 
+import java.util.List;
 import lombok.Data;
 import lombok.ToString;
 import run.halo.app.model.dto.MenuDTO;
 
-import java.util.List;
-
 /**
  * Menu team vo.
  *
diff --git a/src/main/java/run/halo/app/model/vo/MenuVO.java b/src/main/java/run/halo/app/model/vo/MenuVO.java
index 95c759cbbe..d55cea4122 100644
--- a/src/main/java/run/halo/app/model/vo/MenuVO.java
+++ b/src/main/java/run/halo/app/model/vo/MenuVO.java
@@ -1,13 +1,12 @@
 package run.halo.app.model.vo;
 
+import java.util.LinkedList;
+import java.util.List;
 import lombok.Data;
 import lombok.EqualsAndHashCode;
 import lombok.ToString;
 import run.halo.app.model.dto.MenuDTO;
 
-import java.util.LinkedList;
-import java.util.List;
-
 /**
  * @author ryanwang
  * @date 2019-04-07
diff --git a/src/main/java/run/halo/app/model/vo/PhotoTeamVO.java b/src/main/java/run/halo/app/model/vo/PhotoTeamVO.java
index 8c15ee8bb1..2b93a91ba0 100644
--- a/src/main/java/run/halo/app/model/vo/PhotoTeamVO.java
+++ b/src/main/java/run/halo/app/model/vo/PhotoTeamVO.java
@@ -1,11 +1,10 @@
 package run.halo.app.model.vo;
 
+import java.util.List;
 import lombok.Data;
 import lombok.ToString;
 import run.halo.app.model.dto.PhotoDTO;
 
-import java.util.List;
-
 /**
  * Link team vo.
  *
diff --git a/src/main/java/run/halo/app/model/vo/PostDetailVO.java b/src/main/java/run/halo/app/model/vo/PostDetailVO.java
index a6d2552f88..6717caf635 100644
--- a/src/main/java/run/halo/app/model/vo/PostDetailVO.java
+++ b/src/main/java/run/halo/app/model/vo/PostDetailVO.java
@@ -1,5 +1,7 @@
 package run.halo.app.model.vo;
 
+import java.util.List;
+import java.util.Set;
 import lombok.Data;
 import lombok.EqualsAndHashCode;
 import lombok.ToString;
@@ -8,9 +10,6 @@
 import run.halo.app.model.dto.TagDTO;
 import run.halo.app.model.dto.post.BasePostDetailDTO;
 
-import java.util.List;
-import java.util.Set;
-
 /**
  * Post vo.
  *
diff --git a/src/main/java/run/halo/app/model/vo/PostListVO.java b/src/main/java/run/halo/app/model/vo/PostListVO.java
index a2f32f239c..07a29ef7d3 100644
--- a/src/main/java/run/halo/app/model/vo/PostListVO.java
+++ b/src/main/java/run/halo/app/model/vo/PostListVO.java
@@ -1,14 +1,13 @@
 package run.halo.app.model.vo;
 
+import java.util.List;
+import java.util.Map;
 import lombok.Data;
 import lombok.EqualsAndHashCode;
 import run.halo.app.model.dto.CategoryDTO;
 import run.halo.app.model.dto.TagDTO;
 import run.halo.app.model.dto.post.BasePostSimpleDTO;
 
-import java.util.List;
-import java.util.Map;
-
 /**
  * Post list vo.
  *
diff --git a/src/main/java/run/halo/app/model/vo/SheetDetailVO.java b/src/main/java/run/halo/app/model/vo/SheetDetailVO.java
index 0f2e8d38ee..fed027bb6d 100644
--- a/src/main/java/run/halo/app/model/vo/SheetDetailVO.java
+++ b/src/main/java/run/halo/app/model/vo/SheetDetailVO.java
@@ -1,14 +1,13 @@
 package run.halo.app.model.vo;
 
+import java.util.List;
+import java.util.Set;
 import lombok.Data;
 import lombok.EqualsAndHashCode;
 import lombok.ToString;
 import run.halo.app.model.dto.BaseMetaDTO;
 import run.halo.app.model.dto.post.BasePostDetailDTO;
 
-import java.util.List;
-import java.util.Set;
-
 /**
  * Sheet detail VO.
  *
diff --git a/src/main/java/run/halo/app/repository/AttachmentRepository.java b/src/main/java/run/halo/app/repository/AttachmentRepository.java
index 210676f49b..dd68ba3c14 100644
--- a/src/main/java/run/halo/app/repository/AttachmentRepository.java
+++ b/src/main/java/run/halo/app/repository/AttachmentRepository.java
@@ -1,5 +1,6 @@
 package run.halo.app.repository;
 
+import java.util.List;
 import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
 import org.springframework.data.jpa.repository.Query;
 import org.springframework.lang.NonNull;
@@ -7,8 +8,6 @@
 import run.halo.app.model.enums.AttachmentType;
 import run.halo.app.repository.base.BaseRepository;
 
-import java.util.List;
-
 /**
  * Attachment repository
  *
@@ -16,7 +15,8 @@
  * @author ryanwang
  * @date 2019-04-03
  */
-public interface AttachmentRepository extends BaseRepository, JpaSpecificationExecutor {
+public interface AttachmentRepository
+    extends BaseRepository, JpaSpecificationExecutor {
 
     /**
      * Find all attachment media type.
diff --git a/src/main/java/run/halo/app/repository/CategoryRepository.java b/src/main/java/run/halo/app/repository/CategoryRepository.java
index ad73f5b9a1..888354f05d 100644
--- a/src/main/java/run/halo/app/repository/CategoryRepository.java
+++ b/src/main/java/run/halo/app/repository/CategoryRepository.java
@@ -1,12 +1,11 @@
 package run.halo.app.repository;
 
+import java.util.List;
+import java.util.Optional;
 import org.springframework.lang.NonNull;
 import run.halo.app.model.entity.Category;
 import run.halo.app.repository.base.BaseRepository;
 
-import java.util.List;
-import java.util.Optional;
-
 /**
  * Category repository.
  *
diff --git a/src/main/java/run/halo/app/repository/CommentBlackListRepository.java b/src/main/java/run/halo/app/repository/CommentBlackListRepository.java
index 54b664d0c1..50ca251379 100644
--- a/src/main/java/run/halo/app/repository/CommentBlackListRepository.java
+++ b/src/main/java/run/halo/app/repository/CommentBlackListRepository.java
@@ -1,13 +1,12 @@
 package run.halo.app.repository;
 
+import java.util.Optional;
 import org.springframework.data.jpa.repository.Modifying;
 import org.springframework.data.jpa.repository.Query;
 import org.springframework.data.repository.query.Param;
 import run.halo.app.model.entity.CommentBlackList;
 import run.halo.app.repository.base.BaseRepository;
 
-import java.util.Optional;
-
 /**
  * 评论黑名单Repository
  *
@@ -17,20 +16,21 @@
 public interface CommentBlackListRepository extends BaseRepository {
 
     /**
-     * 根据IP地址获取数据
+     * 根据IP地址获取数据.
      *
-     * @param ipAddress
-     * @return
+     * @param ipAddress ip address
+     * @return comment black list or empty
      */
     Optional findByIpAddress(String ipAddress);
 
     /**
-     * Update Comment BlackList By IPAddress
+     * Update Comment BlackList By IPAddress.
      *
-     * @param commentBlackList
+     * @param commentBlackList comment black list
      * @return result
      */
     @Modifying
-    @Query("UPDATE CommentBlackList SET banTime=:#{#commentBlackList.banTime} WHERE ipAddress=:#{#commentBlackList.ipAddress}")
+    @Query("UPDATE CommentBlackList SET banTime=:#{#commentBlackList.banTime} WHERE "
+        + "ipAddress=:#{#commentBlackList.ipAddress}")
     int updateByIpAddress(@Param("commentBlackList") CommentBlackList commentBlackList);
 }
diff --git a/src/main/java/run/halo/app/repository/JournalCommentRepository.java b/src/main/java/run/halo/app/repository/JournalCommentRepository.java
index 99699799ba..5da988bf0b 100644
--- a/src/main/java/run/halo/app/repository/JournalCommentRepository.java
+++ b/src/main/java/run/halo/app/repository/JournalCommentRepository.java
@@ -1,5 +1,7 @@
 package run.halo.app.repository;
 
+import java.util.Collection;
+import java.util.List;
 import org.springframework.data.jpa.repository.Query;
 import org.springframework.lang.NonNull;
 import run.halo.app.model.entity.JournalComment;
@@ -7,9 +9,6 @@
 import run.halo.app.model.projection.CommentCountProjection;
 import run.halo.app.repository.base.BaseCommentRepository;
 
-import java.util.Collection;
-import java.util.List;
-
 /**
  * Journal comment repository.
  *
@@ -25,9 +24,11 @@ public interface JournalCommentRepository extends BaseCommentRepository countByPostIds(@NonNull Collection postIds);
@@ -38,11 +39,14 @@ public interface JournalCommentRepository extends BaseCommentRepository findDirectChildrenCount(@NonNull Collection commentIds);
+    List findDirectChildrenCount(
+        @NonNull Collection commentIds);
 }
diff --git a/src/main/java/run/halo/app/repository/JournalRepository.java b/src/main/java/run/halo/app/repository/JournalRepository.java
index 671ae21484..92a70c5db4 100644
--- a/src/main/java/run/halo/app/repository/JournalRepository.java
+++ b/src/main/java/run/halo/app/repository/JournalRepository.java
@@ -18,12 +18,13 @@
  * @author ryanwang
  * @date 2019-03-22
  */
-public interface JournalRepository extends BaseRepository, JpaSpecificationExecutor {
+public interface JournalRepository
+    extends BaseRepository, JpaSpecificationExecutor {
 
     /**
      * Finds journals by type and pageable.
      *
-     * @param type     journal type must not be null
+     * @param type journal type must not be null
      * @param pageable page info must not be null
      * @return a page of journal
      */
@@ -34,7 +35,7 @@ public interface JournalRepository extends BaseRepository, Jpa
      * Updates journal likes.
      *
      * @param likes likes delta
-     * @param id    id must not be null
+     * @param id id must not be null
      * @return updated rows
      */
     @Modifying
diff --git a/src/main/java/run/halo/app/repository/LinkRepository.java b/src/main/java/run/halo/app/repository/LinkRepository.java
index f54d9dfc29..37f9f98289 100755
--- a/src/main/java/run/halo/app/repository/LinkRepository.java
+++ b/src/main/java/run/halo/app/repository/LinkRepository.java
@@ -1,11 +1,10 @@
 package run.halo.app.repository;
 
+import java.util.List;
 import org.springframework.data.jpa.repository.Query;
 import run.halo.app.model.entity.Link;
 import run.halo.app.repository.base.BaseRepository;
 
-import java.util.List;
-
 /**
  * Link repository.
  *
diff --git a/src/main/java/run/halo/app/repository/MenuRepository.java b/src/main/java/run/halo/app/repository/MenuRepository.java
index 3957d81666..bf21600649 100644
--- a/src/main/java/run/halo/app/repository/MenuRepository.java
+++ b/src/main/java/run/halo/app/repository/MenuRepository.java
@@ -1,13 +1,12 @@
 package run.halo.app.repository;
 
+import java.util.List;
 import org.springframework.data.domain.Sort;
 import org.springframework.data.jpa.repository.Query;
 import org.springframework.lang.NonNull;
 import run.halo.app.model.entity.Menu;
 import run.halo.app.repository.base.BaseRepository;
 
-import java.util.List;
-
 /**
  * Menu repository.
  *
@@ -28,7 +27,7 @@ public interface MenuRepository extends BaseRepository {
     /**
      * Query if the menu name already exists by id and name.
      *
-     * @param id   id must not be null.
+     * @param id id must not be null.
      * @param name name must not be null.
      * @return true or false.
      */
diff --git a/src/main/java/run/halo/app/repository/OptionRepository.java b/src/main/java/run/halo/app/repository/OptionRepository.java
index aa92e11cde..2cb73d4b57 100755
--- a/src/main/java/run/halo/app/repository/OptionRepository.java
+++ b/src/main/java/run/halo/app/repository/OptionRepository.java
@@ -1,11 +1,10 @@
 package run.halo.app.repository;
 
+import java.util.Optional;
 import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
 import run.halo.app.model.entity.Option;
 import run.halo.app.repository.base.BaseRepository;
 
-import java.util.Optional;
-
 /**
  * Option repository.
  *
@@ -13,7 +12,8 @@
  * @author ryanwang
  * @date 2019-03-20
  */
-public interface OptionRepository extends BaseRepository, JpaSpecificationExecutor