diff --git a/build.gradle b/build.gradle index c98802c97..1bd8d3f09 100644 --- a/build.gradle +++ b/build.gradle @@ -1,7 +1,7 @@ plugins { id 'org.springframework.boot' version '2.2.2.RELEASE' id "io.freefair.lombok" version "3.6.6" -// id 'war' + id 'checkstyle' id 'java' } diff --git a/config/checkstyle/checkstyle.xml b/config/checkstyle/checkstyle.xml new file mode 100644 index 000000000..47422c615 --- /dev/null +++ b/config/checkstyle/checkstyle.xml @@ -0,0 +1,90 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/haloCodeStyle.xml b/haloCodeStyle.xml deleted file mode 100644 index 8756f6089..000000000 --- a/haloCodeStyle.xml +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/main/java/run/halo/app/Application.java b/src/main/java/run/halo/app/Application.java index 6b7852598..cc4b4a59a 100755 --- a/src/main/java/run/halo/app/Application.java +++ b/src/main/java/run/halo/app/Application.java @@ -25,14 +25,14 @@ import run.halo.app.repository.base.BaseRepositoryImpl; @EnableJpaRepositories(basePackages = "run.halo.app.repository", repositoryBaseClass = BaseRepositoryImpl.class) public class Application extends SpringBootServletInitializer { - private static ConfigurableApplicationContext context; + private static ConfigurableApplicationContext CONTEXT; public static void main(String[] args) { // Customize the spring config location System.setProperty("spring.config.additional-location", "file:${user.home}/.halo/,file:${user.home}/halo-dev/"); // Run application - context = SpringApplication.run(Application.class, args); + CONTEXT = SpringApplication.run(Application.class, args); } @@ -40,11 +40,11 @@ public class Application extends SpringBootServletInitializer { * Restart Application. */ public static void restart() { - ApplicationArguments args = context.getBean(ApplicationArguments.class); + ApplicationArguments args = CONTEXT.getBean(ApplicationArguments.class); Thread thread = new Thread(() -> { - context.close(); - context = SpringApplication.run(Application.class, args.getSourceArgs()); + CONTEXT.close(); + CONTEXT = SpringApplication.run(Application.class, args.getSourceArgs()); }); thread.setDaemon(false); diff --git a/src/main/java/run/halo/app/cache/LevelCacheStore.java b/src/main/java/run/halo/app/cache/LevelCacheStore.java index 954b90d8f..1c57f20c1 100644 --- a/src/main/java/run/halo/app/cache/LevelCacheStore.java +++ b/src/main/java/run/halo/app/cache/LevelCacheStore.java @@ -28,8 +28,7 @@ public class LevelCacheStore extends StringCacheStore { */ private final static long PERIOD = 60 * 1000; - private static DB leveldb; - + private static DB LEVEL_DB; private Timer timer; @@ -38,7 +37,7 @@ public class LevelCacheStore extends StringCacheStore { @PostConstruct public void init() { - if (leveldb != null) return; + if (LEVEL_DB != null) return; try { //work path File folder = new File(haloProperties.getWorkDir() + ".leveldb"); @@ -46,7 +45,7 @@ public class LevelCacheStore extends StringCacheStore { Options options = new Options(); options.createIfMissing(true); //open leveldb store folder - leveldb = factory.open(folder, options); + LEVEL_DB = factory.open(folder, options); timer = new Timer(); timer.scheduleAtFixedRate(new CacheExpiryCleaner(), 0, PERIOD); } catch (Exception ex) { @@ -60,7 +59,7 @@ public class LevelCacheStore extends StringCacheStore { @PreDestroy public void preDestroy() { try { - leveldb.close(); + LEVEL_DB.close(); timer.cancel(); } catch (IOException e) { log.error("close leveldb error ", e); @@ -70,7 +69,7 @@ public class LevelCacheStore extends StringCacheStore { @Override Optional> getInternal(String key) { Assert.hasText(key, "Cache key must not be blank"); - byte[] bytes = leveldb.get(stringToBytes(key)); + byte[] bytes = LEVEL_DB.get(stringToBytes(key)); if (bytes != null) { String valueJson = bytesToString(bytes); return StringUtils.isEmpty(valueJson) ? Optional.empty() : jsonToCacheWrapper(valueJson); @@ -88,9 +87,9 @@ public class LevelCacheStore extends StringCacheStore { Assert.hasText(key, "Cache key must not be blank"); Assert.notNull(cacheWrapper, "Cache wrapper must not be null"); try { - leveldb.put( - stringToBytes(key), - stringToBytes(JsonUtils.objectToJson(cacheWrapper)) + LEVEL_DB.put( + stringToBytes(key), + stringToBytes(JsonUtils.objectToJson(cacheWrapper)) ); return true; } catch (JsonProcessingException e) { @@ -102,7 +101,7 @@ public class LevelCacheStore extends StringCacheStore { @Override public void delete(String key) { - leveldb.delete(stringToBytes(key)); + LEVEL_DB.delete(stringToBytes(key)); log.debug("cache remove key: [{}]", key); } @@ -132,9 +131,9 @@ public class LevelCacheStore extends StringCacheStore { @Override public void run() { //batch - WriteBatch writeBatch = leveldb.createWriteBatch(); + WriteBatch writeBatch = LEVEL_DB.createWriteBatch(); - DBIterator iterator = leveldb.iterator(); + DBIterator iterator = LEVEL_DB.iterator(); long currentTimeMillis = System.currentTimeMillis(); while (iterator.hasNext()) { Map.Entry next = iterator.next(); @@ -147,8 +146,8 @@ public class LevelCacheStore extends StringCacheStore { 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()); @@ -156,7 +155,7 @@ public class LevelCacheStore extends StringCacheStore { } } } - leveldb.write(writeBatch); + LEVEL_DB.write(writeBatch); } } } diff --git a/src/main/java/run/halo/app/config/HaloConfiguration.java b/src/main/java/run/halo/app/config/HaloConfiguration.java index b2792d068..0b8d63d03 100644 --- a/src/main/java/run/halo/app/config/HaloConfiguration.java +++ b/src/main/java/run/halo/app/config/HaloConfiguration.java @@ -55,10 +55,10 @@ public class HaloConfiguration { @Bean public RestTemplate httpsRestTemplate(RestTemplateBuilder builder) - throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException { + throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException { RestTemplate httpsRestTemplate = builder.build(); httpsRestTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory(HttpClientUtils.createHttpsClient( - (int) haloProperties.getDownloadTimeout().toMillis()))); + (int) haloProperties.getDownloadTimeout().toMillis()))); return httpsRestTemplate; } @@ -125,12 +125,12 @@ public class HaloConfiguration { String adminPattern = HaloUtils.ensureBoth(haloProperties.getAdminPath(), "/") + "**"; contentFilter.addExcludeUrlPatterns( - adminPattern, - "/api/**", - "/install", - "/version", - "/js/**", - "/css/**"); + adminPattern, + "/api/**", + "/install", + "/version", + "/js/**", + "/css/**"); FilterRegistrationBean contentFrb = new FilterRegistrationBean<>(); contentFrb.addUrlPatterns("/*"); @@ -148,9 +148,9 @@ public class HaloConfiguration { OneTimeTokenService oneTimeTokenService) { ApiAuthenticationFilter apiFilter = new ApiAuthenticationFilter(haloProperties, optionService, cacheStore, oneTimeTokenService); apiFilter.addExcludeUrlPatterns( - "/api/content/*/comments", - "/api/content/**/comments/**", - "/api/content/options/comment" + "/api/content/*/comments", + "/api/content/**/comments/**", + "/api/content/options/comment" ); DefaultAuthenticationFailureHandler failureHandler = new DefaultAuthenticationFailureHandler(); @@ -176,7 +176,7 @@ public class HaloConfiguration { OptionService optionService, OneTimeTokenService oneTimeTokenService) { AdminAuthenticationFilter adminAuthenticationFilter = new AdminAuthenticationFilter(cacheStore, userService, - haloProperties, optionService, oneTimeTokenService); + haloProperties, optionService, oneTimeTokenService); DefaultAuthenticationFailureHandler failureHandler = new DefaultAuthenticationFailureHandler(); failureHandler.setProductionEnv(haloProperties.isProductionEnv()); @@ -184,14 +184,14 @@ public class HaloConfiguration { // Config the admin filter adminAuthenticationFilter.addExcludeUrlPatterns( - "/api/admin/login", - "/api/admin/refresh/*", - "/api/admin/installations", - "/api/admin/recoveries/migrations/*", - "/api/admin/migrations/*", - "/api/admin/is_installed", - "/api/admin/password/code", - "/api/admin/password/reset" + "/api/admin/login", + "/api/admin/refresh/*", + "/api/admin/installations", + "/api/admin/recoveries/migrations/*", + "/api/admin/migrations/*", + "/api/admin/is_installed", + "/api/admin/password/code", + "/api/admin/password/reset" ); adminAuthenticationFilter.setFailureHandler(failureHandler); diff --git a/src/main/java/run/halo/app/config/SwaggerConfiguration.java b/src/main/java/run/halo/app/config/SwaggerConfiguration.java index e87cf19e3..7ac736661 100644 --- a/src/main/java/run/halo/app/config/SwaggerConfiguration.java +++ b/src/main/java/run/halo/app/config/SwaggerConfiguration.java @@ -47,12 +47,12 @@ 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; @@ -65,11 +65,11 @@ public class SwaggerConfiguration { } return buildApiDocket("run.halo.app.content.api", - "run.halo.app.controller.content.api", - "/api/content/**") - .securitySchemes(contentApiKeys()) - .securityContexts(contentSecurityContext()) - .enable(!haloProperties.isDocDisabled()); + "run.halo.app.controller.content.api", + "/api/content/**") + .securitySchemes(contentApiKeys()) + .securityContexts(contentSecurityContext()) + .enable(!haloProperties.isDocDisabled()); } @Bean @@ -79,24 +79,24 @@ public class SwaggerConfiguration { } return buildApiDocket("run.halo.app.admin.api", - "run.halo.app.controller.admin", - "/api/admin/**") - .securitySchemes(adminApiKeys()) - .securityContexts(adminSecurityContext()) - .enable(!haloProperties.isDocDisabled()); + "run.halo.app.controller.admin", + "/api/admin/**") + .securitySchemes(adminApiKeys()) + .securityContexts(adminSecurityContext()) + .enable(!haloProperties.isDocDisabled()); } @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(); } private Docket buildApiDocket(@NonNull String groupName, @NonNull String basePackage, @NonNull String antPattern) { @@ -105,74 +105,74 @@ public class SwaggerConfiguration { 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")}; 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")}; 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", "i#ryanc.cc")) - .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", "i#ryanc.cc")) + .license("GNU General Public License v3.0") + .licenseUrl("https://github.com/halo-dev/halo/blob/master/LICENSE") + .build(); } @Bean @@ -186,10 +186,10 @@ public class SwaggerConfiguration { @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()))); } }; } @@ -204,31 +204,31 @@ public class SwaggerConfiguration { 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/WebMvcAutoConfiguration.java b/src/main/java/run/halo/app/config/WebMvcAutoConfiguration.java index e66ef1865..de99fbb9f 100644 --- a/src/main/java/run/halo/app/config/WebMvcAutoConfiguration.java +++ b/src/main/java/run/halo/app/config/WebMvcAutoConfiguration.java @@ -76,15 +76,16 @@ public class WebMvcAutoConfiguration extends WebMvcConfigurationSupport { @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 @@ -105,29 +106,29 @@ public class WebMvcAutoConfiguration extends WebMvcConfigurationSupport { // register /** resource handler. registry.addResourceHandler("/**") - .addResourceLocations(workDir + "templates/admin/") - .addResourceLocations("classpath:/admin/") - .addResourceLocations(workDir + "static/"); + .addResourceLocations(workDir + "templates/admin/") + .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 adminPathPattern = ensureSuffix(haloProperties.getAdminPath(), URL_SEPARATOR) + "**"; registry.addResourceHandler(uploadUrlPattern) - .addResourceLocations(workDir + "upload/"); + .addResourceLocations(workDir + "upload/"); registry.addResourceHandler(adminPathPattern) - .addResourceLocations(workDir + HALO_ADMIN_RELATIVE_PATH) - .addResourceLocations("classpath:/admin/"); + .addResourceLocations(workDir + HALO_ADMIN_RELATIVE_PATH) + .addResourceLocations("classpath:/admin/"); if (!haloProperties.isDocDisabled()) { // 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/controller/admin/api/BackupController.java b/src/main/java/run/halo/app/controller/admin/api/BackupController.java index b250f2da0..451a97503 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 @@ -72,9 +72,9 @@ public class BackupController { } 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("halo") 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 219835ac7..2af07e9c7 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 @@ -46,8 +46,8 @@ public class CategoryController { @GetMapping @ApiOperation("Lists all categories") public List listAll( - @SortDefault(sort = "updateTime", direction = DESC) Sort sort, - @RequestParam(name = "more", required = false, defaultValue = "false") boolean more) { + @SortDefault(sort = "updateTime", direction = DESC) Sort sort, + @RequestParam(name = "more", required = false, defaultValue = "false") boolean more) { if (more) { return postCategoryService.listCategoryWithPostCountDto(sort); } 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 bfb0fb32d..60852aa07 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 @@ -110,7 +110,7 @@ public class InstallController { createDefaultMenu(); eventPublisher.publishEvent( - new LogEvent(this, user.getId().toString(), LogType.BLOG_INITIALIZED, "博客已成功初始化") + new LogEvent(this, user.getId().toString(), LogType.BLOG_INITIALIZED, "博客已成功初始化") ); return BaseResponse.ok("安装完成!"); @@ -167,8 +167,8 @@ public class InstallController { postParam.setTitle("Hello Halo"); postParam.setStatus(PostStatus.PUBLISHED); postParam.setOriginalContent("## Hello Halo!\n" + - "\n" + - "感谢使用 [Halo](https://github.com/halo-dev/halo) 进行创作,请删除该文章开始吧!"); + "\n" + + "感谢使用 [Halo](https://github.com/halo-dev/halo) 进行创作,请删除该文章开始吧!"); if (category != null) { Set categoryIds = new HashSet<>(); @@ -218,7 +218,7 @@ public class InstallController { 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()); + optionService.getBlogBaseUrl() : installParam.getUrl()); properties.put(PrimaryProperties.BIRTHDAY, String.valueOf(System.currentTimeMillis())); // Create properties 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 9934dddb4..798b36563 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 @@ -72,7 +72,7 @@ public class LinkController { } @GetMapping("teams") - @ApiOperation(("Lists all link teams")) + @ApiOperation("Lists all link teams") public List teams() { return linkService.listAllTeams(); } 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 8aeb534df..50fb3df83 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 @@ -85,7 +85,7 @@ public class MenuController { } @GetMapping("teams") - @ApiOperation(("Lists all menu teams")) + @ApiOperation("Lists all menu teams") public List teams() { return menuService.listAllTeams(); } 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 3fca601b8..102199deb 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 @@ -125,8 +125,8 @@ public class PostController { @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); @@ -142,8 +142,8 @@ public class PostController { @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); diff --git a/src/main/java/run/halo/app/controller/admin/api/RecoveryController.java b/src/main/java/run/halo/app/controller/admin/api/RecoveryController.java index 76407ee15..7b9e8463f 100644 --- a/src/main/java/run/halo/app/controller/admin/api/RecoveryController.java +++ b/src/main/java/run/halo/app/controller/admin/api/RecoveryController.java @@ -38,8 +38,8 @@ public class RecoveryController { @ApiOperation("Migrates from halo v0.4.3") @CacheLock public void migrateFromVersion_0_4_3( - @ApiParam("This file content type should be json") - @RequestPart("file") MultipartFile file) { + @ApiParam("This file content type should be json") + @RequestPart("file") MultipartFile file) { if (optionService.getByPropertyOrDefault(PrimaryProperties.IS_INSTALLED, Boolean.class, false)) { throw new BadRequestException("无法在博客初始化完成之后迁移数据"); } 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 83647639d..3d5bdb0e0 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 @@ -82,9 +82,9 @@ public class SheetController { @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); @@ -97,8 +97,8 @@ public class SheetController { @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 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 f56b9e4a4..cc28e9b55 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 @@ -107,7 +107,7 @@ public class PostModel { model.addAttribute("comments", Page.empty()); if (themeService.templateExists( - ThemeService.CUSTOM_POST_PREFIX + post.getTemplate() + HaloConst.SUFFIX_FTL)) { + ThemeService.CUSTOM_POST_PREFIX + post.getTemplate() + HaloConst.SUFFIX_FTL)) { return themeService.render(ThemeService.CUSTOM_POST_PREFIX + post.getTemplate()); } @@ -117,7 +117,7 @@ public class PostModel { public String list(Integer page, Model model, String decide, String template) { 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); @@ -135,15 +135,15 @@ public class PostModel { } nextPageFullPath.append("/page/") - .append(posts.getNumber() + 2) - .append(optionService.getPathSuffix()); + .append(posts.getNumber() + 2) + .append(optionService.getPathSuffix()); if (posts.getNumber() == 1) { prePageFullPath.append("/"); } else { prePageFullPath.append("/page/") - .append(posts.getNumber()) - .append(optionService.getPathSuffix()); + .append(posts.getNumber()) + .append(optionService.getPathSuffix()); } model.addAttribute(decide, 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 4d332a211..f152b2425 100644 --- a/src/main/java/run/halo/app/controller/core/CommonController.java +++ b/src/main/java/run/halo/app/controller/core/CommonController.java @@ -70,10 +70,10 @@ public class CommonController extends AbstractErrorController { @GetMapping public String handleError(HttpServletRequest request, HttpServletResponse response, Model model) { log.error("Request URL: [{}], URI: [{}], Request Method: [{}], IP: [{}]", - request.getRequestURL(), - request.getRequestURI(), - request.getMethod(), - ServletUtil.getClientIP(request)); + request.getRequestURL(), + request.getRequestURI(), + request.getMethod(), + ServletUtil.getClientIP(request)); handleCustomException(request); @@ -138,9 +138,9 @@ public class CommonController extends AbstractErrorController { 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(); } diff --git a/src/main/java/run/halo/app/core/CommonResultControllerAdvice.java b/src/main/java/run/halo/app/core/CommonResultControllerAdvice.java index 53a731c57..e2c3e7acf 100644 --- a/src/main/java/run/halo/app/core/CommonResultControllerAdvice.java +++ b/src/main/java/run/halo/app/core/CommonResultControllerAdvice.java @@ -43,7 +43,7 @@ public class CommonResultControllerAdvice implements ResponseBodyAdvice * 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, diff --git a/src/main/java/run/halo/app/core/ControllerExceptionHandler.java b/src/main/java/run/halo/app/core/ControllerExceptionHandler.java index 2bc317394..0943c4b5f 100644 --- a/src/main/java/run/halo/app/core/ControllerExceptionHandler.java +++ b/src/main/java/run/halo/app/core/ControllerExceptionHandler.java @@ -27,7 +27,7 @@ import java.util.Map; * * @author johnniang */ -@RestControllerAdvice({"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 { diff --git a/src/main/java/run/halo/app/core/ControllerLogAop.java b/src/main/java/run/halo/app/core/ControllerLogAop.java index c3df45de3..0e0be2aaf 100644 --- a/src/main/java/run/halo/app/core/ControllerLogAop.java +++ b/src/main/java/run/halo/app/core/ControllerLogAop.java @@ -53,10 +53,10 @@ public class ControllerLogAop { 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; @@ -65,10 +65,10 @@ public class ControllerLogAop { boolean shouldNotLog = false; for (Object arg : args) { if (arg == null || - arg instanceof HttpServletRequest || - arg instanceof HttpServletResponse || - arg instanceof MultipartFile || - arg.getClass().isAssignableFrom(MultipartFile[].class)) { + arg instanceof HttpServletRequest || + arg instanceof HttpServletResponse || + arg instanceof MultipartFile || + arg.getClass().isAssignableFrom(MultipartFile[].class)) { shouldNotLog = true; break; } diff --git a/src/main/java/run/halo/app/factory/StringToEnumConverterFactory.java b/src/main/java/run/halo/app/factory/StringToEnumConverterFactory.java index 1e1155636..3214e05ec 100644 --- a/src/main/java/run/halo/app/factory/StringToEnumConverterFactory.java +++ b/src/main/java/run/halo/app/factory/StringToEnumConverterFactory.java @@ -18,7 +18,7 @@ public class StringToEnumConverterFactory implements ConverterFactory - implements Converter { + implements Converter { private Class enumType; diff --git a/src/main/java/run/halo/app/filter/LogFilter.java b/src/main/java/run/halo/app/filter/LogFilter.java index 25d7808cc..bc68c0b97 100644 --- a/src/main/java/run/halo/app/filter/LogFilter.java +++ b/src/main/java/run/halo/app/filter/LogFilter.java @@ -32,7 +32,7 @@ public class LogFilter extends OncePerRequestFilter { // Do filter filterChain.doFilter(request, response); - log.debug("Ending url: [{}], method: [{}], ip: [{}], status: [{}], usage: [{}] ms", request.getRequestURL(), request.getMethod(), remoteAddr, response.getStatus(), (System.currentTimeMillis() - startTime)); + log.debug("Ending url: [{}], method: [{}], ip: [{}], status: [{}], usage: [{}] ms", request.getRequestURL(), request.getMethod(), remoteAddr, response.getStatus(), System.currentTimeMillis() - startTime); log.debug(""); } } 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 6e4e4149e..47ca3e8c4 100644 --- a/src/main/java/run/halo/app/handler/file/AliOssFileHandler.java +++ b/src/main/java/run/halo/app/handler/file/AliOssFileHandler.java @@ -60,12 +60,12 @@ public class AliOssFileHandler implements FileHandler { if (StringUtils.isNotEmpty(domain)) { basePath.append(domain) - .append("/"); + .append("/"); } else { basePath.append(bucketName) - .append(".") - .append(endPoint) - .append("/"); + .append(".") + .append(endPoint) + .append("/"); } try { @@ -76,14 +76,14 @@ public class AliOssFileHandler implements FileHandler { if (StringUtils.isNotEmpty(source)) { upFilePath.append(source) - .append("/"); + .append("/"); } upFilePath.append(basename) - .append("_") - .append(timestamp) - .append(".") - .append(extension); + .append("_") + .append(timestamp) + .append(".") + .append(extension); String filePath = StringUtils.join(basePath.toString(), upFilePath.toString()); 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 7e8376a4c..abad7797a 100644 --- a/src/main/java/run/halo/app/handler/file/FileHandler.java +++ b/src/main/java/run/halo/app/handler/file/FileHandler.java @@ -7,7 +7,6 @@ import org.springframework.lang.Nullable; import org.springframework.util.Assert; import org.springframework.web.multipart.MultipartFile; import run.halo.app.exception.FileOperationException; -import run.halo.app.model.enums.AttachmentType; import run.halo.app.model.support.UploadResult; import static run.halo.app.model.support.HaloConst.FILE_SEPARATOR; 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 64433c1c5..99421a1c8 100644 --- a/src/main/java/run/halo/app/handler/file/QiniuOssFileHandler.java +++ b/src/main/java/run/halo/app/handler/file/QiniuOssFileHandler.java @@ -72,10 +72,10 @@ public class QiniuOssFileHandler implements FileHandler { // Build put plicy StringMap putPolicy = new StringMap(); putPolicy.put("returnBody", "{\"size\":$(fsize), " + - "\"width\":$(imageInfo.width), " + - "\"height\":$(imageInfo.height)," + - " \"key\":\"$(key)\", " + - "\"hash\":\"$(etag)\"}"); + "\"width\":$(imageInfo.width), " + + "\"height\":$(imageInfo.height)," + + " \"key\":\"$(key)\", " + + "\"hash\":\"$(etag)\"}"); // Get upload token String uploadToken = auth.uploadToken(bucket, null, 3600, putPolicy); @@ -83,8 +83,8 @@ public class QiniuOssFileHandler implements FileHandler { Path tmpPath = Paths.get(System.getProperty("java.io.tmpdir"), bucket); StringBuilder basePath = new StringBuilder(protocol) - .append(domain) - .append("/"); + .append(domain) + .append("/"); try { String basename = FilenameUtils.getBasename(Objects.requireNonNull(file.getOriginalFilename())); @@ -93,13 +93,13 @@ public class QiniuOssFileHandler implements FileHandler { StringBuilder upFilePath = new StringBuilder(); if (StringUtils.isNotEmpty(source)) { upFilePath.append(source) - .append("/"); + .append("/"); } 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()); 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 fbc90c0c7..785b58184 100644 --- a/src/main/java/run/halo/app/handler/file/SmmsFileHandler.java +++ b/src/main/java/run/halo/app/handler/file/SmmsFileHandler.java @@ -1,5 +1,6 @@ package run.halo.app.handler.file; +import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Data; import lombok.NoArgsConstructor; import lombok.extern.slf4j.Slf4j; @@ -189,7 +190,8 @@ public class SmmsFileHandler implements FileHandler { private SmmsResponseData data; - private String RequestId; + @JsonProperty("RequestId") + private String requestId; } @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 81fe15508..5d70ca792 100644 --- a/src/main/java/run/halo/app/handler/file/TencentCosFileHandler.java +++ b/src/main/java/run/halo/app/handler/file/TencentCosFileHandler.java @@ -68,13 +68,13 @@ public class TencentCosFileHandler implements FileHandler { if (StringUtils.isNotEmpty(domain)) { basePath.append(domain) - .append("/"); + .append("/"); } else { basePath.append(bucketName) - .append(".cos.") - .append(region) - .append(".myqcloud.com") - .append("/"); + .append(".cos.") + .append(region) + .append(".myqcloud.com") + .append("/"); } try { @@ -85,14 +85,14 @@ public class TencentCosFileHandler implements FileHandler { if (StringUtils.isNotEmpty(source)) { upFilePath.append(source) - .append("/"); + .append("/"); } upFilePath.append(basename) - .append("_") - .append(timestamp) - .append(".") - .append(extension); + .append("_") + .append(timestamp) + .append(".") + .append(extension); String filePath = StringUtils.join(basePath.toString(), upFilePath.toString()); diff --git a/src/main/java/run/halo/app/handler/migrate/OldVersionMigrateHandler.java b/src/main/java/run/halo/app/handler/migrate/OldVersionMigrateHandler.java index 8ebc22c96..2f40d92e9 100644 --- a/src/main/java/run/halo/app/handler/migrate/OldVersionMigrateHandler.java +++ b/src/main/java/run/halo/app/handler/migrate/OldVersionMigrateHandler.java @@ -230,8 +230,8 @@ public class OldVersionMigrateHandler implements MigrateHandler { log.debug("Migrated tags of post [{}]: [{}]", tags, createdPost.getId()); List postComments = baseComments.stream() - .map(baseComment -> BeanUtils.transformFrom(baseComment, PostComment.class)) - .collect(Collectors.toList()); + .map(baseComment -> BeanUtils.transformFrom(baseComment, PostComment.class)) + .collect(Collectors.toList()); try { // Build virtual comment @@ -259,8 +259,8 @@ public class OldVersionMigrateHandler implements MigrateHandler { List baseComments = handleComment(commentsObject, createdSheet.getId()); List sheetComments = baseComments.stream() - .map(baseComment -> BeanUtils.transformFrom(baseComment, SheetComment.class)) - .collect(Collectors.toList()); + .map(baseComment -> BeanUtils.transformFrom(baseComment, SheetComment.class)) + .collect(Collectors.toList()); // Create comments try { @@ -293,8 +293,8 @@ public class OldVersionMigrateHandler implements MigrateHandler { } // Get all children List children = postComments.stream() - .filter(postComment -> Objects.equals(oldParentId, postComment.getParentId())) - .collect(Collectors.toList()); + .filter(postComment -> Objects.equals(oldParentId, postComment.getParentId())) + .collect(Collectors.toList()); // Set parent id again @@ -320,8 +320,8 @@ public class OldVersionMigrateHandler implements MigrateHandler { } // Get all children List children = sheetComments.stream() - .filter(sheetComment -> Objects.equals(oldParentId, sheetComment.getParentId())) - .collect(Collectors.toList()); + .filter(sheetComment -> Objects.equals(oldParentId, sheetComment.getParentId())) + .collect(Collectors.toList()); // Set parent id again children.forEach(postComment -> postComment.setParentId(parentComment.getId())); diff --git a/src/main/java/run/halo/app/handler/migrate/utils/PropertyMappingTo.java b/src/main/java/run/halo/app/handler/migrate/utils/PropertyMappingTo.java index 4b6cb5e2d..2ad0d95fd 100644 --- a/src/main/java/run/halo/app/handler/migrate/utils/PropertyMappingTo.java +++ b/src/main/java/run/halo/app/handler/migrate/utils/PropertyMappingTo.java @@ -8,7 +8,7 @@ import java.lang.annotation.*; * @author guqing * @date 2020-1-19 13:51 */ -@Target({ElementType.FIELD, ElementType.TYPE}) +@Target(value = {ElementType.FIELD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface PropertyMappingTo { diff --git a/src/main/java/run/halo/app/handler/migrate/utils/RelationMapperUtils.java b/src/main/java/run/halo/app/handler/migrate/utils/RelationMapperUtils.java index a5c799dd3..d90739798 100644 --- a/src/main/java/run/halo/app/handler/migrate/utils/RelationMapperUtils.java +++ b/src/main/java/run/halo/app/handler/migrate/utils/RelationMapperUtils.java @@ -114,7 +114,7 @@ public class RelationMapperUtils { // Common situation fieldName = methodType + fieldName.substring(0, 1).toUpperCase() + - fieldName.substring(1); + fieldName.substring(1); return fieldName; } 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 2df232102..77c2d5c56 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 @@ -50,7 +50,7 @@ public class YamlThemeConfigResolverImpl implements ThemeConfigResolver { return; } - Map tabMap = ((Map) tabYaml); + Map tabMap = (Map) tabYaml; Group group = new Group(); diff --git a/src/main/java/run/halo/app/listener/StartedListener.java b/src/main/java/run/halo/app/listener/StartedListener.java index 0ba175e7f..1f05c8783 100644 --- a/src/main/java/run/halo/app/listener/StartedListener.java +++ b/src/main/java/run/halo/app/listener/StartedListener.java @@ -78,12 +78,12 @@ public class StartedListener implements ApplicationListener properties) { - this.properties = properties; - } - @Override public Map getProperties() { return this.properties; } + public void setProperties(Map properties) { + this.properties = properties; + } + @Override public String toString() { final String lineSuffix = ",\n"; diff --git a/src/main/java/run/halo/app/mail/MailServiceImpl.java b/src/main/java/run/halo/app/mail/MailServiceImpl.java index 501a0409d..2afe91a9a 100644 --- a/src/main/java/run/halo/app/mail/MailServiceImpl.java +++ b/src/main/java/run/halo/app/mail/MailServiceImpl.java @@ -56,7 +56,7 @@ public class MailServiceImpl extends AbstractMailService implements ApplicationL @Override public void sendAttachMail(String to, String subject, Map content, String templateName, String attachFilePath) { - sendMailTemplate(true, (messageHelper) -> { + sendMailTemplate(true, messageHelper -> { messageHelper.setSubject(subject); messageHelper.setTo(to); Path attachmentPath = Paths.get(attachFilePath); 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 0256d8598..87fb50047 100644 --- a/src/main/java/run/halo/app/model/entity/PostCategory.java +++ b/src/main/java/run/halo/app/model/entity/PostCategory.java @@ -50,7 +50,7 @@ public class PostCategory extends BaseEntity { } PostCategory that = (PostCategory) o; return categoryId.equals(that.categoryId) && - postId.equals(that.postId); + postId.equals(that.postId); } @Override 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 dbc49ff12..c6df28629 100644 --- a/src/main/java/run/halo/app/model/entity/PostTag.java +++ b/src/main/java/run/halo/app/model/entity/PostTag.java @@ -51,7 +51,7 @@ public class PostTag extends BaseEntity { } PostTag postTag = (PostTag) o; return Objects.equals(postId, postTag.postId) && - Objects.equals(tagId, postTag.tagId); + Objects.equals(tagId, postTag.tagId); } @Override diff --git a/src/main/java/run/halo/app/model/enums/BanStatusEnum.java b/src/main/java/run/halo/app/model/enums/BanStatusEnum.java index c36ab2b03..477e0ba24 100644 --- a/src/main/java/run/halo/app/model/enums/BanStatusEnum.java +++ b/src/main/java/run/halo/app/model/enums/BanStatusEnum.java @@ -13,8 +13,7 @@ public enum BanStatusEnum { /** * 封禁状态 */ - NORMAL(0), - ; + NORMAL(0); private int status; diff --git a/src/main/java/run/halo/app/model/enums/CommentViolationTypeEnum.java b/src/main/java/run/halo/app/model/enums/CommentViolationTypeEnum.java index 15a31a294..5136b3ba4 100644 --- a/src/main/java/run/halo/app/model/enums/CommentViolationTypeEnum.java +++ b/src/main/java/run/halo/app/model/enums/CommentViolationTypeEnum.java @@ -17,8 +17,7 @@ public enum CommentViolationTypeEnum { /** * 频繁 */ - FREQUENTLY(1), - ; + FREQUENTLY(1); private int type; 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 8b2be9c37..7a1bae7b9 100644 --- a/src/main/java/run/halo/app/model/enums/ValueEnum.java +++ b/src/main/java/run/halo/app/model/enums/ValueEnum.java @@ -27,9 +27,9 @@ public interface ValueEnum { 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/properties/PropertyEnum.java b/src/main/java/run/halo/app/model/properties/PropertyEnum.java index 1416d7221..aba660bf3 100644 --- a/src/main/java/run/halo/app/model/properties/PropertyEnum.java +++ b/src/main/java/run/halo/app/model/properties/PropertyEnum.java @@ -20,40 +20,6 @@ import java.util.Map; public interface PropertyEnum extends ValueEnum { - /** - * Get property type. - * - * @return property type - */ - Class getType(); - - /** - * Default value. - * - * @return default value - */ - @Nullable - String defaultValue(); - - /** - * Default value with given type. - * - * @param propertyType property type must not be null - * @param property type - * @return default value with given type - */ - @Nullable - default T defaultValue(Class propertyType) { - // Get default value - String defaultValue = defaultValue(); - if (defaultValue == null) { - return null; - } - - // Convert to the given type - return PropertyEnum.convertTo(defaultValue, propertyType); - } - /** * Converts to value with corresponding type * @@ -160,19 +126,20 @@ public interface PropertyEnum extends ValueEnum { * @return true if supports; false else */ static boolean isSupportedType(Class type) { - return type != null && ( - 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) - ); + if (type == null) { + 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); } static Map getValuePropertyEnumMap() { @@ -209,4 +176,38 @@ public interface PropertyEnum extends ValueEnum { return result; } + /** + * Get property type. + * + * @return property type + */ + Class getType(); + + /** + * Default value. + * + * @return default value + */ + @Nullable + String defaultValue(); + + /** + * Default value with given type. + * + * @param propertyType property type must not be null + * @param property type + * @return default value with given type + */ + @Nullable + default T defaultValue(Class propertyType) { + // Get default value + String defaultValue = defaultValue(); + if (defaultValue == null) { + return null; + } + + // Convert to the given type + return PropertyEnum.convertTo(defaultValue, propertyType); + } + } diff --git a/src/main/java/run/halo/app/model/support/AllCheck.java b/src/main/java/run/halo/app/model/support/AllCheck.java deleted file mode 100644 index 4f1523cbe..000000000 --- a/src/main/java/run/halo/app/model/support/AllCheck.java +++ /dev/null @@ -1,13 +0,0 @@ -package run.halo.app.model.support; - -import javax.validation.GroupSequence; - -/** - * All check for hibernate validation. - * - * @author johnniang - * @date 19-4-28 - */ -@GroupSequence({CreateCheck.class, UpdateCheck.class}) -public interface AllCheck { -} diff --git a/src/main/java/run/halo/app/repository/JournalCommentRepository.java b/src/main/java/run/halo/app/repository/JournalCommentRepository.java index 99699799b..719c9f0e6 100644 --- a/src/main/java/run/halo/app/repository/JournalCommentRepository.java +++ b/src/main/java/run/halo/app/repository/JournalCommentRepository.java @@ -26,8 +26,8 @@ public interface JournalCommentRepository extends BaseCommentRepository countByPostIds(@NonNull Collection postIds); @@ -39,9 +39,9 @@ public interface JournalCommentRepository extends BaseCommentRepository findDirectChildrenCount(@NonNull Collection commentIds); diff --git a/src/main/java/run/halo/app/repository/PostCommentRepository.java b/src/main/java/run/halo/app/repository/PostCommentRepository.java index 37ec1878a..fd918434a 100644 --- a/src/main/java/run/halo/app/repository/PostCommentRepository.java +++ b/src/main/java/run/halo/app/repository/PostCommentRepository.java @@ -27,8 +27,8 @@ public interface PostCommentRepository extends BaseCommentRepository countByPostIds(@NonNull Collection postIds); @@ -40,9 +40,9 @@ public interface PostCommentRepository extends BaseCommentRepository findDirectChildrenCount(@NonNull Collection commentIds); diff --git a/src/main/java/run/halo/app/repository/SheetCommentRepository.java b/src/main/java/run/halo/app/repository/SheetCommentRepository.java index 4b4083813..bc937aae2 100644 --- a/src/main/java/run/halo/app/repository/SheetCommentRepository.java +++ b/src/main/java/run/halo/app/repository/SheetCommentRepository.java @@ -26,8 +26,8 @@ public interface SheetCommentRepository extends BaseCommentRepository countByPostIds(@NonNull Collection sheetIds); @@ -39,9 +39,9 @@ public interface SheetCommentRepository extends BaseCommentRepository findDirectChildrenCount(@NonNull Collection commentIds); diff --git a/src/main/java/run/halo/app/repository/base/BaseCommentRepository.java b/src/main/java/run/halo/app/repository/base/BaseCommentRepository.java index 5b31c52ff..45e63af93 100644 --- a/src/main/java/run/halo/app/repository/base/BaseCommentRepository.java +++ b/src/main/java/run/halo/app/repository/base/BaseCommentRepository.java @@ -61,9 +61,9 @@ public interface BaseCommentRepository extends Base * @return a list of comment count */ @Query("select new run.halo.app.model.projection.CommentCountProjection(count(comment.id), comment.postId) " + - "from BaseComment comment " + - "where comment.postId in ?1 " + - "group by comment.postId") + "from BaseComment comment " + + "where comment.postId in ?1 " + + "group by comment.postId") @NonNull List countByPostIds(@NonNull Collection postIds); @@ -181,9 +181,9 @@ public interface BaseCommentRepository extends Base * @return a list of CommentChildrenCountProjection */ @Query("select new run.halo.app.model.projection.CommentChildrenCountProjection(count(comment.id), comment.parentId) " + - "from BaseComment comment " + - "where comment.parentId in ?1 " + - "group by comment.parentId") + "from BaseComment comment " + + "where comment.parentId in ?1 " + + "group by comment.parentId") @NonNull List findDirectChildrenCount(@NonNull Collection commentIds); } diff --git a/src/main/java/run/halo/app/repository/base/BaseRepositoryImpl.java b/src/main/java/run/halo/app/repository/base/BaseRepositoryImpl.java index a426ba9de..7999e84b6 100644 --- a/src/main/java/run/halo/app/repository/base/BaseRepositoryImpl.java +++ b/src/main/java/run/halo/app/repository/base/BaseRepositoryImpl.java @@ -110,8 +110,8 @@ public class BaseRepositoryImpl extends SimpleJpaRepository countQuery = getCountQuery(specification, getDomainClass()).setParameter(specification.parameter, ids); return pageable.isUnpaged() ? - new PageImpl<>(query.getResultList()) - : readPage(query, getDomainClass(), pageable, countQuery); + new PageImpl<>(query.getResultList()) + : readPage(query, getDomainClass(), pageable, countQuery); } /** @@ -143,7 +143,7 @@ public class BaseRepositoryImpl extends SimpleJpaRepository executeCountQuery(countQuery)); + () -> executeCountQuery(countQuery)); } private static final class ByIdsSpecification implements Specification { diff --git a/src/main/java/run/halo/app/security/filter/AbstractAuthenticationFilter.java b/src/main/java/run/halo/app/security/filter/AbstractAuthenticationFilter.java index d04a2849d..4e38b42e1 100644 --- a/src/main/java/run/halo/app/security/filter/AbstractAuthenticationFilter.java +++ b/src/main/java/run/halo/app/security/filter/AbstractAuthenticationFilter.java @@ -197,7 +197,7 @@ public abstract class AbstractAuthenticationFilter extends OncePerRequestFilter // Get allowed uri String allowedUri = oneTimeTokenService.get(oneTimeToken) - .orElseThrow(() -> new BadRequestException("The one-time token does not exist").setErrorData(oneTimeToken)); + .orElseThrow(() -> new BadRequestException("The one-time token does not exist").setErrorData(oneTimeToken)); // Get request uri String requestUri = request.getRequestURI(); diff --git a/src/main/java/run/halo/app/security/filter/AdminAuthenticationFilter.java b/src/main/java/run/halo/app/security/filter/AdminAuthenticationFilter.java index 97e13eaae..16e7c7994 100644 --- a/src/main/java/run/halo/app/security/filter/AdminAuthenticationFilter.java +++ b/src/main/java/run/halo/app/security/filter/AdminAuthenticationFilter.java @@ -54,7 +54,7 @@ public class AdminAuthenticationFilter extends AbstractAuthenticationFilter { if (!haloProperties.isAuthEnabled()) { // Set security userService.getCurrentUser().ifPresent(user -> - SecurityContextHolder.setContext(new SecurityContextImpl(new AuthenticationImpl(new UserDetail(user))))); + SecurityContextHolder.setContext(new SecurityContextImpl(new AuthenticationImpl(new UserDetail(user))))); // Do filter filterChain.doFilter(request, response); diff --git a/src/main/java/run/halo/app/security/resolver/AuthenticationArgumentResolver.java b/src/main/java/run/halo/app/security/resolver/AuthenticationArgumentResolver.java index 9e266773e..beab076f6 100644 --- a/src/main/java/run/halo/app/security/resolver/AuthenticationArgumentResolver.java +++ b/src/main/java/run/halo/app/security/resolver/AuthenticationArgumentResolver.java @@ -31,9 +31,9 @@ public class AuthenticationArgumentResolver implements HandlerMethodArgumentReso @Override public boolean supportsParameter(MethodParameter parameter) { Class parameterType = parameter.getParameterType(); - return (Authentication.class.isAssignableFrom(parameterType) || - UserDetail.class.isAssignableFrom(parameterType) || - User.class.isAssignableFrom(parameterType)); + return Authentication.class.isAssignableFrom(parameterType) + || UserDetail.class.isAssignableFrom(parameterType) + || User.class.isAssignableFrom(parameterType); } @Override @@ -44,7 +44,7 @@ public class AuthenticationArgumentResolver implements HandlerMethodArgumentReso Class parameterType = parameter.getParameterType(); Authentication authentication = Optional.ofNullable(SecurityContextHolder.getContext().getAuthentication()) - .orElseThrow(() -> new AuthenticationException("You haven't signed in yet")); + .orElseThrow(() -> new AuthenticationException("You haven't signed in yet")); if (Authentication.class.isAssignableFrom(parameterType)) { return authentication; diff --git a/src/main/java/run/halo/app/service/base/BaseCommentService.java b/src/main/java/run/halo/app/service/base/BaseCommentService.java index 070992f0b..9b562cd45 100644 --- a/src/main/java/run/halo/app/service/base/BaseCommentService.java +++ b/src/main/java/run/halo/app/service/base/BaseCommentService.java @@ -89,7 +89,6 @@ public interface BaseCommentService extends CrudSer * * @param postId post id must not be null * @param pageable page info must not be null - * @param status status must not be null * @return a page of comment vo */ @NonNull @@ -153,12 +152,12 @@ public interface BaseCommentService extends CrudSer /** * Creates a comment by comment. * - * @param COMMENT comment must not be null + * @param comment comment must not be null * @return created comment */ @NonNull @Override - COMMENT create(@NonNull COMMENT COMMENT); + COMMENT create(@NonNull COMMENT comment); /** * Creates a comment by comment param. diff --git a/src/main/java/run/halo/app/service/impl/AdminServiceImpl.java b/src/main/java/run/halo/app/service/impl/AdminServiceImpl.java index 81f3bfce5..acd89c396 100644 --- a/src/main/java/run/halo/app/service/impl/AdminServiceImpl.java +++ b/src/main/java/run/halo/app/service/impl/AdminServiceImpl.java @@ -145,7 +145,7 @@ public class AdminServiceImpl implements AdminService { try { // Get user by username or email user = Validator.isEmail(username) ? - userService.getByEmailOfNonNull(username) : userService.getByUsernameOfNonNull(username); + userService.getByEmailOfNonNull(username) : userService.getByUsernameOfNonNull(username); } catch (NotFoundException e) { log.error("Failed to find user by name: " + username, e); eventPublisher.publishEvent(new LogEvent(this, loginParam.getUsername(), LogType.LOGIN_FAILED, loginParam.getUsername())); @@ -311,14 +311,14 @@ public class AdminServiceImpl implements AdminService { Assert.hasText(refreshToken, "Refresh token must not be blank"); Integer userId = cacheStore.getAny(SecurityUtils.buildTokenRefreshKey(refreshToken), Integer.class) - .orElseThrow(() -> new BadRequestException("登录状态已失效,请重新登录").setErrorData(refreshToken)); + .orElseThrow(() -> new BadRequestException("登录状态已失效,请重新登录").setErrorData(refreshToken)); // Get user info User user = userService.getById(userId); // Remove all token cacheStore.getAny(SecurityUtils.buildAccessTokenKey(user), String.class) - .ifPresent(accessToken -> cacheStore.delete(SecurityUtils.buildTokenAccessKey(accessToken))); + .ifPresent(accessToken -> cacheStore.delete(SecurityUtils.buildTokenAccessKey(accessToken))); cacheStore.delete(SecurityUtils.buildTokenRefreshKey(refreshToken)); cacheStore.delete(SecurityUtils.buildAccessTokenKey(user)); cacheStore.delete(SecurityUtils.buildRefreshTokenKey(user)); @@ -333,8 +333,8 @@ public class AdminServiceImpl implements AdminService { ResponseEntity responseEntity = restTemplate.getForEntity(HaloConst.HALO_ADMIN_RELEASES_LATEST, Map.class); if (responseEntity == null || - responseEntity.getStatusCode().isError() || - responseEntity.getBody() == null) { + responseEntity.getStatusCode().isError() || + responseEntity.getBody() == null) { log.debug("Failed to request remote url: [{}]", HALO_ADMIN_RELEASES_LATEST); throw new ServiceException("系统无法访问到 Github 的 API").setErrorData(HALO_ADMIN_RELEASES_LATEST); } @@ -348,17 +348,17 @@ public class AdminServiceImpl implements AdminService { try { List assets = (List) assetsObject; Map assetMap = (Map) assets.stream() - .filter(assetPredicate()) - .findFirst() - .orElseThrow(() -> new ServiceException("Halo admin 最新版暂无资源文件,请稍后再试")); + .filter(assetPredicate()) + .findFirst() + .orElseThrow(() -> new ServiceException("Halo admin 最新版暂无资源文件,请稍后再试")); Object browserDownloadUrl = assetMap.getOrDefault("browser_download_url", ""); // Download the assets ResponseEntity downloadResponseEntity = restTemplate.getForEntity(browserDownloadUrl.toString(), byte[].class); if (downloadResponseEntity == null || - downloadResponseEntity.getStatusCode().isError() || - downloadResponseEntity.getBody() == null) { + downloadResponseEntity.getStatusCode().isError() || + downloadResponseEntity.getBody() == null) { throw new ServiceException("Failed to request remote url: " + browserDownloadUrl.toString()).setErrorData(browserDownloadUrl.toString()); } @@ -371,7 +371,7 @@ public class AdminServiceImpl implements AdminService { // Create temp folder Path assetTempPath = FileUtils.createTempDirectory() - .resolve(assetMap.getOrDefault("name", "halo-admin-latest.zip").toString()); + .resolve(assetMap.getOrDefault("name", "halo-admin-latest.zip").toString()); // Unzip FileUtils.unzip(downloadResponseEntity.getBody(), assetTempPath); @@ -526,7 +526,7 @@ public class AdminServiceImpl implements AdminService { linesArray.forEach(line -> { result.append(line) - .append(StringUtils.LF); + .append(StringUtils.LF); }); return result.toString(); diff --git a/src/main/java/run/halo/app/service/impl/BackupServiceImpl.java b/src/main/java/run/halo/app/service/impl/BackupServiceImpl.java index 4be161a85..e156de369 100644 --- a/src/main/java/run/halo/app/service/impl/BackupServiceImpl.java +++ b/src/main/java/run/halo/app/service/impl/BackupServiceImpl.java @@ -88,9 +88,9 @@ public class BackupServiceImpl implements BackupService { */ public static String sanitizeFilename(final String unSanitized) { return unSanitized. - replaceAll("[^(a-zA-Z0-9\\u4e00-\\u9fa5\\.)]", ""). - replaceAll("[\\?\\\\/:|<>\\*\\[\\]\\(\\)\\$%\\{\\}@~\\.]", ""). - replaceAll("\\s", ""); + replaceAll("[^(a-zA-Z0-9\\u4e00-\\u9fa5\\.)]", ""). + replaceAll("[\\?\\\\/:|<>\\*\\[\\]\\(\\)\\$%\\{\\}@~\\.]", ""). + replaceAll("\\s", ""); } @Override @@ -170,8 +170,8 @@ public class BackupServiceImpl implements BackupService { try { // Create zip path for halo zip String haloZipFileName = HaloConst.HALO_BACKUP_PREFIX + - LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd-HH-mm-ss-")) + - IdUtil.simpleUUID().hashCode() + ".zip"; + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd-HH-mm-ss-")) + + IdUtil.simpleUUID().hashCode() + ".zip"; // Create halo zip file Path haloZipPath = Files.createFile(Paths.get(haloProperties.getBackupDir(), haloZipFileName)); @@ -196,17 +196,17 @@ public class BackupServiceImpl implements BackupService { // Build backup dto try (Stream subPathStream = Files.list(backupParentPath)) { return subPathStream - .filter(backupPath -> StringUtils.startsWithIgnoreCase(backupPath.getFileName().toString(), HaloConst.HALO_BACKUP_PREFIX)) - .map(this::buildBackupDto) - .sorted((leftBackup, rightBackup) -> { - // Sort the result - if (leftBackup.getUpdateTime() < rightBackup.getUpdateTime()) { - return 1; - } else if (leftBackup.getUpdateTime() > rightBackup.getUpdateTime()) { - return -1; - } - return 0; - }).collect(Collectors.toList()); + .filter(backupPath -> StringUtils.startsWithIgnoreCase(backupPath.getFileName().toString(), HaloConst.HALO_BACKUP_PREFIX)) + .map(this::buildBackupDto) + .sorted((leftBackup, rightBackup) -> { + // Sort the result + if (leftBackup.getUpdateTime() < rightBackup.getUpdateTime()) { + return 1; + } else if (leftBackup.getUpdateTime() > rightBackup.getUpdateTime()) { + return -1; + } + return 0; + }).collect(Collectors.toList()); } catch (IOException e) { throw new ServiceException("Failed to fetch backups", e); } @@ -309,9 +309,9 @@ public class BackupServiceImpl implements BackupService { // Build full url return HaloUtils.compositeHttpUrl(optionService.getBlogBaseUrl(), backupUri) - + "?" - + HaloConst.ONE_TIME_TOKEN_QUERY_NAME - + "=" + oneTimeToken; + + "?" + + HaloConst.ONE_TIME_TOKEN_QUERY_NAME + + "=" + oneTimeToken; } } diff --git a/src/main/java/run/halo/app/service/impl/BaseCommentServiceImpl.java b/src/main/java/run/halo/app/service/impl/BaseCommentServiceImpl.java index de6193c28..b3df5e2a9 100644 --- a/src/main/java/run/halo/app/service/impl/BaseCommentServiceImpl.java +++ b/src/main/java/run/halo/app/service/impl/BaseCommentServiceImpl.java @@ -397,8 +397,8 @@ public abstract class BaseCommentServiceImpl extend return Collections.emptyList(); } return comments.stream() - .map(this::convertTo) - .collect(Collectors.toList()); + .map(this::convertTo) + .collect(Collectors.toList()); } @Override @@ -454,9 +454,9 @@ public abstract class BaseCommentServiceImpl extend // Get sort order Sort.Order order = sort.filter(anOrder -> "id".equals(anOrder.getProperty())) - .get() - .findFirst() - .orElseGet(() -> Sort.Order.desc("id")); + .get() + .findFirst() + .orElseGet(() -> Sort.Order.desc("id")); // Init sign int sign = order.getDirection().isAscending() ? 1 : -1; @@ -696,8 +696,8 @@ public abstract class BaseCommentServiceImpl extend // Get children List children = comments.stream() - .filter(comment -> Objects.equals(parentComment.getId(), comment.getParentId())) - .collect(Collectors.toList()); + .filter(comment -> Objects.equals(parentComment.getId(), comment.getParentId())) + .collect(Collectors.toList()); // Add children children.forEach(comment -> { diff --git a/src/main/java/run/halo/app/service/impl/BaseMetaServiceImpl.java b/src/main/java/run/halo/app/service/impl/BaseMetaServiceImpl.java index a82a67390..5031f2156 100644 --- a/src/main/java/run/halo/app/service/impl/BaseMetaServiceImpl.java +++ b/src/main/java/run/halo/app/service/impl/BaseMetaServiceImpl.java @@ -80,7 +80,7 @@ public abstract class BaseMetaServiceImpl extends Abstrac // Foreach and collect postMetas.forEach(postMeta -> postMetaListMap.computeIfAbsent(postMeta.getPostId(), postId -> new LinkedList<>()) - .add(postMetaMap.get(postMeta.getId()))); + .add(postMetaMap.get(postMeta.getId()))); return postMetaListMap; } @@ -130,7 +130,7 @@ public abstract class BaseMetaServiceImpl extends Abstrac } return postMetaList.stream() - .map(this::convertTo) - .collect(Collectors.toList()); + .map(this::convertTo) + .collect(Collectors.toList()); } } diff --git a/src/main/java/run/halo/app/service/impl/BasePostServiceImpl.java b/src/main/java/run/halo/app/service/impl/BasePostServiceImpl.java index a9030af63..e692436a0 100644 --- a/src/main/java/run/halo/app/service/impl/BasePostServiceImpl.java +++ b/src/main/java/run/halo/app/service/impl/BasePostServiceImpl.java @@ -51,7 +51,7 @@ public abstract class BasePostServiceImpl extends Abstrac private final OptionService optionService; - private final Pattern SUMMARY_PATTERN = Pattern.compile("\\s*|\t|\r|\n"); + private final Pattern summaryPattern = Pattern.compile("\\s*|\t|\r|\n"); public BasePostServiceImpl(BasePostRepository basePostRepository, OptionService optionService) { @@ -117,9 +117,9 @@ public abstract class BasePostServiceImpl extends Abstrac Assert.notNull(date, "Date must not be null"); return basePostRepository.findAllByStatusAndCreateTimeAfter(PostStatus.PUBLISHED, - date, - PageRequest.of(0, size, Sort.by(ASC, "createTime"))) - .getContent(); + date, + PageRequest.of(0, size, Sort.by(ASC, "createTime"))) + .getContent(); } @Override @@ -127,9 +127,9 @@ public abstract class BasePostServiceImpl extends Abstrac Assert.notNull(date, "Date must not be null"); return basePostRepository.findAllByStatusAndCreateTimeBefore(PostStatus.PUBLISHED, - date, - PageRequest.of(0, size, Sort.by(DESC, "createTime"))) - .getContent(); + date, + PageRequest.of(0, size, Sort.by(DESC, "createTime"))) + .getContent(); } @Override @@ -282,8 +282,8 @@ public abstract class BasePostServiceImpl extends Abstrac } return posts.stream() - .map(this::convertToMinimal) - .collect(Collectors.toList()); + .map(this::convertToMinimal) + .collect(Collectors.toList()); } @Override @@ -314,8 +314,8 @@ public abstract class BasePostServiceImpl extends Abstrac } return posts.stream() - .map(this::convertToSimple) - .collect(Collectors.toList()); + .map(this::convertToSimple) + .collect(Collectors.toList()); } @Override @@ -468,7 +468,7 @@ public abstract class BasePostServiceImpl extends Abstrac String text = HaloUtils.cleanHtmlTag(htmlContent); - Matcher matcher = SUMMARY_PATTERN.matcher(text); + Matcher matcher = summaryPattern.matcher(text); text = matcher.replaceAll(""); // Get summary length diff --git a/src/main/java/run/halo/app/service/impl/CategoryServiceImpl.java b/src/main/java/run/halo/app/service/impl/CategoryServiceImpl.java index a4c5040ef..0309bab53 100644 --- a/src/main/java/run/halo/app/service/impl/CategoryServiceImpl.java +++ b/src/main/java/run/halo/app/service/impl/CategoryServiceImpl.java @@ -113,8 +113,8 @@ public class CategoryServiceImpl extends AbstractCrudService // Get children for removing after List children = categories.stream() - .filter(category -> Objects.equal(parentCategory.getId(), category.getParentId())) - .collect(Collectors.toList()); + .filter(category -> Objects.equal(parentCategory.getId(), category.getParentId())) + .collect(Collectors.toList()); children.forEach(category -> { // Convert to child category vo @@ -219,7 +219,7 @@ public class CategoryServiceImpl extends AbstractCrudService } return categories.stream() - .map(this::convertTo) - .collect(Collectors.toList()); + .map(this::convertTo) + .collect(Collectors.toList()); } } diff --git a/src/main/java/run/halo/app/service/impl/CommentBlackListServiceImpl.java b/src/main/java/run/halo/app/service/impl/CommentBlackListServiceImpl.java index 51b6c6ac0..f01979412 100644 --- a/src/main/java/run/halo/app/service/impl/CommentBlackListServiceImpl.java +++ b/src/main/java/run/halo/app/service/impl/CommentBlackListServiceImpl.java @@ -26,7 +26,7 @@ import java.util.Optional; @Service @Slf4j public class CommentBlackListServiceImpl extends AbstractCrudService implements CommentBlackListService { - private static ZoneId zoneId = ZoneId.of("Asia/Shanghai"); + private static final ZoneId ZONE_ID = ZoneId.of("Asia/Shanghai"); private final CommentBlackListRepository commentBlackListRepository; private final PostCommentRepository postCommentRepository; private final OptionService optionService; @@ -50,10 +50,10 @@ public class CommentBlackListServiceImpl extends AbstractCrudService blackList = commentBlackListRepository.findByIpAddress(ipAddress); LocalDateTime now = LocalDateTime.now(); - Date endTime = new Date(now.atZone(zoneId).toInstant().toEpochMilli()); + Date endTime = new Date(now.atZone(ZONE_ID).toInstant().toEpochMilli()); Integer banTime = optionService.getByPropertyOrDefault(CommentProperties.COMMENT_BAN_TIME, Integer.class, 10); Date startTime = new Date(now.minusMinutes(banTime) - .atZone(zoneId).toInstant().toEpochMilli()); + .atZone(ZONE_ID).toInstant().toEpochMilli()); Integer range = optionService.getByPropertyOrDefault(CommentProperties.COMMENT_RANGE, Integer.class, 30); boolean isPresent = postCommentRepository.countByIpAndTime(ipAddress, startTime, endTime) >= range; if (isPresent && blackList.isPresent()) { @@ -61,10 +61,10 @@ public class CommentBlackListServiceImpl extends AbstractCrudService result <= 0).ifPresent(result -> log.error("更新评论封禁时间失败")); + .filter(result -> result <= 0).ifPresent(result -> log.error("更新评论封禁时间失败")); } private Date getBanTime(LocalDateTime localDateTime, Integer banTime) { - return new Date(localDateTime.plusMinutes(banTime).atZone(zoneId).toInstant().toEpochMilli()); + return new Date(localDateTime.plusMinutes(banTime).atZone(ZONE_ID).toInstant().toEpochMilli()); } } diff --git a/src/main/java/run/halo/app/service/impl/JournalCommentServiceImpl.java b/src/main/java/run/halo/app/service/impl/JournalCommentServiceImpl.java index c3ba32348..6004b573e 100644 --- a/src/main/java/run/halo/app/service/impl/JournalCommentServiceImpl.java +++ b/src/main/java/run/halo/app/service/impl/JournalCommentServiceImpl.java @@ -68,13 +68,13 @@ public class JournalCommentServiceImpl extends BaseCommentServiceImpl journalMap = ServiceUtils.convertToMap(journals, Journal::getId); return journalComments.stream() - .filter(journalComment -> journalMap.containsKey(journalComment.getPostId())) - .map(journalComment -> { - JournalCommentWithJournalVO journalCmtWithJournalVo = new JournalCommentWithJournalVO().convertFrom(journalComment); - journalCmtWithJournalVo.setJournal(new JournalDTO().convertFrom(journalMap.get(journalComment.getPostId()))); - return journalCmtWithJournalVo; - }) - .collect(Collectors.toList()); + .filter(journalComment -> journalMap.containsKey(journalComment.getPostId())) + .map(journalComment -> { + JournalCommentWithJournalVO journalCmtWithJournalVo = new JournalCommentWithJournalVO().convertFrom(journalComment); + journalCmtWithJournalVo.setJournal(new JournalDTO().convertFrom(journalMap.get(journalComment.getPostId()))); + return journalCmtWithJournalVo; + }) + .collect(Collectors.toList()); } @Override diff --git a/src/main/java/run/halo/app/service/impl/JournalServiceImpl.java b/src/main/java/run/halo/app/service/impl/JournalServiceImpl.java index d170fd283..caa5ab020 100644 --- a/src/main/java/run/halo/app/service/impl/JournalServiceImpl.java +++ b/src/main/java/run/halo/app/service/impl/JournalServiceImpl.java @@ -119,13 +119,13 @@ public class JournalServiceImpl extends AbstractCrudService im Map journalCommentCountMap = journalCommentService.countByPostIds(journalIds); return journals.stream() - .map(journal -> { - JournalWithCmtCountDTO journalWithCmtCountDTO = new JournalWithCmtCountDTO().convertFrom(journal); - // Set comment count - journalWithCmtCountDTO.setCommentCount(journalCommentCountMap.getOrDefault(journal.getId(), 0L)); - return journalWithCmtCountDTO; - }) - .collect(Collectors.toList()); + .map(journal -> { + JournalWithCmtCountDTO journalWithCmtCountDTO = new JournalWithCmtCountDTO().convertFrom(journal); + // Set comment count + journalWithCmtCountDTO.setCommentCount(journalCommentCountMap.getOrDefault(journal.getId(), 0L)); + return journalWithCmtCountDTO; + }) + .collect(Collectors.toList()); } @Override diff --git a/src/main/java/run/halo/app/service/impl/LinkServiceImpl.java b/src/main/java/run/halo/app/service/impl/LinkServiceImpl.java index 94893c81a..5fb3d60e6 100644 --- a/src/main/java/run/halo/app/service/impl/LinkServiceImpl.java +++ b/src/main/java/run/halo/app/service/impl/LinkServiceImpl.java @@ -136,6 +136,6 @@ public class LinkServiceImpl extends AbstractCrudService implemen } return links.stream().map(link -> (LinkDTO) new LinkDTO().convertFrom(link)) - .collect(Collectors.toList()); + .collect(Collectors.toList()); } } diff --git a/src/main/java/run/halo/app/service/impl/MenuServiceImpl.java b/src/main/java/run/halo/app/service/impl/MenuServiceImpl.java index 644cf2a89..611054468 100644 --- a/src/main/java/run/halo/app/service/impl/MenuServiceImpl.java +++ b/src/main/java/run/halo/app/service/impl/MenuServiceImpl.java @@ -211,8 +211,8 @@ public class MenuServiceImpl extends AbstractCrudService implemen } return menus.stream() - .map(menu -> (MenuDTO) new MenuDTO().convertFrom(menu)) - .collect(Collectors.toList()); + .map(menu -> (MenuDTO) new MenuDTO().convertFrom(menu)) + .collect(Collectors.toList()); } private void nameMustNotExist(@NonNull Menu menu) { diff --git a/src/main/java/run/halo/app/service/impl/OptionServiceImpl.java b/src/main/java/run/halo/app/service/impl/OptionServiceImpl.java index 2ade3bb0b..d948bf76f 100644 --- a/src/main/java/run/halo/app/service/impl/OptionServiceImpl.java +++ b/src/main/java/run/halo/app/service/impl/OptionServiceImpl.java @@ -192,17 +192,17 @@ public class OptionServiceImpl extends AbstractCrudService impl // Add default property propertyEnumMap.keySet() - .stream() - .filter(key -> !keys.contains(key)) - .forEach(key -> { - PropertyEnum propertyEnum = propertyEnumMap.get(key); + .stream() + .filter(key -> !keys.contains(key)) + .forEach(key -> { + PropertyEnum propertyEnum = propertyEnumMap.get(key); - if (StringUtils.isBlank(propertyEnum.defaultValue())) { - return; - } + if (StringUtils.isBlank(propertyEnum.defaultValue())) { + return; + } - result.put(key, PropertyEnum.convertTo(propertyEnum.defaultValue(), propertyEnum)); - }); + result.put(key, PropertyEnum.convertTo(propertyEnum.defaultValue(), propertyEnum)); + }); // Cache the result cacheStore.putAny(OPTIONS_KEY, result); @@ -222,8 +222,8 @@ public class OptionServiceImpl extends AbstractCrudService impl Map result = new HashMap<>(keys.size()); keys.stream() - .filter(optionMap::containsKey) - .forEach(key -> result.put(key, optionMap.get(key))); + .filter(optionMap::containsKey) + .forEach(key -> result.put(key, optionMap.get(key))); return result; } diff --git a/src/main/java/run/halo/app/service/impl/PostCategoryServiceImpl.java b/src/main/java/run/halo/app/service/impl/PostCategoryServiceImpl.java index 487f56d8e..27cee3095 100644 --- a/src/main/java/run/halo/app/service/impl/PostCategoryServiceImpl.java +++ b/src/main/java/run/halo/app/service/impl/PostCategoryServiceImpl.java @@ -87,7 +87,7 @@ public class PostCategoryServiceImpl extends AbstractCrudService categoryListMap.computeIfAbsent(postCategory.getPostId(), postId -> new LinkedList<>()) - .add(categoryMap.get(postCategory.getCategoryId()))); + .add(categoryMap.get(postCategory.getCategoryId()))); return categoryListMap; } @@ -241,28 +241,28 @@ public class PostCategoryServiceImpl extends AbstractCrudService { - // Create category post count dto - CategoryWithPostCountDTO categoryWithPostCountDTO = new CategoryWithPostCountDTO().convertFrom(category); - // Set post count - categoryWithPostCountDTO.setPostCount(categoryPostCountMap.getOrDefault(category.getId(), 0L)); + .map(category -> { + // Create category post count dto + CategoryWithPostCountDTO categoryWithPostCountDTO = new CategoryWithPostCountDTO().convertFrom(category); + // Set post count + categoryWithPostCountDTO.setPostCount(categoryPostCountMap.getOrDefault(category.getId(), 0L)); - StringBuilder fullPath = new StringBuilder(); + StringBuilder fullPath = new StringBuilder(); - if (optionService.isEnabledAbsolutePath()) { - fullPath.append(optionService.getBlogBaseUrl()); - } + if (optionService.isEnabledAbsolutePath()) { + fullPath.append(optionService.getBlogBaseUrl()); + } - fullPath.append("/") - .append(optionService.getCategoriesPrefix()) - .append("/") - .append(category.getSlugName()) - .append(optionService.getPathSuffix()); + fullPath.append("/") + .append(optionService.getCategoriesPrefix()) + .append("/") + .append(category.getSlugName()) + .append(optionService.getPathSuffix()); - categoryWithPostCountDTO.setFullPath(fullPath.toString()); + categoryWithPostCountDTO.setFullPath(fullPath.toString()); - return categoryWithPostCountDTO; - }) - .collect(Collectors.toList()); + return categoryWithPostCountDTO; + }) + .collect(Collectors.toList()); } } diff --git a/src/main/java/run/halo/app/service/impl/PostCommentServiceImpl.java b/src/main/java/run/halo/app/service/impl/PostCommentServiceImpl.java index d2351fdf0..f8b15d316 100644 --- a/src/main/java/run/halo/app/service/impl/PostCommentServiceImpl.java +++ b/src/main/java/run/halo/app/service/impl/PostCommentServiceImpl.java @@ -91,17 +91,17 @@ public class PostCommentServiceImpl extends BaseCommentServiceImpl Map postMap = ServiceUtils.convertToMap(postRepository.findAllById(postIds), Post::getId); return postComments.stream() - .filter(comment -> postMap.containsKey(comment.getPostId())) - .map(comment -> { - // Convert to vo - PostCommentWithPostVO postCommentWithPostVO = new PostCommentWithPostVO().convertFrom(comment); + .filter(comment -> postMap.containsKey(comment.getPostId())) + .map(comment -> { + // Convert to vo + PostCommentWithPostVO postCommentWithPostVO = new PostCommentWithPostVO().convertFrom(comment); - BasePostMinimalDTO basePostMinimalDTO = new BasePostMinimalDTO().convertFrom(postMap.get(comment.getPostId())); + BasePostMinimalDTO basePostMinimalDTO = new BasePostMinimalDTO().convertFrom(postMap.get(comment.getPostId())); - postCommentWithPostVO.setPost(buildPostFullPath(basePostMinimalDTO)); + postCommentWithPostVO.setPost(buildPostFullPath(basePostMinimalDTO)); - return postCommentWithPostVO; - }).collect(Collectors.toList()); + return postCommentWithPostVO; + }).collect(Collectors.toList()); } private BasePostMinimalDTO buildPostFullPath(BasePostMinimalDTO basePostMinimalDTO) { @@ -121,28 +121,28 @@ public class PostCommentServiceImpl extends BaseCommentServiceImpl if (permalinkType.equals(PostPermalinkType.DEFAULT)) { fullPath.append(archivesPrefix) - .append("/") - .append(basePostMinimalDTO.getUrl()) - .append(pathSuffix); + .append("/") + .append(basePostMinimalDTO.getUrl()) + .append(pathSuffix); } else if (permalinkType.equals(PostPermalinkType.ID)) { fullPath.append("?p=") - .append(basePostMinimalDTO.getId()); + .append(basePostMinimalDTO.getId()); } else if (permalinkType.equals(PostPermalinkType.DATE)) { fullPath.append(DateUtil.year(basePostMinimalDTO.getCreateTime())) - .append("/") - .append(DateUtil.month(basePostMinimalDTO.getCreateTime()) + 1) - .append("/") - .append(basePostMinimalDTO.getUrl()) - .append(pathSuffix); + .append("/") + .append(DateUtil.month(basePostMinimalDTO.getCreateTime()) + 1) + .append("/") + .append(basePostMinimalDTO.getUrl()) + .append(pathSuffix); } else if (permalinkType.equals(PostPermalinkType.DAY)) { fullPath.append(DateUtil.year(basePostMinimalDTO.getCreateTime())) - .append("/") - .append(DateUtil.month(basePostMinimalDTO.getCreateTime()) + 1) - .append("/") - .append(DateUtil.dayOfMonth(basePostMinimalDTO.getCreateTime())) - .append("/") - .append(basePostMinimalDTO.getUrl()) - .append(pathSuffix); + .append("/") + .append(DateUtil.month(basePostMinimalDTO.getCreateTime()) + 1) + .append("/") + .append(DateUtil.dayOfMonth(basePostMinimalDTO.getCreateTime())) + .append("/") + .append(basePostMinimalDTO.getUrl()) + .append(pathSuffix); } basePostMinimalDTO.setFullPath(fullPath.toString()); @@ -153,7 +153,7 @@ public class PostCommentServiceImpl extends BaseCommentServiceImpl @Override public void validateTarget(Integer postId) { Post post = postRepository.findById(postId) - .orElseThrow(() -> new NotFoundException("查询不到该文章的信息").setErrorData(postId)); + .orElseThrow(() -> new NotFoundException("查询不到该文章的信息").setErrorData(postId)); if (post.getDisallowComment()) { throw new BadRequestException("该文章已经被禁止评论").setErrorData(postId); diff --git a/src/main/java/run/halo/app/service/impl/PostMetaServiceImpl.java b/src/main/java/run/halo/app/service/impl/PostMetaServiceImpl.java index ab5bd0480..49ef11c88 100644 --- a/src/main/java/run/halo/app/service/impl/PostMetaServiceImpl.java +++ b/src/main/java/run/halo/app/service/impl/PostMetaServiceImpl.java @@ -30,6 +30,6 @@ public class PostMetaServiceImpl extends BaseMetaServiceImpl implement @Override public void validateTarget(Integer postId) { postRepository.findById(postId) - .orElseThrow(() -> new NotFoundException("查询不到该文章的信息").setErrorData(postId)); + .orElseThrow(() -> new NotFoundException("查询不到该文章的信息").setErrorData(postId)); } } diff --git a/src/main/java/run/halo/app/service/impl/PostServiceImpl.java b/src/main/java/run/halo/app/service/impl/PostServiceImpl.java index 54c95eeb5..3239d2d8c 100644 --- a/src/main/java/run/halo/app/service/impl/PostServiceImpl.java +++ b/src/main/java/run/halo/app/service/impl/PostServiceImpl.java @@ -87,8 +87,7 @@ public class PostServiceImpl extends BasePostServiceImpl implements PostSe PostCategoryService postCategoryService, PostCommentService postCommentService, ApplicationEventPublisher eventPublisher, - PostMetaService postMetaService, - OptionService optionService1) { + PostMetaService postMetaService) { super(basePostRepository, optionService); this.postRepository = postRepository; this.tagService = tagService; @@ -98,7 +97,7 @@ public class PostServiceImpl extends BasePostServiceImpl implements PostSe this.postCommentService = postCommentService; this.eventPublisher = eventPublisher; this.postMetaService = postMetaService; - this.optionService = optionService1; + this.optionService = optionService; } @Override @@ -131,7 +130,7 @@ public class PostServiceImpl extends BasePostServiceImpl implements PostSe if (!autoSave) { // Log the creation LogEvent logEvent = new LogEvent(this, createdPost.getId().toString(), - LogType.POST_PUBLISHED, createdPost.getTitle()); + LogType.POST_PUBLISHED, createdPost.getTitle()); eventPublisher.publishEvent(logEvent); } return createdPost; @@ -144,7 +143,7 @@ public class PostServiceImpl extends BasePostServiceImpl implements PostSe if (!autoSave) { // Log the creation LogEvent logEvent = new LogEvent(this, createdPost.getId().toString(), - LogType.POST_PUBLISHED, createdPost.getTitle()); + LogType.POST_PUBLISHED, createdPost.getTitle()); eventPublisher.publishEvent(logEvent); } return createdPost; @@ -160,7 +159,7 @@ public class PostServiceImpl extends BasePostServiceImpl implements PostSe if (!autoSave) { // Log the creation LogEvent logEvent = new LogEvent(this, updatedPost.getId().toString(), - LogType.POST_EDITED, updatedPost.getTitle()); + LogType.POST_EDITED, updatedPost.getTitle()); eventPublisher.publishEvent(logEvent); } return updatedPost; @@ -180,7 +179,7 @@ public class PostServiceImpl extends BasePostServiceImpl implements PostSe Optional postOptional = postRepository.findBy(year, month, url); return postOptional - .orElseThrow(() -> new NotFoundException("查询不到该文章的信息").setErrorData(url)); + .orElseThrow(() -> new NotFoundException("查询不到该文章的信息").setErrorData(url)); } @Override @@ -193,7 +192,7 @@ public class PostServiceImpl extends BasePostServiceImpl implements PostSe Optional postOptional = postRepository.findBy(year, month, url, status); return postOptional - .orElseThrow(() -> new NotFoundException("查询不到该文章的信息").setErrorData(url)); + .orElseThrow(() -> new NotFoundException("查询不到该文章的信息").setErrorData(url)); } @Override @@ -206,7 +205,7 @@ public class PostServiceImpl extends BasePostServiceImpl implements PostSe Optional postOptional = postRepository.findBy(year, month, day, url); return postOptional - .orElseThrow(() -> new NotFoundException("查询不到该文章的信息").setErrorData(url)); + .orElseThrow(() -> new NotFoundException("查询不到该文章的信息").setErrorData(url)); } @Override @@ -220,7 +219,7 @@ public class PostServiceImpl extends BasePostServiceImpl implements PostSe Optional postOptional = postRepository.findBy(year, month, day, url, status); return postOptional - .orElseThrow(() -> new NotFoundException("查询不到该文章的信息").setErrorData(url)); + .orElseThrow(() -> new NotFoundException("查询不到该文章的信息").setErrorData(url)); } @Override @@ -240,14 +239,14 @@ public class PostServiceImpl extends BasePostServiceImpl implements PostSe public List listYearArchives() { // Get all posts List posts = postRepository - .findAllByStatus(PostStatus.PUBLISHED, Sort.by(DESC, "createTime")); + .findAllByStatus(PostStatus.PUBLISHED, Sort.by(DESC, "createTime")); Map> yearPostMap = new HashMap<>(8); posts.forEach(post -> { Calendar calendar = DateUtils.convertTo(post.getCreateTime()); yearPostMap.computeIfAbsent(calendar.get(Calendar.YEAR), year -> new LinkedList<>()) - .add(post); + .add(post); }); List archives = new LinkedList<>(); @@ -272,7 +271,7 @@ public class PostServiceImpl extends BasePostServiceImpl implements PostSe public List listMonthArchives() { // Get all posts List posts = postRepository - .findAllByStatus(PostStatus.PUBLISHED, Sort.by(DESC, "createTime")); + .findAllByStatus(PostStatus.PUBLISHED, Sort.by(DESC, "createTime")); Map>> yearMonthPostMap = new HashMap<>(8); @@ -280,22 +279,22 @@ public class PostServiceImpl extends BasePostServiceImpl implements PostSe Calendar calendar = DateUtils.convertTo(post.getCreateTime()); yearMonthPostMap.computeIfAbsent(calendar.get(Calendar.YEAR), year -> new HashMap<>()) - .computeIfAbsent((calendar.get(Calendar.MONTH) + 1), - month -> new LinkedList<>()) - .add(post); + .computeIfAbsent(calendar.get(Calendar.MONTH) + 1, + month -> new LinkedList<>()) + .add(post); }); List archives = new LinkedList<>(); yearMonthPostMap.forEach((year, monthPostMap) -> - monthPostMap.forEach((month, postList) -> { - ArchiveMonthVO archive = new ArchiveMonthVO(); - archive.setYear(year); - archive.setMonth(month); - archive.setPosts(convertToMinimal(postList)); + monthPostMap.forEach((month, postList) -> { + ArchiveMonthVO archive = new ArchiveMonthVO(); + archive.setYear(year); + archive.setMonth(month); + archive.setPosts(convertToMinimal(postList)); - archives.add(archive); - })); + archives.add(archive); + })); // Sort this list archives.sort(new ArchiveMonthVO.ArchiveComparator()); @@ -435,7 +434,7 @@ public class PostServiceImpl extends BasePostServiceImpl implements PostSe content.append("postMetas:").append("\n"); for (PostMeta postMeta : postMetas) { content.append(" - ").append(postMeta.getKey()).append(" : ") - .append(postMeta.getValue()).append("\n"); + .append(postMeta.getValue()).append("\n"); } } @@ -484,7 +483,7 @@ public class PostServiceImpl extends BasePostServiceImpl implements PostSe // Log it eventPublisher.publishEvent(new LogEvent(this, postId.toString(), LogType.POST_DELETED, - deletedPost.getTitle())); + deletedPost.getTitle())); return deletedPost; } @@ -502,7 +501,7 @@ public class PostServiceImpl extends BasePostServiceImpl implements PostSe // Get category list map Map> categoryListMap = postCategoryService - .listCategoryListMap(postIds); + .listCategoryListMap(postIds); // Get comment count Map commentCountMap = postCommentService.countByPostIds(postIds); @@ -521,27 +520,27 @@ public class PostServiceImpl extends BasePostServiceImpl implements PostSe // Set tags postListVO.setTags(Optional.ofNullable(tagListMap.get(post.getId())) - .orElseGet(LinkedList::new) - .stream() - .filter(Objects::nonNull) - .map(tagService::convertTo) - .collect(Collectors.toList())); + .orElseGet(LinkedList::new) + .stream() + .filter(Objects::nonNull) + .map(tagService::convertTo) + .collect(Collectors.toList())); // Set categories postListVO.setCategories(Optional.ofNullable(categoryListMap.get(post.getId())) - .orElseGet(LinkedList::new) - .stream() - .filter(Objects::nonNull) - .map(categoryService::convertTo) - .collect(Collectors.toList())); + .orElseGet(LinkedList::new) + .stream() + .filter(Objects::nonNull) + .map(categoryService::convertTo) + .collect(Collectors.toList())); // Set post metas postListVO.setPostMetas(Optional.ofNullable(postMetaListMap.get(post.getId())) - .orElseGet(LinkedList::new) - .stream() - .filter(Objects::nonNull) - .map(postMeta -> (BaseMetaDTO) new BaseMetaDTO().convertFrom(postMeta)) - .collect(Collectors.toList())); + .orElseGet(LinkedList::new) + .stream() + .filter(Objects::nonNull) + .map(postMeta -> (BaseMetaDTO) new BaseMetaDTO().convertFrom(postMeta)) + .collect(Collectors.toList())); // Set comment count postListVO.setCommentCount(commentCountMap.getOrDefault(post.getId(), 0L)); @@ -563,7 +562,7 @@ public class PostServiceImpl extends BasePostServiceImpl implements PostSe // Get category list map Map> categoryListMap = postCategoryService - .listCategoryListMap(postIds); + .listCategoryListMap(postIds); // Get comment count Map commentCountMap = postCommentService.countByPostIds(postIds); @@ -582,27 +581,27 @@ public class PostServiceImpl extends BasePostServiceImpl implements PostSe // Set tags postListVO.setTags(Optional.ofNullable(tagListMap.get(post.getId())) - .orElseGet(LinkedList::new) - .stream() - .filter(Objects::nonNull) - .map(tagService::convertTo) - .collect(Collectors.toList())); + .orElseGet(LinkedList::new) + .stream() + .filter(Objects::nonNull) + .map(tagService::convertTo) + .collect(Collectors.toList())); // Set categories postListVO.setCategories(Optional.ofNullable(categoryListMap.get(post.getId())) - .orElseGet(LinkedList::new) - .stream() - .filter(Objects::nonNull) - .map(categoryService::convertTo) - .collect(Collectors.toList())); + .orElseGet(LinkedList::new) + .stream() + .filter(Objects::nonNull) + .map(categoryService::convertTo) + .collect(Collectors.toList())); // Set post metas postListVO.setPostMetas(Optional.ofNullable(postMetaListMap.get(post.getId())) - .orElseGet(LinkedList::new) - .stream() - .filter(Objects::nonNull) - .map(postMeta -> (BaseMetaDTO) new BaseMetaDTO().convertFrom(postMeta)) - .collect(Collectors.toList())); + .orElseGet(LinkedList::new) + .stream() + .filter(Objects::nonNull) + .map(postMeta -> (BaseMetaDTO) new BaseMetaDTO().convertFrom(postMeta)) + .collect(Collectors.toList())); // Set comment count postListVO.setCommentCount(commentCountMap.getOrDefault(post.getId(), 0L)); @@ -636,8 +635,8 @@ public class PostServiceImpl extends BasePostServiceImpl implements PostSe } return posts.stream() - .map(this::convertToMinimal) - .collect(Collectors.toList()); + .map(this::convertToMinimal) + .collect(Collectors.toList()); } @Override @@ -723,21 +722,21 @@ public class PostServiceImpl extends BasePostServiceImpl implements PostSe Root postCategoryRoot = postSubquery.from(PostCategory.class); postSubquery.select(postCategoryRoot.get("postId")); postSubquery.where( - criteriaBuilder.equal(root.get("id"), postCategoryRoot.get("postId")), - criteriaBuilder.equal(postCategoryRoot.get("categoryId"), - postQuery.getCategoryId())); + criteriaBuilder.equal(root.get("id"), postCategoryRoot.get("postId")), + criteriaBuilder.equal(postCategoryRoot.get("categoryId"), + postQuery.getCategoryId())); predicates.add(criteriaBuilder.exists(postSubquery)); } if (postQuery.getKeyword() != null) { // Format like condition String likeCondition = String - .format("%%%s%%", StringUtils.strip(postQuery.getKeyword())); + .format("%%%s%%", StringUtils.strip(postQuery.getKeyword())); // Build like predicate Predicate titleLike = criteriaBuilder.like(root.get("title"), likeCondition); Predicate originalContentLike = criteriaBuilder - .like(root.get("originalContent"), likeCondition); + .like(root.get("originalContent"), likeCondition); predicates.add(criteriaBuilder.or(titleLike, originalContentLike)); } @@ -765,20 +764,20 @@ public class PostServiceImpl extends BasePostServiceImpl implements PostSe // Create post tags List postTags = postTagService.mergeOrCreateByIfAbsent(post.getId(), - ServiceUtils.fetchProperty(tags, Tag::getId)); + ServiceUtils.fetchProperty(tags, Tag::getId)); log.debug("Created post tags: [{}]", postTags); // Create post categories List postCategories = postCategoryService - .mergeOrCreateByIfAbsent(post.getId(), - ServiceUtils.fetchProperty(categories, Category::getId)); + .mergeOrCreateByIfAbsent(post.getId(), + ServiceUtils.fetchProperty(categories, Category::getId)); log.debug("Created post categories: [{}]", postCategories); // Create post meta data List postMetaList = postMetaService - .createOrUpdateByPostId(post.getId(), postMetas); + .createOrUpdateByPostId(post.getId(), postMetas); log.debug("Created post postMetas: [{}]", postMetaList); // Convert to post detail vo @@ -809,7 +808,7 @@ public class PostServiceImpl extends BasePostServiceImpl implements PostSe while (needNext && totalCount > postList.size()) { pageable = PageRequest - .of(page >= 1 ? page - 1 : page, defaultPageSize, sort); + .of(page >= 1 ? page - 1 : page, defaultPageSize, sort); Page postPage = pageBy(postStatus, pageable); List pageablePostList = postPage.getContent(); @@ -818,8 +817,8 @@ public class PostServiceImpl extends BasePostServiceImpl implements PostSe } postList.addAll(postPage.getContent()); if (postList.stream().filter(it -> it.getId().equals(currentPost.getId())).count() == 1 - && !postList.stream().reduce((first, second) -> second).get().getId() - .equals(currentPost.getId())) { + && !postList.stream().reduce((first, second) -> second).get().getId() + .equals(currentPost.getId())) { // contains the post && the post is not in the end needNext = false; } @@ -858,7 +857,7 @@ public class PostServiceImpl extends BasePostServiceImpl implements PostSe @Override public @NotNull Sort getPostDefaultSort() { String indexSort = optionService.getByPropertyOfNonNull(PostProperties.INDEX_SORT) - .toString(); + .toString(); return Sort.by(DESC, "topPriority").and(Sort.by(DESC, indexSort)).and(Sort.by(DESC, "id")); } @@ -880,28 +879,28 @@ public class PostServiceImpl extends BasePostServiceImpl implements PostSe if (permalinkType.equals(PostPermalinkType.DEFAULT)) { fullPath.append(archivesPrefix) - .append("/") - .append(post.getUrl()) - .append(pathSuffix); + .append("/") + .append(post.getUrl()) + .append(pathSuffix); } else if (permalinkType.equals(PostPermalinkType.ID)) { fullPath.append("?p=") - .append(post.getId()); + .append(post.getId()); } else if (permalinkType.equals(PostPermalinkType.DATE)) { fullPath.append(DateUtil.year(post.getCreateTime())) - .append("/") - .append(DateUtil.month(post.getCreateTime()) + 1) - .append("/") - .append(post.getUrl()) - .append(pathSuffix); + .append("/") + .append(DateUtil.month(post.getCreateTime()) + 1) + .append("/") + .append(post.getUrl()) + .append(pathSuffix); } else if (permalinkType.equals(PostPermalinkType.DAY)) { fullPath.append(DateUtil.year(post.getCreateTime())) - .append("/") - .append(DateUtil.month(post.getCreateTime()) + 1) - .append("/") - .append(DateUtil.dayOfMonth(post.getCreateTime())) - .append("/") - .append(post.getUrl()) - .append(pathSuffix); + .append("/") + .append(DateUtil.month(post.getCreateTime()) + 1) + .append("/") + .append(DateUtil.dayOfMonth(post.getCreateTime())) + .append("/") + .append(post.getUrl()) + .append(pathSuffix); } return fullPath.toString(); } diff --git a/src/main/java/run/halo/app/service/impl/PostTagServiceImpl.java b/src/main/java/run/halo/app/service/impl/PostTagServiceImpl.java index 62611e0f5..3befba87e 100644 --- a/src/main/java/run/halo/app/service/impl/PostTagServiceImpl.java +++ b/src/main/java/run/halo/app/service/impl/PostTagServiceImpl.java @@ -75,26 +75,26 @@ public class PostTagServiceImpl extends AbstractCrudService im // Find post count return tags.stream().map( - tag -> { - TagWithPostCountDTO tagWithCountOutputDTO = new TagWithPostCountDTO().convertFrom(tag); - tagWithCountOutputDTO.setPostCount(tagPostCountMap.getOrDefault(tag.getId(), 0L)); + tag -> { + TagWithPostCountDTO tagWithCountOutputDTO = new TagWithPostCountDTO().convertFrom(tag); + tagWithCountOutputDTO.setPostCount(tagPostCountMap.getOrDefault(tag.getId(), 0L)); - StringBuilder fullPath = new StringBuilder(); + StringBuilder fullPath = new StringBuilder(); - if (optionService.isEnabledAbsolutePath()) { - fullPath.append(optionService.getBlogBaseUrl()); - } - - fullPath.append("/") - .append(optionService.getTagsPrefix()) - .append("/") - .append(tag.getSlugName()) - .append(optionService.getPathSuffix()); - - tagWithCountOutputDTO.setFullPath(fullPath.toString()); - - return tagWithCountOutputDTO; + if (optionService.isEnabledAbsolutePath()) { + fullPath.append(optionService.getBlogBaseUrl()); } + + fullPath.append("/") + .append(optionService.getTagsPrefix()) + .append("/") + .append(tag.getSlugName()) + .append(optionService.getPathSuffix()); + + tagWithCountOutputDTO.setFullPath(fullPath.toString()); + + return tagWithCountOutputDTO; + } ).collect(Collectors.toList()); } diff --git a/src/main/java/run/halo/app/service/impl/RecoveryServiceImpl.java b/src/main/java/run/halo/app/service/impl/RecoveryServiceImpl.java index 8f2c30a20..185a94636 100644 --- a/src/main/java/run/halo/app/service/impl/RecoveryServiceImpl.java +++ b/src/main/java/run/halo/app/service/impl/RecoveryServiceImpl.java @@ -240,8 +240,8 @@ public class RecoveryServiceImpl implements RecoveryService { log.debug("Migrated tags of post [{}]: [{}]", tags, createdPost.getId()); List postComments = baseComments.stream() - .map(baseComment -> BeanUtils.transformFrom(baseComment, PostComment.class)) - .collect(Collectors.toList()); + .map(baseComment -> BeanUtils.transformFrom(baseComment, PostComment.class)) + .collect(Collectors.toList()); try { // Build virtual comment @@ -269,8 +269,8 @@ public class RecoveryServiceImpl implements RecoveryService { List baseComments = handleComment(commentsObject, createdSheet.getId()); List sheetComments = baseComments.stream() - .map(baseComment -> BeanUtils.transformFrom(baseComment, SheetComment.class)) - .collect(Collectors.toList()); + .map(baseComment -> BeanUtils.transformFrom(baseComment, SheetComment.class)) + .collect(Collectors.toList()); // Create comments try { @@ -303,8 +303,8 @@ public class RecoveryServiceImpl implements RecoveryService { } // Get all children List children = postComments.stream() - .filter(postComment -> Objects.equals(oldParentId, postComment.getParentId())) - .collect(Collectors.toList()); + .filter(postComment -> Objects.equals(oldParentId, postComment.getParentId())) + .collect(Collectors.toList()); // Set parent id again @@ -330,8 +330,8 @@ public class RecoveryServiceImpl implements RecoveryService { } // Get all children List children = sheetComments.stream() - .filter(sheetComment -> Objects.equals(oldParentId, sheetComment.getParentId())) - .collect(Collectors.toList()); + .filter(sheetComment -> Objects.equals(oldParentId, sheetComment.getParentId())) + .collect(Collectors.toList()); // Set parent id again children.forEach(postComment -> postComment.setParentId(parentComment.getId())); diff --git a/src/main/java/run/halo/app/service/impl/SheetMetaServiceImpl.java b/src/main/java/run/halo/app/service/impl/SheetMetaServiceImpl.java index f397797a8..fc9d1968e 100644 --- a/src/main/java/run/halo/app/service/impl/SheetMetaServiceImpl.java +++ b/src/main/java/run/halo/app/service/impl/SheetMetaServiceImpl.java @@ -33,6 +33,6 @@ public class SheetMetaServiceImpl extends BaseMetaServiceImpl impleme @Override public void validateTarget(Integer sheetId) { sheetRepository.findById(sheetId) - .orElseThrow(() -> new NotFoundException("查询不到该页面的信息").setErrorData(sheetId)); + .orElseThrow(() -> new NotFoundException("查询不到该页面的信息").setErrorData(sheetId)); } } diff --git a/src/main/java/run/halo/app/service/impl/StaticPageServiceImpl.java b/src/main/java/run/halo/app/service/impl/StaticPageServiceImpl.java index f40ee3381..220937b9c 100644 --- a/src/main/java/run/halo/app/service/impl/StaticPageServiceImpl.java +++ b/src/main/java/run/halo/app/service/impl/StaticPageServiceImpl.java @@ -168,8 +168,8 @@ public class StaticPageServiceImpl implements StaticPageService { public Path zipStaticPagesDirectory() { try { String staticPagePackName = HaloConst.STATIC_PAGE_PACK_PREFIX + - LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd-HH-mm-ss-")) + - IdUtil.simpleUUID().hashCode() + ".zip"; + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd-HH-mm-ss-")) + + IdUtil.simpleUUID().hashCode() + ".zip"; Path staticPageZipPath = Files.createFile(Paths.get(STATIC_PAGE_PACK_DIR, staticPagePackName)); FileUtils.zip(pagesDir, staticPageZipPath); diff --git a/src/main/java/run/halo/app/service/impl/StaticStorageServiceImpl.java b/src/main/java/run/halo/app/service/impl/StaticStorageServiceImpl.java index 8f16c4262..d4cd75e83 100644 --- a/src/main/java/run/halo/app/service/impl/StaticStorageServiceImpl.java +++ b/src/main/java/run/halo/app/service/impl/StaticStorageServiceImpl.java @@ -1,6 +1,7 @@ package run.halo.app.service.impl; import cn.hutool.core.util.IdUtil; +import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.lang.NonNull; import org.springframework.lang.Nullable; @@ -30,6 +31,7 @@ import java.util.stream.Stream; * @date 2019-12-06 */ @Service +@Slf4j public class StaticStorageServiceImpl implements StaticStorageService { private final Path staticDir; @@ -90,7 +92,7 @@ public class StaticStorageServiceImpl implements StaticStorageService { Assert.notNull(relativePath, "Relative path must not be null"); Path path = Paths.get(staticDir.toString(), relativePath); - System.out.println(path.toString()); + log.debug(path.toString()); try { if (path.toFile().isDirectory()) { diff --git a/src/main/java/run/halo/app/service/impl/TagServiceImpl.java b/src/main/java/run/halo/app/service/impl/TagServiceImpl.java index 63cd43610..3e3d99ff6 100644 --- a/src/main/java/run/halo/app/service/impl/TagServiceImpl.java +++ b/src/main/java/run/halo/app/service/impl/TagServiceImpl.java @@ -102,7 +102,7 @@ public class TagServiceImpl extends AbstractCrudService implements } return tags.stream() - .map(this::convertTo) - .collect(Collectors.toList()); + .map(this::convertTo) + .collect(Collectors.toList()); } } diff --git a/src/main/java/run/halo/app/service/impl/ThemeServiceImpl.java b/src/main/java/run/halo/app/service/impl/ThemeServiceImpl.java index 3587dbf6c..e459da4c5 100644 --- a/src/main/java/run/halo/app/service/impl/ThemeServiceImpl.java +++ b/src/main/java/run/halo/app/service/impl/ThemeServiceImpl.java @@ -138,7 +138,7 @@ public class ThemeServiceImpl implements ThemeService { // List and filter sub folders List themePaths = pathStream.filter(path -> Files.isDirectory(path)) - .collect(Collectors.toList()); + .collect(Collectors.toList()); if (CollectionUtils.isEmpty(themePaths)) { return Collections.emptySet(); @@ -177,13 +177,13 @@ public class ThemeServiceImpl implements ThemeService { try (Stream pathStream = Files.list(themePath)) { return pathStream.filter(path -> StringUtils.startsWithIgnoreCase(path.getFileName().toString(), CUSTOM_SHEET_PREFIX)) - .map(path -> { - // Remove prefix - String customTemplate = StringUtils.removeStartIgnoreCase(path.getFileName().toString(), CUSTOM_SHEET_PREFIX); - // Remove suffix - return StringUtils.removeEndIgnoreCase(customTemplate, HaloConst.SUFFIX_FTL); - }) - .collect(Collectors.toSet()); + .map(path -> { + // Remove prefix + String customTemplate = StringUtils.removeStartIgnoreCase(path.getFileName().toString(), CUSTOM_SHEET_PREFIX); + // Remove suffix + return StringUtils.removeEndIgnoreCase(customTemplate, HaloConst.SUFFIX_FTL); + }) + .collect(Collectors.toSet()); } catch (IOException e) { throw new ServiceException("Failed to list files of path " + themePath.toString(), e); } @@ -196,13 +196,13 @@ public class ThemeServiceImpl implements ThemeService { try (Stream pathStream = Files.list(themePath)) { return pathStream.filter(path -> StringUtils.startsWithIgnoreCase(path.getFileName().toString(), prefix)) - .map(path -> { - // Remove prefix - String customTemplate = StringUtils.removeStartIgnoreCase(path.getFileName().toString(), prefix); - // Remove suffix - return StringUtils.removeEndIgnoreCase(customTemplate, HaloConst.SUFFIX_FTL); - }) - .collect(Collectors.toSet()); + .map(path -> { + // Remove prefix + String customTemplate = StringUtils.removeStartIgnoreCase(path.getFileName().toString(), prefix); + // Remove suffix + return StringUtils.removeEndIgnoreCase(customTemplate, HaloConst.SUFFIX_FTL); + }) + .collect(Collectors.toSet()); } catch (IOException e) { throw new ServiceException("Failed to list files of path " + themePath.toString(), e); } @@ -473,7 +473,7 @@ public class ThemeServiceImpl implements ThemeService { // Check theme existence boolean isExist = getThemes().stream() - .anyMatch(themeProperty -> themeProperty.getId().equalsIgnoreCase(tmpThemeProperty.getId())); + .anyMatch(themeProperty -> themeProperty.getId().equalsIgnoreCase(tmpThemeProperty.getId())); if (isExist) { throw new AlreadyExistsException("当前安装的主题已存在"); @@ -616,7 +616,7 @@ public class ThemeServiceImpl implements ThemeService { // Get branch String branch = StringUtils.isBlank(themeProperty.getBranch()) ? - DEFAULT_REMOTE_BRANCH : themeProperty.getBranch(); + DEFAULT_REMOTE_BRANCH : themeProperty.getBranch(); Git git = null; @@ -634,38 +634,38 @@ public class ThemeServiceImpl implements ThemeService { // Force to set remote name git.remoteRemove().setRemoteName(THEME_PROVIDER_REMOTE_NAME).call(); RemoteConfig remoteConfig = git.remoteAdd() - .setName(THEME_PROVIDER_REMOTE_NAME) - .setUri(new URIish(themeProperty.getRepo())) - .call(); + .setName(THEME_PROVIDER_REMOTE_NAME) + .setUri(new URIish(themeProperty.getRepo())) + .call(); // Add all changes git.add() - .addFilepattern(".") - .call(); + .addFilepattern(".") + .call(); // Commit the changes git.commit().setMessage("Commit by halo automatically").call(); // Check out to specified branch if (!StringUtils.equalsIgnoreCase(branch, git.getRepository().getBranch())) { boolean present = git.branchList() - .call() - .stream() - .map(Ref::getName) - .anyMatch(name -> StringUtils.equalsIgnoreCase(name, branch)); + .call() + .stream() + .map(Ref::getName) + .anyMatch(name -> StringUtils.equalsIgnoreCase(name, branch)); git.checkout() - .setCreateBranch(true) - .setForced(!present) - .setName(branch) - .call(); + .setCreateBranch(true) + .setForced(!present) + .setName(branch) + .call(); } // Pull with rebasing PullResult pullResult = git.pull() - .setRemote(remoteConfig.getName()) - .setRemoteBranchName(branch) - .setRebase(true) - .call(); + .setRemote(remoteConfig.getName()) + .setRemoteBranchName(branch) + .setRebase(true) + .call(); if (!pullResult.isSuccessful()) { log.debug("Rebase result: [{}]", pullResult.getRebaseResult()); @@ -681,9 +681,9 @@ public class ThemeServiceImpl implements ThemeService { if (StringUtils.isNotEmpty(updatedThemeProperty.getRequire()) && !VersionUtil.compareVersion(HaloConst.HALO_VERSION, updatedThemeProperty.getRequire())) { // reset theme version git.reset() - .setMode(ResetCommand.ResetType.HARD) - .setRef(lastCommit.getName()) - .call(); + .setMode(ResetCommand.ResetType.HARD) + .setRef(lastCommit.getName()) + .call(); throw new ThemeNotSupportException("新版本主题仅支持 Halo " + updatedThemeProperty.getRequire() + " 以上的版本"); } } finally { @@ -864,11 +864,11 @@ public class ThemeServiceImpl implements ThemeService { // Set screenshots getScreenshotsFileName(themePath).ifPresent(screenshotsName -> - themeProperty.setScreenshots(StringUtils.join(optionService.getBlogBaseUrl(), - "/themes/", - FilenameUtils.getBasename(themeProperty.getThemePath()), - "/", - screenshotsName))); + themeProperty.setScreenshots(StringUtils.join(optionService.getBlogBaseUrl(), + "/themes/", + FilenameUtils.getBasename(themeProperty.getThemePath()), + "/", + screenshotsName))); if (StringUtils.equals(themeProperty.getId(), getActivatedThemeId())) { // Set activation @@ -908,10 +908,10 @@ public class ThemeServiceImpl implements ThemeService { try (Stream pathStream = Files.list(themePath)) { return pathStream.filter(path -> Files.isRegularFile(path) - && Files.isReadable(path) - && FilenameUtils.getBasename(path.toString()).equalsIgnoreCase(THEME_SCREENSHOTS_NAME)) - .findFirst() - .map(path -> path.getFileName().toString()); + && Files.isReadable(path) + && FilenameUtils.getBasename(path.toString()).equalsIgnoreCase(THEME_SCREENSHOTS_NAME)) + .findFirst() + .map(path -> path.getFileName().toString()); } } diff --git a/src/main/java/run/halo/app/service/impl/ThemeSettingServiceImpl.java b/src/main/java/run/halo/app/service/impl/ThemeSettingServiceImpl.java index d058e913f..6cf10f417 100644 --- a/src/main/java/run/halo/app/service/impl/ThemeSettingServiceImpl.java +++ b/src/main/java/run/halo/app/service/impl/ThemeSettingServiceImpl.java @@ -59,11 +59,11 @@ public class ThemeSettingServiceImpl extends AbstractCrudService { - themeSettingRepository.delete(setting); - log.debug("Removed theme setting: [{}]", setting); - return setting; - }).orElse(null); + .map(setting -> { + themeSettingRepository.delete(setting); + log.debug("Removed theme setting: [{}]", setting); + return setting; + }).orElse(null); } // Get config item map @@ -74,19 +74,19 @@ public class ThemeSettingServiceImpl extends AbstractCrudService { - log.debug("Updating theme setting: [{}]", setting); - setting.setValue(value); - log.debug("Updated theme setting: [{}]", setting); - return setting; - }).orElseGet(() -> { - ThemeSetting setting = new ThemeSetting(); - setting.setKey(key); - setting.setValue(value); - setting.setThemeId(themeId); - log.debug("Creating theme setting: [{}]", setting); - return setting; - }); + .map(setting -> { + log.debug("Updating theme setting: [{}]", setting); + setting.setValue(value); + log.debug("Updated theme setting: [{}]", setting); + return setting; + }).orElseGet(() -> { + ThemeSetting setting = new ThemeSetting(); + setting.setKey(key); + setting.setValue(value); + setting.setThemeId(themeId); + log.debug("Creating theme setting: [{}]", setting); + return setting; + }); // Save the theme setting return themeSettingRepository.save(themeSetting); diff --git a/src/main/java/run/halo/app/utils/BeanUtils.java b/src/main/java/run/halo/app/utils/BeanUtils.java index ba3729489..e0ca792a0 100644 --- a/src/main/java/run/halo/app/utils/BeanUtils.java +++ b/src/main/java/run/halo/app/utils/BeanUtils.java @@ -69,8 +69,8 @@ public class BeanUtils { // Transform in batch return sources.stream() - .map(source -> transformFrom(source, targetClass)) - .collect(Collectors.toList()); + .map(source -> transformFrom(source, targetClass)) + .collect(Collectors.toList()); } /** diff --git a/src/main/java/run/halo/app/utils/FileUtils.java b/src/main/java/run/halo/app/utils/FileUtils.java index bdb80f3ce..026c5b012 100644 --- a/src/main/java/run/halo/app/utils/FileUtils.java +++ b/src/main/java/run/halo/app/utils/FileUtils.java @@ -72,7 +72,7 @@ public class FileUtils { // Delete folder recursively org.eclipse.jgit.util.FileUtils.delete(deletingPath.toFile(), - org.eclipse.jgit.util.FileUtils.RECURSIVE | org.eclipse.jgit.util.FileUtils.RETRY); + org.eclipse.jgit.util.FileUtils.RECURSIVE | org.eclipse.jgit.util.FileUtils.RETRY); log.info("Deleted [{}] successfully", deletingPath); } diff --git a/src/main/java/run/halo/app/utils/GitUtils.java b/src/main/java/run/halo/app/utils/GitUtils.java index 9ec801a35..5ae874738 100644 --- a/src/main/java/run/halo/app/utils/GitUtils.java +++ b/src/main/java/run/halo/app/utils/GitUtils.java @@ -37,9 +37,9 @@ public class GitUtils { Git git = null; try { git = Git.cloneRepository() - .setURI(repoUrl) - .setDirectory(targetPath.toFile()) - .call(); + .setURI(repoUrl) + .setDirectory(targetPath.toFile()) + .call(); log.debug("Cloned git repo [{}] successfully", repoUrl); } finally { closeQuietly(git); diff --git a/src/main/java/run/halo/app/utils/HaloUtils.java b/src/main/java/run/halo/app/utils/HaloUtils.java index 6a58722d6..25c0451d9 100755 --- a/src/main/java/run/halo/app/utils/HaloUtils.java +++ b/src/main/java/run/halo/app/utils/HaloUtils.java @@ -244,7 +244,7 @@ public class HaloUtils { Assert.hasText(originalUrl, "Original Url must not be blank"); if (StringUtils.startsWithAny(originalUrl, "/", "https://", "http://") - && !StringUtils.startsWith(originalUrl, "//")) { + && !StringUtils.startsWith(originalUrl, "//")) { return originalUrl; } diff --git a/src/main/java/run/halo/app/utils/HttpClientUtils.java b/src/main/java/run/halo/app/utils/HttpClientUtils.java index 79a9cdb9f..9294508d4 100644 --- a/src/main/java/run/halo/app/utils/HttpClientUtils.java +++ b/src/main/java/run/halo/app/utils/HttpClientUtils.java @@ -41,14 +41,14 @@ public class HttpClientUtils { @NonNull public static CloseableHttpClient createHttpsClient(int timeout) throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException { SSLContext sslContext = new SSLContextBuilder() - .loadTrustMaterial(null, (certificate, authType) -> true) - .build(); + .loadTrustMaterial(null, (certificate, authType) -> true) + .build(); return HttpClients.custom() - .setSSLContext(sslContext) - .setSSLHostnameVerifier(new NoopHostnameVerifier()) - .setDefaultRequestConfig(getReqeustConfig(timeout)) - .build(); + .setSSLContext(sslContext) + .setSSLHostnameVerifier(new NoopHostnameVerifier()) + .setDefaultRequestConfig(getReqeustConfig(timeout)) + .build(); } /** @@ -59,10 +59,10 @@ public class HttpClientUtils { */ private static RequestConfig getReqeustConfig(int timeout) { return RequestConfig.custom() - .setConnectTimeout(timeout) - .setConnectionRequestTimeout(timeout) - .setSocketTimeout(timeout) - .build(); + .setConnectTimeout(timeout) + .setConnectionRequestTimeout(timeout) + .setSocketTimeout(timeout) + .build(); } diff --git a/src/main/java/run/halo/app/utils/MarkdownUtils.java b/src/main/java/run/halo/app/utils/MarkdownUtils.java index 3bcd6fc5d..c9fa05430 100644 --- a/src/main/java/run/halo/app/utils/MarkdownUtils.java +++ b/src/main/java/run/halo/app/utils/MarkdownUtils.java @@ -37,32 +37,32 @@ import java.util.Map; public class MarkdownUtils { private static final DataHolder OPTIONS = new MutableDataSet() - .set(Parser.EXTENSIONS, Arrays.asList( - AttributesExtension.create(), - AutolinkExtension.create(), - EmojiExtension.create(), - EscapedCharacterExtension.create(), - StrikethroughExtension.create(), - TaskListExtension.create(), - InsExtension.create(), - MediaTagsExtension.create(), - TablesExtension.create(), - TocExtension.create(), - YamlFrontMatterExtension.create(), - GitLabExtension.create()) - ) - .set(TocExtension.LEVELS, 255) - .set(TablesExtension.WITH_CAPTION, false) - .set(TablesExtension.COLUMN_SPANS, false) - .set(TablesExtension.MIN_SEPARATOR_DASHES, 1) - .set(TablesExtension.MIN_HEADER_ROWS, 1) - .set(TablesExtension.MAX_HEADER_ROWS, 1) - .set(TablesExtension.APPEND_MISSING_COLUMNS, true) - .set(TablesExtension.DISCARD_EXTRA_COLUMNS, true) - .set(TablesExtension.HEADER_SEPARATOR_COLUMN_MATCH, true) - .set(EmojiExtension.USE_SHORTCUT_TYPE, EmojiShortcutType.EMOJI_CHEAT_SHEET) - .set(EmojiExtension.USE_IMAGE_TYPE, EmojiImageType.UNICODE_ONLY) - .set(HtmlRenderer.SOFT_BREAK, "
\n"); + .set(Parser.EXTENSIONS, Arrays.asList( + AttributesExtension.create(), + AutolinkExtension.create(), + EmojiExtension.create(), + EscapedCharacterExtension.create(), + StrikethroughExtension.create(), + TaskListExtension.create(), + InsExtension.create(), + MediaTagsExtension.create(), + TablesExtension.create(), + TocExtension.create(), + YamlFrontMatterExtension.create(), + GitLabExtension.create()) + ) + .set(TocExtension.LEVELS, 255) + .set(TablesExtension.WITH_CAPTION, false) + .set(TablesExtension.COLUMN_SPANS, false) + .set(TablesExtension.MIN_SEPARATOR_DASHES, 1) + .set(TablesExtension.MIN_HEADER_ROWS, 1) + .set(TablesExtension.MAX_HEADER_ROWS, 1) + .set(TablesExtension.APPEND_MISSING_COLUMNS, true) + .set(TablesExtension.DISCARD_EXTRA_COLUMNS, true) + .set(TablesExtension.HEADER_SEPARATOR_COLUMN_MATCH, true) + .set(EmojiExtension.USE_SHORTCUT_TYPE, EmojiShortcutType.EMOJI_CHEAT_SHEET) + .set(EmojiExtension.USE_IMAGE_TYPE, EmojiImageType.UNICODE_ONLY) + .set(HtmlRenderer.SOFT_BREAK, "
\n"); private static final Parser PARSER = Parser.builder(OPTIONS).build(); diff --git a/src/main/java/run/halo/app/utils/ServiceUtils.java b/src/main/java/run/halo/app/utils/ServiceUtils.java index bc04025cc..fdd5c1308 100644 --- a/src/main/java/run/halo/app/utils/ServiceUtils.java +++ b/src/main/java/run/halo/app/utils/ServiceUtils.java @@ -32,8 +32,8 @@ public class ServiceUtils { @NonNull public static Set fetchProperty(final Collection datas, Function mappingFunction) { return CollectionUtils.isEmpty(datas) ? - Collections.emptySet() : - datas.stream().map(mappingFunction).collect(Collectors.toSet()); + Collections.emptySet() : + datas.stream().map(mappingFunction).collect(Collectors.toSet()); } /** diff --git a/src/main/java/run/halo/app/utils/ServletUtils.java b/src/main/java/run/halo/app/utils/ServletUtils.java index 9329f3032..1df167de4 100644 --- a/src/main/java/run/halo/app/utils/ServletUtils.java +++ b/src/main/java/run/halo/app/utils/ServletUtils.java @@ -28,9 +28,9 @@ public class ServletUtils { @NonNull public static Optional getCurrentRequest() { return Optional.ofNullable(RequestContextHolder.getRequestAttributes()) - .filter(requestAttributes -> requestAttributes instanceof ServletRequestAttributes) - .map(requestAttributes -> ((ServletRequestAttributes) requestAttributes)) - .map(ServletRequestAttributes::getRequest); + .filter(requestAttributes -> requestAttributes instanceof ServletRequestAttributes) + .map(requestAttributes -> (ServletRequestAttributes) requestAttributes) + .map(ServletRequestAttributes::getRequest); } /** diff --git a/src/main/java/run/halo/app/utils/SlugUtils.java b/src/main/java/run/halo/app/utils/SlugUtils.java index ca6bafa7d..7164b9d5b 100644 --- a/src/main/java/run/halo/app/utils/SlugUtils.java +++ b/src/main/java/run/halo/app/utils/SlugUtils.java @@ -47,10 +47,10 @@ public class SlugUtils { public static String slug(@NonNull String input) { Assert.hasText(input, "Input string must not be blank"); String slug = input. - replaceAll("[^(a-zA-Z0-9\\u4e00-\\u9fa5\\.\\-)]", ""). - replaceAll("[\\?\\\\/:|<>\\*\\[\\]\\(\\)\\$%\\{\\}@~\\.]", ""). - replaceAll("\\s", "") - .toLowerCase(Locale.ENGLISH); + replaceAll("[^(a-zA-Z0-9\\u4e00-\\u9fa5\\.\\-)]", ""). + replaceAll("[\\?\\\\/:|<>\\*\\[\\]\\(\\)\\$%\\{\\}@~\\.]", ""). + replaceAll("\\s", "") + .toLowerCase(Locale.ENGLISH); return StrUtil.isNotEmpty(slug) ? slug : String.valueOf(System.currentTimeMillis()); } } diff --git a/src/main/java/run/halo/app/utils/ValidationUtils.java b/src/main/java/run/halo/app/utils/ValidationUtils.java index e28c20434..40f4e1310 100644 --- a/src/main/java/run/halo/app/utils/ValidationUtils.java +++ b/src/main/java/run/halo/app/utils/ValidationUtils.java @@ -77,8 +77,8 @@ public class ValidationUtils { Map errMap = new HashMap<>(4); // Format the error message constraintViolations.forEach( - constraintViolation -> - errMap.put(constraintViolation.getPropertyPath().toString(), constraintViolation.getMessage())); + constraintViolation -> + errMap.put(constraintViolation.getPropertyPath().toString(), constraintViolation.getMessage())); return errMap; } diff --git a/src/main/java/run/halo/app/utils/VersionUtil.java b/src/main/java/run/halo/app/utils/VersionUtil.java index e1d6f8406..659922f96 100644 --- a/src/main/java/run/halo/app/utils/VersionUtil.java +++ b/src/main/java/run/halo/app/utils/VersionUtil.java @@ -15,7 +15,7 @@ public class VersionUtil { } public static int[] getCanonicalVersion(String version) { - int[] canonicalVersion = new int[]{1, 1, 0, 0}; + int[] canonicalVersion = new int[] {1, 1, 0, 0}; StringTokenizer tokenizer = new StringTokenizer(version, "."); String token = tokenizer.nextToken(); canonicalVersion[0] = Integer.parseInt(token); diff --git a/src/main/resources/application-user.yaml b/src/main/resources/application-user.yaml index b9718153c..def1ae047 100755 --- a/src/main/resources/application-user.yaml +++ b/src/main/resources/application-user.yaml @@ -14,10 +14,10 @@ spring: password: 123456 # MySQL database configuration. -# driver-class-name: com.mysql.cj.jdbc.Driver -# url: jdbc:mysql://127.0.0.1:3306/halodb?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true -# username: root -# password: 123456 + # driver-class-name: com.mysql.cj.jdbc.Driver + # url: jdbc:mysql://127.0.0.1:3306/halodb?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true + # username: root + # password: 123456 # H2 database console configuration. h2: diff --git a/src/test/java/run/halo/app/handler/aspect/DisableOnConditionAspectTest.java b/src/test/java/run/halo/app/handler/aspect/DisableOnConditionAspectTest.java index e58e5c57c..1624e2ee4 100644 --- a/src/test/java/run/halo/app/handler/aspect/DisableOnConditionAspectTest.java +++ b/src/test/java/run/halo/app/handler/aspect/DisableOnConditionAspectTest.java @@ -30,14 +30,12 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @AutoConfigureMockMvc class DisableOnConditionAspectTest { + static final String REQUEST_URI = "/api/admin/test/disableOnCondition"; @Autowired MockMvc mvc; - @Autowired OptionService optionService; - static final String REQUEST_URI = "/api/admin/test/disableOnCondition"; - @BeforeEach void setUp() { optionService.saveProperty(PrimaryProperties.IS_INSTALLED, "true"); @@ -48,8 +46,8 @@ class DisableOnConditionAspectTest { Throwable t = null; try { mvc.perform(get(REQUEST_URI + "/no")) - .andDo(print()) - .andReturn(); + .andDo(print()) + .andReturn(); } catch (NestedServletException nse) { t = nse; } @@ -63,8 +61,8 @@ class DisableOnConditionAspectTest { @Test void ableAccessTest() throws Exception { mvc.perform(get(REQUEST_URI + "/yes")) - .andDo(print()) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.status", is(HttpStatus.OK.value()))); + .andDo(print()) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.status", is(HttpStatus.OK.value()))); } } diff --git a/src/test/java/run/halo/app/handler/theme/YamlThemePropertyResolverTest.java b/src/test/java/run/halo/app/handler/theme/YamlThemePropertyResolverTest.java index e5a9d95c7..ad4b3b73e 100644 --- a/src/test/java/run/halo/app/handler/theme/YamlThemePropertyResolverTest.java +++ b/src/test/java/run/halo/app/handler/theme/YamlThemePropertyResolverTest.java @@ -2,6 +2,7 @@ package run.halo.app.handler.theme; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; +import lombok.extern.slf4j.Slf4j; import org.junit.Test; import run.halo.app.handler.theme.config.support.ThemeProperty; @@ -11,6 +12,7 @@ import java.io.IOException; * @author johnniang * @date 4/11/19 */ +@Slf4j public class YamlThemePropertyResolverTest { private final ObjectMapper yamlMapper = new ObjectMapper(new YAMLFactory()); @@ -18,17 +20,17 @@ public class YamlThemePropertyResolverTest { @Test public void directResolveTest() throws IOException { String yaml = "id: viosey_material\n" + - "name: Material\n" + - "author:\n" + - " name: Viosey\n" + - " website: https://viosey.com\n" + - "description: Nature, Pure | 原质,纯粹\n" + - "logo: https://avatars0.githubusercontent.com/u/8141232?s=460&v=4\n" + - "website: https://github.com/viosey/hexo-theme-material\n" + - "version: 1.0"; + "name: Material\n" + + "author:\n" + + " name: Viosey\n" + + " website: https://viosey.com\n" + + "description: Nature, Pure | 原质,纯粹\n" + + "logo: https://avatars0.githubusercontent.com/u/8141232?s=460&v=4\n" + + "website: https://github.com/viosey/hexo-theme-material\n" + + "version: 1.0"; ThemeProperty themeProperty = yamlMapper.readValue(yaml, ThemeProperty.class); - System.out.println(themeProperty); + log.debug("[{}]", themeProperty); } } \ No newline at end of file diff --git a/src/test/java/run/halo/app/model/MediaTypeTest.java b/src/test/java/run/halo/app/model/MediaTypeTest.java index 7d78ba00b..7e942a159 100644 --- a/src/test/java/run/halo/app/model/MediaTypeTest.java +++ b/src/test/java/run/halo/app/model/MediaTypeTest.java @@ -3,7 +3,6 @@ package run.halo.app.model; import lombok.extern.slf4j.Slf4j; import org.junit.Test; import org.springframework.http.MediaType; -import run.halo.app.service.support.HaloMediaType; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.*; diff --git a/src/test/java/run/halo/app/model/enums/DataTypeTest.java b/src/test/java/run/halo/app/model/enums/DataTypeTest.java index 1dd93226b..208000022 100644 --- a/src/test/java/run/halo/app/model/enums/DataTypeTest.java +++ b/src/test/java/run/halo/app/model/enums/DataTypeTest.java @@ -1,9 +1,10 @@ package run.halo.app.model.enums; +import lombok.extern.slf4j.Slf4j; import org.junit.Test; import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.*; +import static org.junit.Assert.assertThat; /** * Data type test. @@ -11,12 +12,13 @@ import static org.junit.Assert.*; * @author johnniang * @date 19-4-21 */ +@Slf4j public class DataTypeTest { @Test public void typeOf() { DataType type = DataType.typeOf("bool"); - System.out.println(type); + log.debug("[{}]", type); assertThat(type, equalTo(DataType.BOOL)); } } \ No newline at end of file diff --git a/src/test/java/run/halo/app/model/params/InstallParamTest.java b/src/test/java/run/halo/app/model/params/InstallParamTest.java index 669d48b71..6ce80ce87 100644 --- a/src/test/java/run/halo/app/model/params/InstallParamTest.java +++ b/src/test/java/run/halo/app/model/params/InstallParamTest.java @@ -2,7 +2,6 @@ package run.halo.app.model.params; import lombok.extern.slf4j.Slf4j; import org.junit.Test; -import run.halo.app.model.support.AllCheck; import run.halo.app.model.support.CreateCheck; import javax.validation.ConstraintViolation; diff --git a/src/test/java/run/halo/app/repository/SheetRepositoryTest.java b/src/test/java/run/halo/app/repository/SheetRepositoryTest.java index 4db9ec92b..e47c45240 100644 --- a/src/test/java/run/halo/app/repository/SheetRepositoryTest.java +++ b/src/test/java/run/halo/app/repository/SheetRepositoryTest.java @@ -1,12 +1,13 @@ package run.halo.app.repository; -import run.halo.app.model.entity.Sheet; +import lombok.extern.slf4j.Slf4j; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; +import run.halo.app.model.entity.Sheet; import java.util.List; @@ -19,6 +20,7 @@ import java.util.List; @RunWith(SpringRunner.class) @SpringBootTest @ActiveProfiles("test") +@Slf4j public class SheetRepositoryTest { @Autowired @@ -27,6 +29,6 @@ public class SheetRepositoryTest { @Test public void listAllTest() { List allSheets = sheetRepository.findAll(); - System.out.println(allSheets); + log.debug("{}", allSheets); } } diff --git a/src/test/java/run/halo/app/security/OneTimeTokenTest.java b/src/test/java/run/halo/app/security/OneTimeTokenTest.java index 12bc7b54e..b9a0598ae 100644 --- a/src/test/java/run/halo/app/security/OneTimeTokenTest.java +++ b/src/test/java/run/halo/app/security/OneTimeTokenTest.java @@ -21,21 +21,19 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @AutoConfigureMockMvc class OneTimeTokenTest { + static final String REQUEST_URI = "/api/admin/counts"; @Autowired MockMvc mvc; - @Autowired OneTimeTokenService oneTimeTokenService; - static final String REQUEST_URI = "/api/admin/counts"; - @Test void provideNonExistOneTimeTokenTest() throws Exception { mvc.perform(get(REQUEST_URI + "?ott={ott}", "one-time-token-value")) - .andDo(print()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) - .andExpect(status().isBadRequest()) - .andExpect(jsonPath("$.status", is(HttpStatus.BAD_REQUEST.value()))); + .andDo(print()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.status", is(HttpStatus.BAD_REQUEST.value()))); } @Test @@ -44,8 +42,8 @@ class OneTimeTokenTest { String ott = oneTimeTokenService.create(REQUEST_URI); mvc.perform(get(REQUEST_URI + "?ott={ott}", ott)) - .andDo(print()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()); + .andDo(print()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()); } } diff --git a/src/test/java/run/halo/app/service/impl/PostServiceImplTest.java b/src/test/java/run/halo/app/service/impl/PostServiceImplTest.java index fe62df791..c585f5042 100644 --- a/src/test/java/run/halo/app/service/impl/PostServiceImplTest.java +++ b/src/test/java/run/halo/app/service/impl/PostServiceImplTest.java @@ -1,5 +1,6 @@ package run.halo.app.service.impl; +import lombok.extern.slf4j.Slf4j; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; @@ -12,28 +13,29 @@ import org.springframework.transaction.annotation.Transactional; @RunWith(SpringRunner.class) @SpringBootTest @ActiveProfiles("test") +@Slf4j public class PostServiceImplTest { private String standardMdContent = "---\n" + - "title: springfox-swagger2配置成功但无法访问/swagger-ui.html\n" + - "tags:\n" + - " - spring boot\n" + - " - swagger\n" + - " - solution\n" + - "date: 2018-11-23 16:11:28\n" + - "---\n" + - "\n" + - "# Pre\n" + - "\n" + - "在前后端分离项目中,通常需要用到 API 文档,springfox 开发的 **[SpringFox](https://github.com/springfox/springfox)** 可以实现自动化 json API 文档。"; + "title: springfox-swagger2配置成功但无法访问/swagger-ui.html\n" + + "tags:\n" + + " - spring boot\n" + + " - swagger\n" + + " - solution\n" + + "date: 2018-11-23 16:11:28\n" + + "---\n" + + "\n" + + "# Pre\n" + + "\n" + + "在前后端分离项目中,通常需要用到 API 文档,springfox 开发的 **[SpringFox](https://github.com/springfox/springfox)** 可以实现自动化 json API 文档。"; private String nonStandardMdContent = "---\n" + - "title: Basic concepts of JPA\n" + - "date: 2018-08-03 11:57:00\n" + - "tags: ['spring', 'jpa', 'database', 'concept']\n" + - "---\n" + - "\n" + - "以下将讲解关系型数据的关系描述。仅仅是作为总结。"; + "title: Basic concepts of JPA\n" + + "date: 2018-08-03 11:57:00\n" + + "tags: ['spring', 'jpa', 'database', 'concept']\n" + + "---\n" + + "\n" + + "以下将讲解关系型数据的关系描述。仅仅是作为总结。"; @Autowired private PostServiceImpl postService; @@ -42,7 +44,7 @@ public class PostServiceImplTest { @Ignore public void getContent() { String exportMarkdown = postService.exportMarkdown(18); - System.out.println(exportMarkdown); + log.debug(exportMarkdown); } @Test diff --git a/src/test/java/run/halo/app/utils/BcryptTest.java b/src/test/java/run/halo/app/utils/BcryptTest.java index fec06895a..d6ae834a2 100644 --- a/src/test/java/run/halo/app/utils/BcryptTest.java +++ b/src/test/java/run/halo/app/utils/BcryptTest.java @@ -1,6 +1,7 @@ package run.halo.app.utils; import cn.hutool.crypto.digest.BCrypt; +import lombok.extern.slf4j.Slf4j; import org.junit.Test; /** @@ -9,11 +10,12 @@ import org.junit.Test; * @author johnniang * @date 3/28/19 */ +@Slf4j public class BcryptTest { @Test public void cryptTest() { String cryptPassword = BCrypt.hashpw("opentest", BCrypt.gensalt()); - System.out.println("Crypt password: " + cryptPassword); + log.debug("Crypt password: [{}]", cryptPassword); } } diff --git a/src/test/java/run/halo/app/utils/BeanUtilsTest.java b/src/test/java/run/halo/app/utils/BeanUtilsTest.java index 4c9c1248a..b636c8571 100644 --- a/src/test/java/run/halo/app/utils/BeanUtilsTest.java +++ b/src/test/java/run/halo/app/utils/BeanUtilsTest.java @@ -3,13 +3,13 @@ package run.halo.app.utils; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; -import org.junit.Assert; import org.junit.Test; import java.util.Arrays; import java.util.List; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; /** * BeanUtils test. @@ -38,8 +38,8 @@ public class BeanUtilsTest { @Test public void transformFromInBatch() { TestA[] as = { - new TestA(1, 2), - new TestA(3, 4) + new TestA(1, 2), + new TestA(3, 4) }; List aList = Arrays.asList(as); diff --git a/src/test/java/run/halo/app/utils/DirectoryAttackTest.java b/src/test/java/run/halo/app/utils/DirectoryAttackTest.java index 65c83f198..45ca84ed3 100644 --- a/src/test/java/run/halo/app/utils/DirectoryAttackTest.java +++ b/src/test/java/run/halo/app/utils/DirectoryAttackTest.java @@ -1,10 +1,10 @@ package run.halo.app.utils; +import lombok.extern.slf4j.Slf4j; import org.junit.Assert; import org.junit.Test; import run.halo.app.exception.ForbiddenException; -import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; @@ -14,6 +14,7 @@ import java.nio.file.Paths; * @author johnniang * @date 4/9/19 */ +@Slf4j public class DirectoryAttackTest { private String userHome = System.getProperty("user.home"); @@ -25,8 +26,8 @@ public class DirectoryAttackTest { Path testPath = Paths.get(userHome + "/../../etc/passwd"); - System.out.println("Work directory path: " + workDirPath); - System.out.println("Test path: " + testPath); + log.debug("Work directory path: [{}]", workDirPath); + log.debug("Test path: [{}]", testPath); Assert.assertFalse(testPath.startsWith(workDirPath)); Assert.assertFalse(workDirPath.startsWith(testPath)); @@ -38,8 +39,8 @@ public class DirectoryAttackTest { Path testPath = Paths.get(userHome + "/halo-test/test.txt"); - System.out.println("Work directory path: " + workDirPath); - System.out.println("Test path: " + testPath); + log.debug("Work directory path: [{}]", workDirPath); + log.debug("Test path: [{}]", testPath); Assert.assertTrue(testPath.startsWith(workDirPath)); Assert.assertFalse(workDirPath.startsWith(testPath)); @@ -52,8 +53,8 @@ public class DirectoryAttackTest { Path testPath = Paths.get("/etc/passwd"); - System.out.println("Work directory path: " + workDirPath); - System.out.println("Test path: " + testPath); + log.debug("Work directory path: [{}]", workDirPath); + log.debug("Test path: [{}]", testPath); Assert.assertTrue(testPath.startsWith(workDirPath)); Assert.assertFalse(workDirPath.startsWith(testPath)); @@ -64,10 +65,10 @@ public class DirectoryAttackTest { String pathname = "/home/test/../../etc/"; Path path = Paths.get(pathname); - System.out.println("Path: " + path); - System.out.println("Absolute path: " + path.toAbsolutePath()); - System.out.println("Name count: " + path.getNameCount()); - System.out.println("Normalized path: " + path.normalize()); + log.debug("Path: [{}]", path); + log.debug("Absolute path: [{}]", path.toAbsolutePath()); + log.debug("Name count: [{}]", path.getNameCount()); + log.debug("Normalized path: [{}]", path.normalize()); } @Test diff --git a/src/test/java/run/halo/app/utils/FileUtilsTest.java b/src/test/java/run/halo/app/utils/FileUtilsTest.java index d1a7e860d..420894007 100644 --- a/src/test/java/run/halo/app/utils/FileUtilsTest.java +++ b/src/test/java/run/halo/app/utils/FileUtilsTest.java @@ -37,25 +37,25 @@ public class FileUtilsTest { try (Stream pathStream = Files.walk(tempDirectory)) { List walkList = pathStream.collect(Collectors.toList()); - walkList.forEach(System.out::println); + walkList.forEach(path -> log.debug(path.toString())); Assert.assertThat(walkList.size(), equalTo(4)); } try (Stream pathStream = Files.walk(tempDirectory, 1)) { List walkList = pathStream.collect(Collectors.toList()); - walkList.forEach(System.out::println); + walkList.forEach(path -> log.debug(path.toString())); Assert.assertThat(walkList.size(), equalTo(2)); } try (Stream pathStream = Files.list(tempDirectory)) { List walkList = pathStream.collect(Collectors.toList()); - walkList.forEach(System.out::println); + walkList.forEach(path -> log.debug(path.toString())); Assert.assertThat(walkList.size(), equalTo(1)); } try (Stream pathStream = Files.list(testPath)) { List walkList = pathStream.collect(Collectors.toList()); - walkList.forEach(System.out::println); + walkList.forEach(path -> log.debug(path.toString())); Assert.assertThat(walkList.size(), equalTo(0)); } @@ -103,9 +103,9 @@ public class FileUtilsTest { randomAccessFile.seek(2283640); byte[] buffer = new byte[1024]; int count = randomAccessFile.read(buffer, 0, buffer.length); - System.out.println("Count: " + count); + log.debug("Count: [{}]", count); String bufString = new String(buffer); - System.out.println("Buffer String: " + bufString); + log.debug("Buffer String: [{}]", bufString); } } } \ No newline at end of file diff --git a/src/test/java/run/halo/app/utils/GitTest.java b/src/test/java/run/halo/app/utils/GitTest.java index 83c36ab00..77d3a3690 100644 --- a/src/test/java/run/halo/app/utils/GitTest.java +++ b/src/test/java/run/halo/app/utils/GitTest.java @@ -7,14 +7,16 @@ import org.eclipse.jgit.api.errors.GitAPIException; import org.eclipse.jgit.errors.RepositoryNotFoundException; import org.eclipse.jgit.transport.RemoteConfig; import org.eclipse.jgit.transport.URIish; -import org.junit.*; +import org.junit.After; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; import java.io.IOException; import java.net.URISyntaxException; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; -import java.util.Set; /** * Git test. @@ -80,8 +82,8 @@ public class GitTest { private Git cloneRepository() throws GitAPIException { return Git.cloneRepository() - .setURI("https://github.com/halo-dev/halo-theme-pinghsu.git") - .setDirectory(tempPath.toFile()) - .call(); + .setURI("https://github.com/halo-dev/halo-theme-pinghsu.git") + .setDirectory(tempPath.toFile()) + .call(); } } diff --git a/src/test/java/run/halo/app/utils/GithubTest.java b/src/test/java/run/halo/app/utils/GithubTest.java index 983041f83..d3aae2436 100644 --- a/src/test/java/run/halo/app/utils/GithubTest.java +++ b/src/test/java/run/halo/app/utils/GithubTest.java @@ -1,5 +1,6 @@ package run.halo.app.utils; +import lombok.extern.slf4j.Slf4j; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; @@ -11,7 +12,6 @@ import run.halo.app.exception.BadRequestException; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.security.KeyManagementException; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; @@ -25,14 +25,12 @@ import java.util.Map; * @date 19-5-21 */ @Ignore +@Slf4j public class GithubTest { - private final Path tempPath; - private final static String API_URL = "https://api.github.com/repos/halo-dev/halo-admin/releases/latest"; - private final static String HALO_ADMIN_REGEX = "halo-admin-\\d+\\.\\d+(\\.\\d+)?(-\\S*)?\\.zip"; - + private final Path tempPath; private final RestTemplate restTemplate; public GithubTest() throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException, IOException { @@ -44,10 +42,10 @@ public class GithubTest { @SuppressWarnings("unchecked") public void getLatestReleaseTest() throws Throwable { ResponseEntity responseEntity = restTemplate.getForEntity(API_URL, Map.class); - System.out.println("Response: " + responseEntity); + log.debug("Response: " + responseEntity); Object assetsObject = responseEntity.getBody().get("assets"); - System.out.println("Assets class: " + assetsObject.getClass()); - System.out.println("Assets: " + assetsObject); + log.debug("Assets class: " + assetsObject.getClass()); + log.debug("Assets: " + assetsObject); if (assetsObject instanceof List) { List assets = (List) assetsObject; Map assetMap = (Map) assets.stream().filter(aAsset -> { @@ -58,18 +56,18 @@ public class GithubTest { Object name = aAssetMap.getOrDefault("name", ""); return name.toString().matches(HALO_ADMIN_REGEX); }) - .findFirst() - .orElseThrow(() -> new BadRequestException("Halo admin has no assets available")); + .findFirst() + .orElseThrow(() -> new BadRequestException("Halo admin has no assets available")); Object name = assetMap.getOrDefault("name", ""); Object browserDownloadUrl = assetMap.getOrDefault("browser_download_url", ""); // Download the assets ResponseEntity downloadResponseEntity = restTemplate.getForEntity(browserDownloadUrl.toString(), byte[].class); - System.out.println("Download response entity status: " + downloadResponseEntity.getStatusCode()); + log.debug("Download response entity status: " + downloadResponseEntity.getStatusCode()); Path downloadedPath = Files.write(tempPath.resolve(name.toString()), downloadResponseEntity.getBody()); - System.out.println("Downloaded path: " + downloadedPath.toString()); + log.debug("Downloaded path: " + downloadedPath.toString()); } } diff --git a/src/test/java/run/halo/app/utils/InetAddressTest.java b/src/test/java/run/halo/app/utils/InetAddressTest.java index cd79dba74..93f165c39 100644 --- a/src/test/java/run/halo/app/utils/InetAddressTest.java +++ b/src/test/java/run/halo/app/utils/InetAddressTest.java @@ -1,5 +1,6 @@ package run.halo.app.utils; +import lombok.extern.slf4j.Slf4j; import org.junit.Test; import java.net.InetAddress; @@ -10,14 +11,15 @@ import java.net.UnknownHostException; * * @author johnniang */ +@Slf4j public class InetAddressTest { @Test public void getMachaineAddressTest() throws UnknownHostException { InetAddress localHost = InetAddress.getLocalHost(); - System.out.println("Localhost: " + localHost.getHostAddress()); + log.debug("Localhost: " + localHost.getHostAddress()); InetAddress loopbackAddress = InetAddress.getLoopbackAddress(); - System.out.println("Loopback: " + loopbackAddress.getHostAddress()); + log.debug("Loopback: " + loopbackAddress.getHostAddress()); } } diff --git a/src/test/java/run/halo/app/utils/LocalDateTimeTest.java b/src/test/java/run/halo/app/utils/LocalDateTimeTest.java index 71c216d54..d8733f8bd 100644 --- a/src/test/java/run/halo/app/utils/LocalDateTimeTest.java +++ b/src/test/java/run/halo/app/utils/LocalDateTimeTest.java @@ -19,8 +19,8 @@ public class LocalDateTimeTest { LocalDateTime dateTime = LocalDateTime.now(); log.debug(dateTime.toString()); log.debug(dateTime.toLocalDate().toString()); - String DATE_FORMATTER = "yyyy-MM-dd-HH-mm-ss-"; - log.debug(dateTime.format(DateTimeFormatter.ofPattern(DATE_FORMATTER))); + String dateFormatter = "yyyy-MM-dd-HH-mm-ss-"; + log.debug(dateTime.format(DateTimeFormatter.ofPattern(dateFormatter))); } } diff --git a/src/test/java/run/halo/app/utils/PathTest.java b/src/test/java/run/halo/app/utils/PathTest.java index 4e0c6bf75..79b6e11b5 100644 --- a/src/test/java/run/halo/app/utils/PathTest.java +++ b/src/test/java/run/halo/app/utils/PathTest.java @@ -1,5 +1,6 @@ package run.halo.app.utils; +import lombok.extern.slf4j.Slf4j; import org.junit.Test; import java.net.URI; @@ -14,6 +15,7 @@ import java.nio.file.Paths; * @author johnniang * @date 19-5-20 */ +@Slf4j public class PathTest { @Test(expected = FileSystemNotFoundException.class) @@ -22,6 +24,6 @@ public class PathTest { URI uri = new URI(file); Path path = Paths.get(uri); - System.out.println("Path: " + path.toString()); + log.debug("Path: " + path.toString()); } } diff --git a/src/test/java/run/halo/app/utils/ReflectionUtilsTest.java b/src/test/java/run/halo/app/utils/ReflectionUtilsTest.java index c0da6be2d..5acfbe69f 100644 --- a/src/test/java/run/halo/app/utils/ReflectionUtilsTest.java +++ b/src/test/java/run/halo/app/utils/ReflectionUtilsTest.java @@ -2,7 +2,6 @@ package run.halo.app.utils; import lombok.extern.slf4j.Slf4j; import org.junit.Test; -import run.halo.app.model.dto.base.InputConverter; import run.halo.app.model.params.BaseCommentParam; import run.halo.app.model.params.JournalCommentParam; diff --git a/src/test/java/run/halo/app/utils/SlugUtilsTest.java b/src/test/java/run/halo/app/utils/SlugUtilsTest.java index 9b9cb137d..b75313ba8 100644 --- a/src/test/java/run/halo/app/utils/SlugUtilsTest.java +++ b/src/test/java/run/halo/app/utils/SlugUtilsTest.java @@ -1,5 +1,6 @@ package run.halo.app.utils; +import lombok.extern.slf4j.Slf4j; import org.junit.Assert; import org.junit.Test; @@ -9,6 +10,7 @@ import static org.hamcrest.Matchers.equalTo; * @author johnniang * @date 3/20/19 */ +@Slf4j public class SlugUtilsTest { @Test @@ -29,6 +31,6 @@ public class SlugUtilsTest { public void nullSlugTest() { String slug = SlugUtils.slug("+/~!@#$%^&*()_+"); - System.out.println("slug:" + slug); + log.debug("slug:" + slug); } } diff --git a/src/test/java/run/halo/app/utils/TimeUnitTest.java b/src/test/java/run/halo/app/utils/TimeUnitTest.java index ca60d6fb5..40dc0fd43 100644 --- a/src/test/java/run/halo/app/utils/TimeUnitTest.java +++ b/src/test/java/run/halo/app/utils/TimeUnitTest.java @@ -1,5 +1,6 @@ package run.halo.app.utils; +import lombok.extern.slf4j.Slf4j; import org.junit.Test; import java.util.concurrent.TimeUnit; @@ -10,13 +11,14 @@ import java.util.concurrent.TimeUnit; * @author johnniang * @date 19-4-29 */ +@Slf4j public class TimeUnitTest { @Test public void convertTest() { Long millis = TimeUnit.DAYS.toMillis(30); - System.out.println(millis); - System.out.println(millis.intValue()); + log.debug("" + millis); + log.debug("" + millis.intValue()); } } diff --git a/src/test/java/run/halo/app/utils/URITest.java b/src/test/java/run/halo/app/utils/URITest.java index 76509a470..ce163f90c 100644 --- a/src/test/java/run/halo/app/utils/URITest.java +++ b/src/test/java/run/halo/app/utils/URITest.java @@ -1,5 +1,6 @@ package run.halo.app.utils; +import lombok.extern.slf4j.Slf4j; import org.junit.Test; import java.net.URI; @@ -11,12 +12,13 @@ import java.net.URISyntaxException; * @author johnniang * @date 3/26/19 */ +@Slf4j public class URITest { @Test public void createURITest() throws URISyntaxException { String homeDir = System.getProperty("user.home"); URI uri = new URI(homeDir); - System.out.println(uri); + log.debug("[{}]", uri); } } diff --git a/src/test/java/run/halo/app/utils/XmlMigrateUtilsTest.java b/src/test/java/run/halo/app/utils/XmlMigrateUtilsTest.java index c8ae255a7..c876da353 100644 --- a/src/test/java/run/halo/app/utils/XmlMigrateUtilsTest.java +++ b/src/test/java/run/halo/app/utils/XmlMigrateUtilsTest.java @@ -1,6 +1,7 @@ package run.halo.app.utils; import com.alibaba.fastjson.JSONObject; +import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.Test; import org.springframework.util.ResourceUtils; import run.halo.app.handler.migrate.converter.Converter; @@ -20,25 +21,24 @@ import java.util.List; * @author guqing * @date 2020-01-18 14:02 */ +@Slf4j public class XmlMigrateUtilsTest { @Test void testXmlMigrateUtils() throws IOException, URISyntaxException { JSONObject json = readXml(); - System.out.println("WordPress blog json data:" + json); + log.debug("WordPress blog json data:" + json); Rss rss = json.getObject("rss", Rss.class); -// System.out.println(rss); } @Test void testWordPressConvert() throws IOException, URISyntaxException { JSONObject json = readXml(); Rss rss = json.getObject("rss", Rss.class); -// System.out.println("WordPress blog rss data:" + rss); Converter> converter = new WordPressConverter(); List postVoList = converter.convertFrom(rss); - System.out.println(postVoList); + log.debug("{}", postVoList); } private JSONObject readXml() throws IOException, URISyntaxException { diff --git a/src/test/java/run/halo/app/utils/YamlTest.java b/src/test/java/run/halo/app/utils/YamlTest.java index 2993c4c10..95c433912 100644 --- a/src/test/java/run/halo/app/utils/YamlTest.java +++ b/src/test/java/run/halo/app/utils/YamlTest.java @@ -1,8 +1,8 @@ package run.halo.app.utils; import org.junit.Test; -import run.halo.app.handler.theme.config.support.Group; import run.halo.app.handler.theme.config.impl.YamlThemeConfigResolverImpl; +import run.halo.app.handler.theme.config.support.Group; import java.io.IOException; import java.util.List; @@ -24,43 +24,43 @@ public class YamlTest { public void readYamlTest() throws IOException { String yaml = "sns:\n" + - " label: 社交资料设置\n" + - " items:\n" + - " rss:\n" + - " name: rss\n" + - " label: RSS\n" + - " type: radio\n" + - " default: true\n" + - " options:\n" + - " - value: true\n" + - " label: 开启\n" + - " - value: false\n" + - " label: 关闭\n" + - " twitter:\n" + - " name: twitter\n" + - " label: Twitter\n" + - " type: text\n" + - " facebook:\n" + - " name: facebook\n" + - " label: Facebook\n" + - " type: text\n" + - "style:\n" + - " label: 样式设置\n" + - " items:\n" + - " icon:\n" + - " name: icon\n" + - " label: 右上角图标\n" + - " type: text\n" + - " post_title_uppper:\n" + - " name: post_title_uppper\n" + - " label: 文章标题大写\n" + - " type: radio\n" + - " default: true\n" + - " options:\n" + - " - value: true\n" + - " label: 开启\n" + - " - value: false\n" + - " label: 关闭"; + " label: 社交资料设置\n" + + " items:\n" + + " rss:\n" + + " name: rss\n" + + " label: RSS\n" + + " type: radio\n" + + " default: true\n" + + " options:\n" + + " - value: true\n" + + " label: 开启\n" + + " - value: false\n" + + " label: 关闭\n" + + " twitter:\n" + + " name: twitter\n" + + " label: Twitter\n" + + " type: text\n" + + " facebook:\n" + + " name: facebook\n" + + " label: Facebook\n" + + " type: text\n" + + "style:\n" + + " label: 样式设置\n" + + " items:\n" + + " icon:\n" + + " name: icon\n" + + " label: 右上角图标\n" + + " type: text\n" + + " post_title_uppper:\n" + + " name: post_title_uppper\n" + + " label: 文章标题大写\n" + + " type: radio\n" + + " default: true\n" + + " options:\n" + + " - value: true\n" + + " label: 开启\n" + + " - value: false\n" + + " label: 关闭"; List groups = resolver.resolve(yaml); @@ -72,50 +72,50 @@ public class YamlTest { @Test public void readAnotherYamlTest() throws IOException { String yaml = "sns:\n" + - " label: 社交资料设置\n" + - " items:\n" + - " - name: rss\n" + - " label: RSS\n" + - " type: radio\n" + - " default: true\n" + - " options:\n" + - " - value: true\n" + - " label: 开启\n" + - " - value: false\n" + - " label: 关闭\n" + - " - name: twitter\n" + - " label: Twitter\n" + - " type: text\n" + - " - name: facebook\n" + - " label: Facebook\n" + - " type: text\n" + - " - name: instagram\n" + - " label: Instagram\n" + - " type: text\n" + - "style:\n" + - " label: 样式设置\n" + - " items:\n" + - " - name: icon\n" + - " label: 右上角图标\n" + - " type: text\n" + - " - name: post_title_uppper\n" + - " label: 文章标题大写\n" + - " type: radio\n" + - " default: true\n" + - " options:\n" + - " - value: true\n" + - " label: 开启\n" + - " - value: false\n" + - " label: 关闭\n" + - " - name: blog_title_uppper\n" + - " label: 博客标题大写\n" + - " type: radio\n" + - " default: true\n" + - " options:\n" + - " - value: true\n" + - " label: 开启\n" + - " - value: false\n" + - " label: 关闭\n"; + " label: 社交资料设置\n" + + " items:\n" + + " - name: rss\n" + + " label: RSS\n" + + " type: radio\n" + + " default: true\n" + + " options:\n" + + " - value: true\n" + + " label: 开启\n" + + " - value: false\n" + + " label: 关闭\n" + + " - name: twitter\n" + + " label: Twitter\n" + + " type: text\n" + + " - name: facebook\n" + + " label: Facebook\n" + + " type: text\n" + + " - name: instagram\n" + + " label: Instagram\n" + + " type: text\n" + + "style:\n" + + " label: 样式设置\n" + + " items:\n" + + " - name: icon\n" + + " label: 右上角图标\n" + + " type: text\n" + + " - name: post_title_uppper\n" + + " label: 文章标题大写\n" + + " type: radio\n" + + " default: true\n" + + " options:\n" + + " - value: true\n" + + " label: 开启\n" + + " - value: false\n" + + " label: 关闭\n" + + " - name: blog_title_uppper\n" + + " label: 博客标题大写\n" + + " type: radio\n" + + " default: true\n" + + " options:\n" + + " - value: true\n" + + " label: 开启\n" + + " - value: false\n" + + " label: 关闭\n"; List groups = resolver.resolve(yaml); @@ -128,50 +128,50 @@ public class YamlTest { @Test public void convertYamlTest() throws IOException { String yaml = "- name: sns\n" + - " label: 社交资料设置\n" + - " items:\n" + - " - name: rss\n" + - " label: RSS\n" + - " type: radio\n" + - " default: true\n" + - " options:\n" + - " - value: true\n" + - " label: 开启\n" + - " - value: false\n" + - " label: 关闭\n" + - " - name: twitter\n" + - " label: Twitter\n" + - " type: text\n" + - " - name: facebook\n" + - " label: Facebook\n" + - " type: text\n" + - " - name: instagram\n" + - " label: Instagram\n" + - " type: text\n" + - "- name: style\n" + - " label: 样式设置\n" + - " items:\n" + - " - name: icon\n" + - " label: 右上角图标\n" + - " type: text\n" + - " - name: post_title_uppper\n" + - " label: 文章标题大写\n" + - " type: radio\n" + - " default: true\n" + - " options:\n" + - " - value: true\n" + - " label: 开启\n" + - " - value: false\n" + - " label: 关闭\n" + - " - name: blog_title_uppper\n" + - " label: 博客标题大写\n" + - " type: radio\n" + - " default: true\n" + - " options:\n" + - " - value: true\n" + - " label: 开启\n" + - " - value: false\n" + - " label: 关闭"; + " label: 社交资料设置\n" + + " items:\n" + + " - name: rss\n" + + " label: RSS\n" + + " type: radio\n" + + " default: true\n" + + " options:\n" + + " - value: true\n" + + " label: 开启\n" + + " - value: false\n" + + " label: 关闭\n" + + " - name: twitter\n" + + " label: Twitter\n" + + " type: text\n" + + " - name: facebook\n" + + " label: Facebook\n" + + " type: text\n" + + " - name: instagram\n" + + " label: Instagram\n" + + " type: text\n" + + "- name: style\n" + + " label: 样式设置\n" + + " items:\n" + + " - name: icon\n" + + " label: 右上角图标\n" + + " type: text\n" + + " - name: post_title_uppper\n" + + " label: 文章标题大写\n" + + " type: radio\n" + + " default: true\n" + + " options:\n" + + " - value: true\n" + + " label: 开启\n" + + " - value: false\n" + + " label: 关闭\n" + + " - name: blog_title_uppper\n" + + " label: 博客标题大写\n" + + " type: radio\n" + + " default: true\n" + + " options:\n" + + " - value: true\n" + + " label: 开启\n" + + " - value: false\n" + + " label: 关闭"; List groups = resolver.resolve(yaml); diff --git a/src/test/resources/wordpressdemo.xml b/src/test/resources/wordpressdemo.xml index ec965732e..c6fce1486 100644 --- a/src/test/resources/wordpressdemo.xml +++ b/src/test/resources/wordpressdemo.xml @@ -1,10 +1,9 @@ - WordPress Demo