diff --git a/buildSrc/build.gradle.kts b/buildSrc/build.gradle.kts index 44517a9de..e51c4b4f1 100644 --- a/buildSrc/build.gradle.kts +++ b/buildSrc/build.gradle.kts @@ -10,6 +10,7 @@ repositories { dependencies { implementation("org.springframework.boot:spring-boot-gradle-plugin:${libs.versions.spring.boot.get()}") + implementation("io.spring.javaformat:spring-javaformat-gradle-plugin:${libs.versions.spring.javaformat.get()}") } gradlePlugin { diff --git a/buildSrc/src/main/kotlin/com/livk/boot/ModulePlugin.kt b/buildSrc/src/main/kotlin/com/livk/boot/ModulePlugin.kt index f45dc1a85..5b325a3b4 100644 --- a/buildSrc/src/main/kotlin/com/livk/boot/ModulePlugin.kt +++ b/buildSrc/src/main/kotlin/com/livk/boot/ModulePlugin.kt @@ -18,6 +18,7 @@ package com.livk.boot import com.livk.boot.compile.CompileArgsPlugin +import io.spring.javaformat.gradle.SpringJavaFormatPlugin import org.gradle.api.Plugin import org.gradle.api.Project @@ -28,5 +29,6 @@ class ModulePlugin : Plugin { override fun apply(project: Project) { project.pluginManager.apply(CompileArgsPlugin::class.java) project.pluginManager.apply(CorePlugin::class.java) + project.pluginManager.apply(SpringJavaFormatPlugin::class.java) } } diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 2efc4fb16..1b3b1e865 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -39,6 +39,7 @@ jexl3 = "3.3" mvel2 = "2.5.0.Final" disruptor = "4.0.0" spring-asciidoctor = "0.0.7" +spring-javaformat = "0.0.40" [libraries] spring-boot-admin-dependencies = { group = "de.codecentric", name = "spring-boot-admin-dependencies", version.ref = "spring-admin" } @@ -116,3 +117,4 @@ spring-boot = { id = "org.springframework.boot", version.ref = "spring-boot" } kotlin-jvm = { id = "org.jetbrains.kotlin.jvm", version.ref = "kotlin" } asciidoctor-jvm = { id = "org.asciidoctor.jvm.convert", version.ref = "asciidoctor-jvm" } google-protobuf = { id = "com.google.protobuf", version.ref = "protobuf-plugins" } +spring-javaformat = { id = "io.spring.javaformat", version.ref = "spring-javaformat" } diff --git a/spring-auto-service/src/main/java/com/livk/auto/service/annotation/SpringAutoService.java b/spring-auto-service/src/main/java/com/livk/auto/service/annotation/SpringAutoService.java index 3d2d79a3b..d0e07e44b 100644 --- a/spring-auto-service/src/main/java/com/livk/auto/service/annotation/SpringAutoService.java +++ b/spring-auto-service/src/main/java/com/livk/auto/service/annotation/SpringAutoService.java @@ -30,10 +30,12 @@ @Retention(RetentionPolicy.SOURCE) @Target(ElementType.TYPE) public @interface SpringAutoService { + /** - * Annotation for automatic assembly, default org.springframework.boot.autoconfigure.AutoConfiguration - * + * Annotation for automatic assembly, default + * org.springframework.boot.autoconfigure.AutoConfiguration * @return class */ Class value() default Annotation.class; + } diff --git a/spring-auto-service/src/main/java/com/livk/auto/service/annotation/SpringFactories.java b/spring-auto-service/src/main/java/com/livk/auto/service/annotation/SpringFactories.java index 80228fd67..9285e5624 100644 --- a/spring-auto-service/src/main/java/com/livk/auto/service/annotation/SpringFactories.java +++ b/spring-auto-service/src/main/java/com/livk/auto/service/annotation/SpringFactories.java @@ -30,18 +30,17 @@ @Retention(RetentionPolicy.SOURCE) @Target(ElementType.TYPE) public @interface SpringFactories { + /** - * 指定spring.factories文件生成接口 - * 如当前类仅有一个接口,则可以自动推断 - * + * 指定spring.factories文件生成接口 如当前类仅有一个接口,则可以自动推断 * @return class */ Class value() default Void.class; /** * 将spring.factories文件调整至aot.factories - * * @return the boolean */ boolean aot() default false; + } diff --git a/spring-auto-service/src/main/java/com/livk/auto/service/processor/CustomizeAbstractProcessor.java b/spring-auto-service/src/main/java/com/livk/auto/service/processor/CustomizeAbstractProcessor.java index a2b9f1b99..986deca81 100644 --- a/spring-auto-service/src/main/java/com/livk/auto/service/processor/CustomizeAbstractProcessor.java +++ b/spring-auto-service/src/main/java/com/livk/auto/service/processor/CustomizeAbstractProcessor.java @@ -88,14 +88,11 @@ public SourceVersion getSupportedSourceVersion() { @Override public Set getSupportedAnnotationTypes() { - return getSupportedAnnotation().stream() - .map(Class::getName) - .collect(Collectors.toSet()); + return getSupportedAnnotation().stream().map(Class::getName).collect(Collectors.toSet()); } /** * Set supported annotations - * * @return Set class */ protected abstract Set> getSupportedAnnotation(); @@ -104,7 +101,8 @@ public Set getSupportedAnnotationTypes() { public boolean process(Set annotations, RoundEnvironment roundEnv) { if (roundEnv.processingOver()) { generateConfigFiles(); - } else { + } + else { processAnnotations(annotations, roundEnv); } return false; @@ -117,15 +115,13 @@ public boolean process(Set annotations, RoundEnvironment /** * 处理注解 - * * @param annotations annotations - * @param roundEnv roundEnv + * @param roundEnv roundEnv */ protected abstract void processAnnotations(Set annotations, RoundEnvironment roundEnv); /** * buffered reader. - * * @param fileObject the file object * @return the buffered reader * @throws IOException the io exception @@ -136,7 +132,6 @@ protected BufferedReader bufferedReader(FileObject fileObject) throws IOExceptio /** * buffered writer. - * * @param fileObject the file object * @return the buffered writer * @throws IOException the io exception @@ -144,4 +139,5 @@ protected BufferedReader bufferedReader(FileObject fileObject) throws IOExceptio protected BufferedWriter bufferedWriter(FileObject fileObject) throws IOException { return new BufferedWriter(fileObject.openWriter()); } + } diff --git a/spring-auto-service/src/main/java/com/livk/auto/service/processor/SpringAutoServiceProcessor.java b/spring-auto-service/src/main/java/com/livk/auto/service/processor/SpringAutoServiceProcessor.java index 6c6eb98d6..691147fb3 100644 --- a/spring-auto-service/src/main/java/com/livk/auto/service/processor/SpringAutoServiceProcessor.java +++ b/spring-auto-service/src/main/java/com/livk/auto/service/processor/SpringAutoServiceProcessor.java @@ -55,7 +55,8 @@ public class SpringAutoServiceProcessor extends CustomizeAbstractProcessor { private static final String LOCATION = "META-INF/spring/%s.imports"; - private final SetMultimap importsMap = Multimaps.synchronizedSetMultimap(LinkedHashMultimap.create()); + private final SetMultimap importsMap = Multimaps + .synchronizedSetMultimap(LinkedHashMultimap.create()); @Override protected Set> getSupportedAnnotation() { @@ -71,11 +72,11 @@ protected void generateConfigFiles() { Set exitImports = this.read(resource); Set allImports = Stream.concat(exitImports.stream(), importsMap.get(providerInterface).stream()) .collect(Collectors.toSet()); - FileObject fileObject = - filer.createResource(StandardLocation.CLASS_OUTPUT, "", resourceFile); + FileObject fileObject = filer.createResource(StandardLocation.CLASS_OUTPUT, "", resourceFile); this.writeFile(allImports, fileObject); - } catch (IOException e) { + } + catch (IOException e) { throw new RuntimeException(e); } } @@ -97,24 +98,21 @@ private TypeElement AutoConfigurationElement() { /** * 从文件读取配置 - * * @param fileObject 文件信息 * @return set className */ private Set read(FileObject fileObject) { try (BufferedReader reader = bufferedReader(fileObject)) { - return reader.lines() - .map(String::trim) - .collect(Collectors.toUnmodifiableSet()); - } catch (Exception ignored) { + return reader.lines().map(String::trim).collect(Collectors.toUnmodifiableSet()); + } + catch (Exception ignored) { return Collections.emptySet(); } } /** * 将配置信息写入到文件 - * - * @param services 实现类信息 + * @param services 实现类信息 * @param fileObject 文件信息 */ private void writeFile(Collection services, FileObject fileObject) throws IOException { @@ -126,4 +124,5 @@ private void writeFile(Collection services, FileObject fileObject) throw writer.flush(); } } + } diff --git a/spring-auto-service/src/main/java/com/livk/auto/service/processor/SpringFactoriesProcessor.java b/spring-auto-service/src/main/java/com/livk/auto/service/processor/SpringFactoriesProcessor.java index a304dd633..ae6b7348c 100644 --- a/spring-auto-service/src/main/java/com/livk/auto/service/processor/SpringFactoriesProcessor.java +++ b/spring-auto-service/src/main/java/com/livk/auto/service/processor/SpringFactoriesProcessor.java @@ -53,9 +53,11 @@ public class SpringFactoriesProcessor extends CustomizeAbstractProcessor { private static final String AOT_LOCATION = "META-INF/spring/aot.factories"; - private final SetMultimap springFactoriesMap = Multimaps.synchronizedSetMultimap(LinkedHashMultimap.create()); + private final SetMultimap springFactoriesMap = Multimaps + .synchronizedSetMultimap(LinkedHashMultimap.create()); - private final SetMultimap aotFactoriesMap = Multimaps.synchronizedSetMultimap(LinkedHashMultimap.create()); + private final SetMultimap aotFactoriesMap = Multimaps + .synchronizedSetMultimap(LinkedHashMultimap.create()); @Override protected Set> getSupportedAnnotation() { @@ -76,11 +78,11 @@ private void generateConfigFiles(Multimap factoriesMap, String l for (Map.Entry entry : factoriesMap.entries()) { allImportMap.put(entry.getKey(), entry.getValue()); } - FileObject fileObject = - filer.createResource(StandardLocation.CLASS_OUTPUT, "", location); + FileObject fileObject = filer.createResource(StandardLocation.CLASS_OUTPUT, "", location); this.writeFile(allImportMap.asMap(), fileObject); - } catch (IOException e) { + } + catch (IOException e) { throw new RuntimeException(e); } } @@ -99,7 +101,8 @@ protected void processAnnotations(Set annotations, RoundE String serviceImpl = TypeElements.getBinaryName((TypeElement) element); if (aot) { aotFactoriesMap.put(provider, serviceImpl); - } else { + } + else { springFactoriesMap.put(provider, serviceImpl); } } @@ -120,7 +123,6 @@ private TypeElement fromInterface(Element element) { /** * 从文件读取某个接口的配置 - * * @param fileObject 文件信息 * @return set className */ @@ -135,18 +137,19 @@ private Multimap read(FileObject fileObject) { providers.putAll(factoryTypeName, Arrays.asList(factoryImplementationNames)); } return providers; - } catch (Exception e) { + } + catch (Exception e) { return LinkedHashMultimap.create(); } } /** * 将配置信息写入到文件 - * * @param allImportMap 供应商接口及实现类信息 - * @param fileObject 文件信息 + * @param fileObject 文件信息 */ - private void writeFile(Map> allImportMap, FileObject fileObject) throws IOException { + private void writeFile(Map> allImportMap, FileObject fileObject) + throws IOException { try (BufferedWriter writer = bufferedWriter(fileObject)) { for (Map.Entry> entry : allImportMap.entrySet()) { String providerInterface = entry.getKey(); @@ -169,4 +172,5 @@ private void writeFile(Map> allImportMap, F writer.flush(); } } + } diff --git a/spring-auto-service/src/main/java/com/livk/auto/service/processor/TypeElements.java b/spring-auto-service/src/main/java/com/livk/auto/service/processor/TypeElements.java index 265765a6e..79335294f 100644 --- a/spring-auto-service/src/main/java/com/livk/auto/service/processor/TypeElements.java +++ b/spring-auto-service/src/main/java/com/livk/auto/service/processor/TypeElements.java @@ -36,11 +36,10 @@ class TypeElements { /** * Gets annotation attributes. - * - * @param the type parameter - * @param element the element + * @param the type parameter + * @param element the element * @param targetClass the target class - * @param key the key + * @param key the key * @return the annotation attributes */ public Optional getAnnotationAttributes(Element element, Class targetClass, String key) { @@ -51,13 +50,11 @@ public Optional getAnnotationAttributes(Element element, Class< .entrySet() .stream() .filter(entry -> entry.getValue() != null) - .collect(Collectors.toMap(entry -> entry.getKey().getSimpleName().toString(), - Map.Entry::getValue)); - return Optional.ofNullable(elementValues.get(key)) - .map(annotationValue -> { - DeclaredType declaredType = (DeclaredType) annotationValue.getValue(); - return (TypeElement) declaredType.asElement(); - }); + .collect(Collectors.toMap(entry -> entry.getKey().getSimpleName().toString(), Map.Entry::getValue)); + return Optional.ofNullable(elementValues.get(key)).map(annotationValue -> { + DeclaredType declaredType = (DeclaredType) annotationValue.getValue(); + return (TypeElement) declaredType.asElement(); + }); } } throw new IllegalArgumentException(element + " not has annotation:" + targetClass); @@ -65,7 +62,6 @@ public Optional getAnnotationAttributes(Element element, Class< /** * Gets binary name. - * * @param element the element * @return the binary name */ @@ -84,4 +80,5 @@ private String getBinaryNameImpl(TypeElement element, String className) { } return getBinaryNameImpl((TypeElement) enclosingElement, enclosingElement.getSimpleName() + "$" + className); } + } diff --git a/spring-auto-service/src/test/java/com/livk/auto/service/processor/EnableAuto.java b/spring-auto-service/src/test/java/com/livk/auto/service/processor/EnableAuto.java index 8838bfccd..0ba1401a6 100644 --- a/spring-auto-service/src/test/java/com/livk/auto/service/processor/EnableAuto.java +++ b/spring-auto-service/src/test/java/com/livk/auto/service/processor/EnableAuto.java @@ -28,4 +28,5 @@ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface EnableAuto { + } diff --git a/spring-auto-service/src/test/java/com/livk/auto/service/processor/SpringAutoContext.java b/spring-auto-service/src/test/java/com/livk/auto/service/processor/SpringAutoContext.java index 78be9dd10..9ab3b0566 100644 --- a/spring-auto-service/src/test/java/com/livk/auto/service/processor/SpringAutoContext.java +++ b/spring-auto-service/src/test/java/com/livk/auto/service/processor/SpringAutoContext.java @@ -24,4 +24,5 @@ */ @SpringAutoService(EnableAuto.class) public class SpringAutoContext { + } diff --git a/spring-auto-service/src/test/java/com/livk/auto/service/processor/SpringAutoServiceProcessorTest.java b/spring-auto-service/src/test/java/com/livk/auto/service/processor/SpringAutoServiceProcessorTest.java index b02e013ec..944b9d6cf 100644 --- a/spring-auto-service/src/test/java/com/livk/auto/service/processor/SpringAutoServiceProcessorTest.java +++ b/spring-auto-service/src/test/java/com/livk/auto/service/processor/SpringAutoServiceProcessorTest.java @@ -47,9 +47,7 @@ public void testEnableAuto() { private void compile(Class type, String annotationName) { SpringAutoServiceProcessor serviceProcessor = new SpringAutoServiceProcessor(); SourceFile sourceFile = SourceFile.forTestClass(type); - TestCompiler testCompiler = TestCompiler.forSystem() - .withProcessors(serviceProcessor) - .withSources(sourceFile); + TestCompiler testCompiler = TestCompiler.forSystem().withProcessors(serviceProcessor).withSources(sourceFile); testCompiler.compile(compiled -> { try { Enumeration resources = compiled.getClassLoader() @@ -61,11 +59,11 @@ private void compile(Class type, String annotationName) { configList.addAll(Arrays.stream(arr).map(String::trim).toList()); } Assertions.assertTrue(configList.contains(type.getName())); - } catch (IOException e) { + } + catch (IOException e) { throw new RuntimeException(e); } }); } - } diff --git a/spring-auto-service/src/test/java/com/livk/auto/service/processor/SpringContext.java b/spring-auto-service/src/test/java/com/livk/auto/service/processor/SpringContext.java index 128cf5938..242a232ee 100644 --- a/spring-auto-service/src/test/java/com/livk/auto/service/processor/SpringContext.java +++ b/spring-auto-service/src/test/java/com/livk/auto/service/processor/SpringContext.java @@ -24,4 +24,5 @@ */ @SpringAutoService public class SpringContext { + } diff --git a/spring-auto-service/src/test/java/com/livk/auto/service/processor/SpringFactoriesProcessorTest.java b/spring-auto-service/src/test/java/com/livk/auto/service/processor/SpringFactoriesProcessorTest.java index 346168bc6..900ee8913 100644 --- a/spring-auto-service/src/test/java/com/livk/auto/service/processor/SpringFactoriesProcessorTest.java +++ b/spring-auto-service/src/test/java/com/livk/auto/service/processor/SpringFactoriesProcessorTest.java @@ -38,20 +38,16 @@ class SpringFactoriesProcessorTest { @Test public void test() { - compile(SpringFactoryServiceImpl.class, SpringFactoryService.class, - SpringFactoryServiceImpl.class.getName()); + compile(SpringFactoryServiceImpl.class, SpringFactoryService.class, SpringFactoryServiceImpl.class.getName()); } private void compile(Class type, Class factoryClass, String factoryClassImplName) { SpringFactoriesProcessor serviceProcessor = new SpringFactoriesProcessor(); SourceFile sourceFile = SourceFile.forTestClass(type); - TestCompiler testCompiler = TestCompiler.forSystem() - .withProcessors(serviceProcessor) - .withSources(sourceFile); + TestCompiler testCompiler = TestCompiler.forSystem().withProcessors(serviceProcessor).withSources(sourceFile); testCompiler.compile(compiled -> { try { - Enumeration resources = compiled.getClassLoader() - .getResources("META-INF/spring.factories"); + Enumeration resources = compiled.getClassLoader().getResources("META-INF/spring.factories"); Properties pro = new Properties(); for (URL url : Collections.list(resources)) { InputStream inputStream = new UrlResource(url).getInputStream(); @@ -61,9 +57,11 @@ private void compile(Class type, Class factoryClass, String factoryClassIm } Assertions.assertTrue(pro.containsKey(factoryClass.getName())); Assertions.assertEquals(factoryClassImplName, pro.get(factoryClass.getName())); - } catch (IOException e) { + } + catch (IOException e) { throw new RuntimeException(e); } }); } + } diff --git a/spring-auto-service/src/test/java/com/livk/auto/service/processor/SpringFactoryService.java b/spring-auto-service/src/test/java/com/livk/auto/service/processor/SpringFactoryService.java index fda1e68ef..a640f5070 100644 --- a/spring-auto-service/src/test/java/com/livk/auto/service/processor/SpringFactoryService.java +++ b/spring-auto-service/src/test/java/com/livk/auto/service/processor/SpringFactoryService.java @@ -21,4 +21,5 @@ * @author livk */ public interface SpringFactoryService { + } diff --git a/spring-boot-example/spring-admin/spring-admin-client/src/main/java/com/livk/admin/client/SpringClientApp.java b/spring-boot-example/spring-admin/spring-admin-client/src/main/java/com/livk/admin/client/SpringClientApp.java index 6c5d05945..55612c88e 100644 --- a/spring-boot-example/spring-admin/spring-admin-client/src/main/java/com/livk/admin/client/SpringClientApp.java +++ b/spring-boot-example/spring-admin/spring-admin-client/src/main/java/com/livk/admin/client/SpringClientApp.java @@ -29,7 +29,9 @@ */ @SpringBootApplication public class SpringClientApp { + public static void main(String[] args) { SpringLauncher.run(args); } + } diff --git a/spring-boot-example/spring-admin/spring-admin-server/src/main/java/com/livk/admin/server/SpringServerApp.java b/spring-boot-example/spring-admin/spring-admin-server/src/main/java/com/livk/admin/server/SpringServerApp.java index 32440b04e..d9f0ce6d2 100644 --- a/spring-boot-example/spring-admin/spring-admin-server/src/main/java/com/livk/admin/server/SpringServerApp.java +++ b/spring-boot-example/spring-admin/spring-admin-server/src/main/java/com/livk/admin/server/SpringServerApp.java @@ -31,7 +31,9 @@ @EnableAdminServer @SpringBootApplication public class SpringServerApp { + public static void main(String[] args) { SpringLauncher.run(args); } + } diff --git a/spring-boot-example/spring-admin/spring-admin-server/src/main/java/com/livk/admin/server/config/AdminRedisConfig.java b/spring-boot-example/spring-admin/spring-admin-server/src/main/java/com/livk/admin/server/config/AdminRedisConfig.java index 5f410a7e4..98e26b9ab 100644 --- a/spring-boot-example/spring-admin/spring-admin-server/src/main/java/com/livk/admin/server/config/AdminRedisConfig.java +++ b/spring-boot-example/spring-admin/spring-admin-server/src/main/java/com/livk/admin/server/config/AdminRedisConfig.java @@ -44,20 +44,24 @@ public class AdminRedisConfig { @Bean public ReactiveRedisOps reactiveRedisOps(AdminServerProperties adminServerProperties, - ReactiveRedisConnectionFactory redisConnectionFactory) { + ReactiveRedisConnectionFactory redisConnectionFactory) { JsonMapper mapper = JsonMapper.builder() .addModule(new AdminServerModule(adminServerProperties.getMetadataKeysToSanitize())) .addModule(new JavaTimeModule()) .build(); - Jackson2JsonRedisSerializer hashKeySerializer = new Jackson2JsonRedisSerializer<>(mapper, InstanceId.class); + Jackson2JsonRedisSerializer hashKeySerializer = new Jackson2JsonRedisSerializer<>(mapper, + InstanceId.class); CollectionType collectionType = TypeFactoryUtils.collectionType(InstanceEvent.class); - Jackson2JsonRedisSerializer> hashValueSerializer = new Jackson2JsonRedisSerializer<>(mapper, collectionType); - RedisSerializationContext serializationContext = RedisSerializationContext. - newSerializationContext() + Jackson2JsonRedisSerializer> hashValueSerializer = new Jackson2JsonRedisSerializer<>(mapper, + collectionType); + RedisSerializationContext serializationContext = RedisSerializationContext + .newSerializationContext() .key(RedisSerializer.string()) .value(JacksonSerializerUtils.json()) .hashKey(hashKeySerializer) - .hashValue(hashValueSerializer).build(); + .hashValue(hashValueSerializer) + .build(); return new ReactiveRedisOps(redisConnectionFactory, serializationContext); } + } diff --git a/spring-boot-example/spring-admin/spring-admin-server/src/main/java/com/livk/admin/server/config/CustomNotifier.java b/spring-boot-example/spring-admin/spring-admin-server/src/main/java/com/livk/admin/server/config/CustomNotifier.java index 9190812b2..c06ee8539 100644 --- a/spring-boot-example/spring-admin/spring-admin-server/src/main/java/com/livk/admin/server/config/CustomNotifier.java +++ b/spring-boot-example/spring-admin/spring-admin-server/src/main/java/com/livk/admin/server/config/CustomNotifier.java @@ -48,10 +48,11 @@ protected Mono doNotify(@NonNull InstanceEvent event, @NonNull Instance in return Mono.fromRunnable(() -> { if (event instanceof InstanceStatusChangedEvent statusChangedEvent) { log.info("Instance {} ({}) is {}", instance.getRegistration().getName(), event.getInstance(), - statusChangedEvent.getStatusInfo().getStatus()); - } else { + statusChangedEvent.getStatusInfo().getStatus()); + } + else { log.info("Instance {} ({}) {}", instance.getRegistration().getName(), event.getInstance(), - event.getType()); + event.getType()); } }); } diff --git a/spring-boot-example/spring-admin/spring-admin-server/src/main/java/com/livk/admin/server/config/RedisEventStore.java b/spring-boot-example/spring-admin/spring-admin-server/src/main/java/com/livk/admin/server/config/RedisEventStore.java index 6a64781b6..dec196ab4 100644 --- a/spring-boot-example/spring-admin/spring-admin-server/src/main/java/com/livk/admin/server/config/RedisEventStore.java +++ b/spring-boot-example/spring-admin/spring-admin-server/src/main/java/com/livk/admin/server/config/RedisEventStore.java @@ -47,6 +47,7 @@ public class RedisEventStore extends InstanceEventPublisher implements InstanceE private static final Comparator byTimestampAndIdAndVersion = comparing(InstanceEvent::getTimestamp) .thenComparing(InstanceEvent::getInstance) .thenComparing(InstanceEvent::getVersion); + private final ReactiveHashOperations> hashOperations; public RedisEventStore(ReactiveRedisOps redisOps) { @@ -80,4 +81,5 @@ public Mono append(List events) { return hashOperations.put(INSTANCE_EVENT_KEY, id.getValue(), events) .then(Mono.fromRunnable(() -> this.publish(events))); } + } diff --git a/spring-boot-example/spring-admin/spring-admin-server/src/main/java/com/livk/admin/server/config/SecurityConfig.java b/spring-boot-example/spring-admin/spring-admin-server/src/main/java/com/livk/admin/server/config/SecurityConfig.java index ae5592298..d794a58fb 100644 --- a/spring-boot-example/spring-admin/spring-admin-server/src/main/java/com/livk/admin/server/config/SecurityConfig.java +++ b/spring-boot-example/spring-admin/spring-admin-server/src/main/java/com/livk/admin/server/config/SecurityConfig.java @@ -42,12 +42,13 @@ public class SecurityConfig { @Bean - public SecurityFilterChain securityFilterChain(HttpSecurity http, - AdminServerProperties adminServer) throws Exception { + public SecurityFilterChain securityFilterChain(HttpSecurity http, AdminServerProperties adminServer) + throws Exception { SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler(); successHandler.setTargetUrlParameter("redirectTo"); successHandler.setDefaultTargetUrl(adminServer.path("/")); - return http.authorizeHttpRequests(registry -> registry.requestMatchers(adminServer.path("/assets/**")) + return http + .authorizeHttpRequests(registry -> registry.requestMatchers(adminServer.path("/assets/**")) .permitAll() .requestMatchers(adminServer.path("/variables.css")) .permitAll() @@ -60,14 +61,16 @@ public SecurityFilterChain securityFilterChain(HttpSecurity http, .dispatcherTypeMatchers(DispatcherType.ASYNC) .permitAll() .anyRequest() - .authenticated()).formLogin(configurer -> configurer.loginPage(adminServer.path("/login")) - .successHandler(successHandler)) + .authenticated()) + .formLogin(configurer -> configurer.loginPage(adminServer.path("/login")).successHandler(successHandler)) .httpBasic(Customizer.withDefaults()) .csrf(configurer -> configurer.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()) - .ignoringRequestMatchers(new AntPathRequestMatcher(adminServer.path("/instances"), HttpMethod.POST.toString()), - new AntPathRequestMatcher(adminServer.path("/instances/*"), HttpMethod.DELETE.toString()), - new AntPathRequestMatcher(adminServer.path("/actuator/**")))) - .rememberMe(configurer -> configurer.key(UUID.randomUUID().toString()) - .tokenValiditySeconds(1209600)).build(); + .ignoringRequestMatchers( + new AntPathRequestMatcher(adminServer.path("/instances"), HttpMethod.POST.toString()), + new AntPathRequestMatcher(adminServer.path("/instances/*"), HttpMethod.DELETE.toString()), + new AntPathRequestMatcher(adminServer.path("/actuator/**")))) + .rememberMe(configurer -> configurer.key(UUID.randomUUID().toString()).tokenValiditySeconds(1209600)) + .build(); } + } diff --git a/spring-boot-example/spring-admin/spring-admin-server/src/main/java/com/livk/admin/server/converter/RegistrationHttpMessageConverters.java b/spring-boot-example/spring-admin/spring-admin-server/src/main/java/com/livk/admin/server/converter/RegistrationHttpMessageConverters.java index d6a22fd6e..2b7cdd665 100644 --- a/spring-boot-example/spring-admin/spring-admin-server/src/main/java/com/livk/admin/server/converter/RegistrationHttpMessageConverters.java +++ b/spring-boot-example/spring-admin/spring-admin-server/src/main/java/com/livk/admin/server/converter/RegistrationHttpMessageConverters.java @@ -40,7 +40,9 @@ public RegistrationHttpMessageConverters(AdminServerProperties adminServerProper private static HttpMessageConverter jacksonHttpMessageConverter(AdminServerProperties adminServerProperties) { MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); - converter.getObjectMapper().registerModule(new AdminServerModule(adminServerProperties.getMetadataKeysToSanitize())); + converter.getObjectMapper() + .registerModule(new AdminServerModule(adminServerProperties.getMetadataKeysToSanitize())); return converter; } + } diff --git a/spring-boot-example/spring-authorization-server/auth-client/src/main/java/com/livk/auth/client/config/WebClientConfig.java b/spring-boot-example/spring-authorization-server/auth-client/src/main/java/com/livk/auth/client/config/WebClientConfig.java index 29b74a3c7..746a4cbe2 100644 --- a/spring-boot-example/spring-authorization-server/auth-client/src/main/java/com/livk/auth/client/config/WebClientConfig.java +++ b/spring-boot-example/spring-authorization-server/auth-client/src/main/java/com/livk/auth/client/config/WebClientConfig.java @@ -35,20 +35,23 @@ public class WebClientConfig { @Bean - WebClient webClient(OAuth2AuthorizedClientManager authorizedClientManager, - WebClient.Builder builder) { - ServletOAuth2AuthorizedClientExchangeFilterFunction oauth2Client = new ServletOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager); + WebClient webClient(OAuth2AuthorizedClientManager authorizedClientManager, WebClient.Builder builder) { + ServletOAuth2AuthorizedClientExchangeFilterFunction oauth2Client = new ServletOAuth2AuthorizedClientExchangeFilterFunction( + authorizedClientManager); return builder.apply(oauth2Client.oauth2Configuration()).build(); } @Bean OAuth2AuthorizedClientManager authorizedClientManager(ClientRegistrationRepository clientRegistrationRepository, - OAuth2AuthorizedClientRepository authorizedClientRepository) { + OAuth2AuthorizedClientRepository authorizedClientRepository) { - OAuth2AuthorizedClientProvider authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder().authorizationCode() - .refreshToken().clientCredentials().build(); - DefaultOAuth2AuthorizedClientManager authorizedClientManager = new DefaultOAuth2AuthorizedClientManager(clientRegistrationRepository, - authorizedClientRepository); + OAuth2AuthorizedClientProvider authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder() + .authorizationCode() + .refreshToken() + .clientCredentials() + .build(); + DefaultOAuth2AuthorizedClientManager authorizedClientManager = new DefaultOAuth2AuthorizedClientManager( + clientRegistrationRepository, authorizedClientRepository); authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider); return authorizedClientManager; diff --git a/spring-boot-example/spring-authorization-server/auth-client/src/main/java/com/livk/auth/client/web/AuthorizationController.java b/spring-boot-example/spring-authorization-server/auth-client/src/main/java/com/livk/auth/client/web/AuthorizationController.java index c220325df..d03d3605d 100644 --- a/spring-boot-example/spring-authorization-server/auth-client/src/main/java/com/livk/auth/client/web/AuthorizationController.java +++ b/spring-boot-example/spring-authorization-server/auth-client/src/main/java/com/livk/auth/client/web/AuthorizationController.java @@ -48,10 +48,14 @@ public AuthorizationController(WebClient webClient, @Value("${messages.base-uri} @GetMapping(value = "/authorize", params = "grant_type=authorization_code") public String[] authorizationCodeGrant( - @RegisteredOAuth2AuthorizedClient("livk-client-authorization-code") OAuth2AuthorizedClient authorizedClient) { + @RegisteredOAuth2AuthorizedClient("livk-client-authorization-code") OAuth2AuthorizedClient authorizedClient) { - return this.webClient.get().uri(this.messagesBaseUri).attributes(oauth2AuthorizedClient(authorizedClient)) - .retrieve().bodyToMono(String[].class).block(); + return this.webClient.get() + .uri(this.messagesBaseUri) + .attributes(oauth2AuthorizedClient(authorizedClient)) + .retrieve() + .bodyToMono(String[].class) + .block(); } // '/authorized' is the registered 'redirect_uri' for authorization_code @@ -60,7 +64,7 @@ public OAuth2Error authorizationFailed(HttpServletRequest request) { String errorCode = request.getParameter(OAuth2ParameterNames.ERROR); if (StringUtils.hasText(errorCode)) { return new OAuth2Error(errorCode, request.getParameter(OAuth2ParameterNames.ERROR_DESCRIPTION), - request.getParameter(OAuth2ParameterNames.ERROR_URI)); + request.getParameter(OAuth2ParameterNames.ERROR_URI)); } return new OAuth2Error("Null"); @@ -69,9 +73,12 @@ public OAuth2Error authorizationFailed(HttpServletRequest request) { @GetMapping(value = "/authorize", params = "grant_type=client_credentials") public String[] clientCredentialsGrant() { - return this.webClient.get().uri(this.messagesBaseUri) - .attributes(clientRegistrationId("livk-client-client-credentials")).retrieve() - .bodyToMono(String[].class).block(); + return this.webClient.get() + .uri(this.messagesBaseUri) + .attributes(clientRegistrationId("livk-client-client-credentials")) + .retrieve() + .bodyToMono(String[].class) + .block(); } } diff --git a/spring-boot-example/spring-authorization-server/auth-resource/src/main/java/com/livk/auth/resource/web/ResourceController.java b/spring-boot-example/spring-authorization-server/auth-resource/src/main/java/com/livk/auth/resource/web/ResourceController.java index 105900b05..5e22743b7 100644 --- a/spring-boot-example/spring-authorization-server/auth-resource/src/main/java/com/livk/auth/resource/web/ResourceController.java +++ b/spring-boot-example/spring-authorization-server/auth-resource/src/main/java/com/livk/auth/resource/web/ResourceController.java @@ -28,7 +28,7 @@ public class ResourceController { @GetMapping("/resource-livk") public String[] getMessages() { - return new String[]{"livk", "livk-spring", "livk-cloud"}; + return new String[] { "livk", "livk-spring", "livk-cloud" }; } } diff --git a/spring-boot-example/spring-authorization-server/auth-server/src/main/java/com/livk/auth/server/AuthServerApp.java b/spring-boot-example/spring-authorization-server/auth-server/src/main/java/com/livk/auth/server/AuthServerApp.java index 7bb72f2c1..7cdef7a57 100644 --- a/spring-boot-example/spring-authorization-server/auth-server/src/main/java/com/livk/auth/server/AuthServerApp.java +++ b/spring-boot-example/spring-authorization-server/auth-server/src/main/java/com/livk/auth/server/AuthServerApp.java @@ -43,4 +43,5 @@ public static void main(String[] args) { public HttpEntity hello() { return ResponseEntity.ok("hello"); } + } diff --git a/spring-boot-example/spring-authorization-server/auth-server/src/main/java/com/livk/auth/server/config/AuthorizationServerConfiguration.java b/spring-boot-example/spring-authorization-server/auth-server/src/main/java/com/livk/auth/server/config/AuthorizationServerConfiguration.java index 18329e428..5d4b5ee6c 100644 --- a/spring-boot-example/spring-authorization-server/auth-server/src/main/java/com/livk/auth/server/config/AuthorizationServerConfiguration.java +++ b/spring-boot-example/spring-authorization-server/auth-server/src/main/java/com/livk/auth/server/config/AuthorizationServerConfiguration.java @@ -72,30 +72,26 @@ public class AuthorizationServerConfiguration { @Bean @Order(Ordered.HIGHEST_PRECEDENCE) public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http, - OAuth2AuthorizationService authorizationService, - OAuth2TokenGenerator oAuth2TokenGenerator, - UserDetailsAuthenticationProvider userDetailsAuthenticationProvider) throws Exception { + OAuth2AuthorizationService authorizationService, OAuth2TokenGenerator oAuth2TokenGenerator, + UserDetailsAuthenticationProvider userDetailsAuthenticationProvider) throws Exception { OAuth2AuthorizationServerConfigurer authorizationServerConfigurer = new OAuth2AuthorizationServerConfigurer(); AuthenticationManager authenticationManager = http.getSharedObject(AuthenticationManagerBuilder.class).build(); OAuth2PasswordAuthenticationProvider passwordAuthenticationProvider = new OAuth2PasswordAuthenticationProvider( - authenticationManager, authorizationService, oAuth2TokenGenerator); + authenticationManager, authorizationService, oAuth2TokenGenerator); OAuth2SmsAuthenticationProvider smsAuthenticationProvider = new OAuth2SmsAuthenticationProvider( - authenticationManager, authorizationService, oAuth2TokenGenerator); + authenticationManager, authorizationService, oAuth2TokenGenerator); OAuth2AuthorizationServerConfigurer configurer = authorizationServerConfigurer - .tokenEndpoint( - (tokenEndpoint) -> tokenEndpoint - .accessTokenRequestConverter(accessTokenRequestConverter()) - .authenticationProvider(passwordAuthenticationProvider) - .authenticationProvider(smsAuthenticationProvider) - .accessTokenResponseHandler(new AuthenticationSuccessEventHandler()) - .errorResponseHandler(new AuthenticationFailureEventHandler()) - ) - .authorizationEndpoint(authorizationEndpoint -> - authorizationEndpoint.consentPage(SecurityConstants.CUSTOM_CONSENT_PAGE_URI)); + .tokenEndpoint((tokenEndpoint) -> tokenEndpoint.accessTokenRequestConverter(accessTokenRequestConverter()) + .authenticationProvider(passwordAuthenticationProvider) + .authenticationProvider(smsAuthenticationProvider) + .accessTokenResponseHandler(new AuthenticationSuccessEventHandler()) + .errorResponseHandler(new AuthenticationFailureEventHandler())) + .authorizationEndpoint(authorizationEndpoint -> authorizationEndpoint + .consentPage(SecurityConstants.CUSTOM_CONSENT_PAGE_URI)); http.apply(configurer); http.apply(configurer.authorizationService(authorizationService)); @@ -106,8 +102,12 @@ public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity h return http.securityMatcher(endpointsMatcher) .authenticationManager(authenticationManager) - .securityContext(contextConfigurer -> contextConfigurer.securityContextRepository(httpSessionSecurityContextRepository)) - .authorizeHttpRequests(registry -> registry.requestMatchers("/auth/**", "/actuator/**", "/css/**", "/error").permitAll().anyRequest().authenticated()) + .securityContext(contextConfigurer -> contextConfigurer + .securityContextRepository(httpSessionSecurityContextRepository)) + .authorizeHttpRequests(registry -> registry.requestMatchers("/auth/**", "/actuator/**", "/css/**", "/error") + .permitAll() + .anyRequest() + .authenticated()) .csrf(csrfConfigurer -> csrfConfigurer.ignoringRequestMatchers(endpointsMatcher)) .authenticationProvider(userDetailsAuthenticationProvider) .build(); @@ -115,7 +115,7 @@ public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity h @Bean public DaoAuthenticationProvider daoAuthenticationProvider(PasswordEncoder passwordEncoder, - UserDetailsService userDetailsService) { + UserDetailsService userDetailsService) { DaoAuthenticationProvider provider = new DaoAuthenticationProvider(); provider.setPasswordEncoder(passwordEncoder); provider.setUserDetailsService(userDetailsService); @@ -131,11 +131,9 @@ public OAuth2TokenGenerator oAuth2TokenGenerator(JWKSource registry.requestMatchers("/auth/**", "/actuator/**", "/css/**", "/error") + return http + .authorizeHttpRequests(registry -> registry.requestMatchers("/auth/**", "/actuator/**", "/css/**", "/error") .permitAll() .anyRequest() .authenticated()) - .formLogin(Customizer.withDefaults()).build(); + .formLogin(Customizer.withDefaults()) + .build(); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } + } diff --git a/spring-boot-example/spring-authorization-server/auth-server/src/main/java/com/livk/auth/server/config/JdbcConfig.java b/spring-boot-example/spring-authorization-server/auth-server/src/main/java/com/livk/auth/server/config/JdbcConfig.java index 569b6737d..f4f6f778f 100644 --- a/spring-boot-example/spring-authorization-server/auth-server/src/main/java/com/livk/auth/server/config/JdbcConfig.java +++ b/spring-boot-example/spring-authorization-server/auth-server/src/main/java/com/livk/auth/server/config/JdbcConfig.java @@ -50,7 +50,8 @@ public class JdbcConfig { @Bean public RegisteredClientRepository registeredClientRepository(JdbcTemplate jdbcTemplate) { - RegisteredClient client = RegisteredClient.withId("livk").clientId("livk-client") + RegisteredClient client = RegisteredClient.withId("livk") + .clientId("livk-client") .clientSecret(new BCryptPasswordEncoder().encode("secret")) .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC) .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_POST) @@ -81,13 +82,14 @@ public RegisteredClientRepository registeredClientRepository(JdbcTemplate jdbcTe @Bean public OAuth2AuthorizationService authorizationService(JdbcTemplate jdbcTemplate, - RegisteredClientRepository registeredClientRepository) { + RegisteredClientRepository registeredClientRepository) { return new JdbcOAuth2AuthorizationService(jdbcTemplate, registeredClientRepository); } @Bean public OAuth2AuthorizationConsentService authorizationConsentService(JdbcTemplate jdbcTemplate, - RegisteredClientRepository registeredClientRepository) { + RegisteredClientRepository registeredClientRepository) { return new JdbcOAuth2AuthorizationConsentService(jdbcTemplate, registeredClientRepository); } + } diff --git a/spring-boot-example/spring-authorization-server/auth-server/src/main/java/com/livk/auth/server/mapper/UsersMapper.java b/spring-boot-example/spring-authorization-server/auth-server/src/main/java/com/livk/auth/server/mapper/UsersMapper.java index c286f9e20..443483e66 100644 --- a/spring-boot-example/spring-authorization-server/auth-server/src/main/java/com/livk/auth/server/mapper/UsersMapper.java +++ b/spring-boot-example/spring-authorization-server/auth-server/src/main/java/com/livk/auth/server/mapper/UsersMapper.java @@ -34,4 +34,5 @@ public interface UsersMapper { @Select("select * from users") User getOne(@Param("username") String username); + } diff --git a/spring-boot-example/spring-authorization-server/auth-server/src/test/java/com/livk/auth/server/AuthServerAppTest.java b/spring-boot-example/spring-authorization-server/auth-server/src/test/java/com/livk/auth/server/AuthServerAppTest.java index e5ad07d74..db7a32e23 100644 --- a/spring-boot-example/spring-authorization-server/auth-server/src/test/java/com/livk/auth/server/AuthServerAppTest.java +++ b/spring-boot-example/spring-authorization-server/auth-server/src/test/java/com/livk/auth/server/AuthServerAppTest.java @@ -43,15 +43,11 @@ * * @author livk */ -@SpringBootTest({ - "spring.datasource.driver-class-name=org.h2.Driver", - "spring.datasource.url=jdbc:h2:mem:test", - "spring.sql.init.schema-locations[0]=classpath*:/org/springframework/security/oauth2/server/authorization/client/oauth2-registered-client-schema.sql", - "spring.sql.init.schema-locations[1]=classpath*:/org/springframework/security/oauth2/server/authorization/oauth2-authorization-consent-schema.sql", - "spring.sql.init.schema-locations[2]=classpath*:/org/springframework/security/oauth2/server/authorization/oauth2-authorization-schema.sql", - "spring.sql.init.platform=h2", - "spring.sql.init.mode=embedded" -}) +@SpringBootTest({ "spring.datasource.driver-class-name=org.h2.Driver", "spring.datasource.url=jdbc:h2:mem:test", + "spring.sql.init.schema-locations[0]=classpath*:/org/springframework/security/oauth2/server/authorization/client/oauth2-registered-client-schema.sql", + "spring.sql.init.schema-locations[1]=classpath*:/org/springframework/security/oauth2/server/authorization/oauth2-authorization-consent-schema.sql", + "spring.sql.init.schema-locations[2]=classpath*:/org/springframework/security/oauth2/server/authorization/oauth2-authorization-schema.sql", + "spring.sql.init.platform=h2", "spring.sql.init.mode=embedded" }) @AutoConfigureMockMvc class AuthServerAppTest { @@ -65,7 +61,8 @@ public void testPassword() throws Exception { params.set("username", "livk"); params.set("password", "123456"); params.set("scope", "livk.read"); - String json = mockMvc.perform(post("/oauth2/token") + String json = mockMvc + .perform(post("/oauth2/token") .header(HttpHeaders.AUTHORIZATION, "Basic " + Base64.encode("livk-client:secret")) .contentType(MediaType.MULTIPART_FORM_DATA_VALUE) .params(params)) @@ -90,7 +87,8 @@ public void testSms() throws Exception { params.set("mobile", "18664960000"); params.set("code", "123456"); params.set("scope", "livk.read"); - String json = mockMvc.perform(post("/oauth2/token") + String json = mockMvc + .perform(post("/oauth2/token") .header(HttpHeaders.AUTHORIZATION, "Basic " + Base64.encode("livk-client:secret")) .contentType(MediaType.MULTIPART_FORM_DATA_VALUE) .params(params)) @@ -107,4 +105,5 @@ public void testSms() throws Exception { assertNotNull(accessToken); assertFalse(accessToken.isBlank()); } + } diff --git a/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/AuthorizationServerAutoConfiguration.java b/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/AuthorizationServerAutoConfiguration.java index 59f8c6beb..54d5e1432 100644 --- a/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/AuthorizationServerAutoConfiguration.java +++ b/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/AuthorizationServerAutoConfiguration.java @@ -38,7 +38,8 @@ public class AuthorizationServerAutoConfiguration { @Bean public UserDetailsAuthenticationProvider userDetailsAuthenticationProvider(PasswordEncoder passwordEncoder, - ObjectProvider oauth2UserDetailsServices) { + ObjectProvider oauth2UserDetailsServices) { return new UserDetailsAuthenticationProvider(passwordEncoder, oauth2UserDetailsServices); } + } diff --git a/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/constant/SecurityConstants.java b/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/constant/SecurityConstants.java index 407063738..7b825adff 100644 --- a/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/constant/SecurityConstants.java +++ b/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/constant/SecurityConstants.java @@ -35,11 +35,11 @@ public interface SecurityConstants { String SMS = "sms"; AuthorizationGrantType GRANT_TYPE_SMS = new AuthorizationGrantType(SMS); + String PASSWORD = "password"; AuthorizationGrantType GRANT_TYPE_PASSWORD = new AuthorizationGrantType(PASSWORD); - /** * {bcrypt} 加密的特征码 */ @@ -93,4 +93,5 @@ public interface SecurityConstants { String DEFAULT_ID_SUFFIX = "}"; String ACCESS_TOKEN_REQUEST_ERROR_URI = "https://datatracker.ietf.org/doc/html/rfc6749#section-5.2"; + } diff --git a/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/converter/OAuth2BaseAuthenticationConverter.java b/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/converter/OAuth2BaseAuthenticationConverter.java index dccf8ca38..fa5a586e0 100644 --- a/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/converter/OAuth2BaseAuthenticationConverter.java +++ b/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/converter/OAuth2BaseAuthenticationConverter.java @@ -17,7 +17,6 @@ package com.livk.auth.server.common.converter; - import com.google.common.collect.Sets; import com.livk.auth.server.common.constant.SecurityConstants; import com.livk.auth.server.common.token.OAuth2BaseAuthenticationToken; @@ -42,15 +41,17 @@ import java.util.stream.Collectors; /** - *

自定义模式认证转换器

+ *

+ * 自定义模式认证转换器 + *

* * @author livk */ -public interface OAuth2BaseAuthenticationConverter extends AuthenticationConverter { +public interface OAuth2BaseAuthenticationConverter + extends AuthenticationConverter { RequestMatcher support(); - /** * 构建具体类型的token */ @@ -64,7 +65,8 @@ default Authentication convert(HttpServletRequest request) { String scope = request.getParameter(OAuth2ParameterNames.SCOPE); if (StringUtils.hasText(scope) && request.getParameterValues(OAuth2ParameterNames.SCOPE).length != 1) { - throw new OAuth2AuthenticationException(new OAuth2Error(OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.SCOPE, SecurityConstants.ACCESS_TOKEN_REQUEST_ERROR_URI)); + throw new OAuth2AuthenticationException(new OAuth2Error(OAuth2ErrorCodes.INVALID_REQUEST, + OAuth2ParameterNames.SCOPE, SecurityConstants.ACCESS_TOKEN_REQUEST_ERROR_URI)); } Set requestedScopes = Collections.emptySet(); @@ -74,12 +76,14 @@ default Authentication convert(HttpServletRequest request) { // 获取当前已经认证的客户端信息 Authentication clientPrincipal = SecurityContextHolder.getContext().getAuthentication(); - Optional.ofNullable(clientPrincipal).orElseThrow(() -> - new OAuth2AuthenticationException(new OAuth2Error(OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ErrorCodes.INVALID_CLIENT, SecurityConstants.ACCESS_TOKEN_REQUEST_ERROR_URI))); + Optional.ofNullable(clientPrincipal) + .orElseThrow(() -> new OAuth2AuthenticationException(new OAuth2Error(OAuth2ErrorCodes.INVALID_REQUEST, + OAuth2ErrorCodes.INVALID_CLIENT, SecurityConstants.ACCESS_TOKEN_REQUEST_ERROR_URI))); // 扩展信息 Map additionalParameters = BaseStreamUtils.convert(request.getParameterNames()) - .filter(Predicate.isEqual(OAuth2ParameterNames.GRANT_TYPE).negate() + .filter(Predicate.isEqual(OAuth2ParameterNames.GRANT_TYPE) + .negate() .and(Predicate.isEqual(OAuth2ParameterNames.SCOPE).negate())) .collect(Collectors.toMap(Function.identity(), request::getParameter)); diff --git a/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/converter/OAuth2PasswordAuthenticationConverter.java b/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/converter/OAuth2PasswordAuthenticationConverter.java index 29e4eb77d..c630edc59 100644 --- a/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/converter/OAuth2PasswordAuthenticationConverter.java +++ b/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/converter/OAuth2PasswordAuthenticationConverter.java @@ -17,7 +17,6 @@ package com.livk.auth.server.common.converter; - import com.livk.auth.server.common.constant.SecurityConstants; import com.livk.auth.server.common.token.OAuth2PasswordAuthenticationToken; import org.springframework.security.core.Authentication; @@ -29,21 +28,26 @@ import java.util.Set; /** - *

密码认证转换器

+ *

+ * 密码认证转换器 + *

* * @author livk */ -public class OAuth2PasswordAuthenticationConverter implements OAuth2BaseAuthenticationConverter { +public class OAuth2PasswordAuthenticationConverter + implements OAuth2BaseAuthenticationConverter { @Override public RequestMatcher support() { return request -> SecurityConstants.PASSWORD.equals(request.getParameter(OAuth2ParameterNames.GRANT_TYPE)) - && StringUtils.hasText(request.getParameter(OAuth2ParameterNames.USERNAME)) - && StringUtils.hasText(request.getParameter(OAuth2ParameterNames.PASSWORD)); + && StringUtils.hasText(request.getParameter(OAuth2ParameterNames.USERNAME)) + && StringUtils.hasText(request.getParameter(OAuth2ParameterNames.PASSWORD)); } @Override - public OAuth2PasswordAuthenticationToken buildToken(Authentication clientPrincipal, Set requestedScopes, Map additionalParameters) { + public OAuth2PasswordAuthenticationToken buildToken(Authentication clientPrincipal, Set requestedScopes, + Map additionalParameters) { return new OAuth2PasswordAuthenticationToken(clientPrincipal, requestedScopes, additionalParameters); } + } diff --git a/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/converter/OAuth2SmsAuthenticationConverter.java b/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/converter/OAuth2SmsAuthenticationConverter.java index b96c63291..4728bc15b 100644 --- a/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/converter/OAuth2SmsAuthenticationConverter.java +++ b/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/converter/OAuth2SmsAuthenticationConverter.java @@ -28,21 +28,26 @@ import java.util.Set; /** - *

短信登录转换器

+ *

+ * 短信登录转换器 + *

* * @author kevin */ -public class OAuth2SmsAuthenticationConverter implements OAuth2BaseAuthenticationConverter { +public class OAuth2SmsAuthenticationConverter + implements OAuth2BaseAuthenticationConverter { @Override public RequestMatcher support() { return request -> SecurityConstants.SMS.equals(request.getParameter(OAuth2ParameterNames.GRANT_TYPE)) - && StringUtils.hasText(request.getParameter(SecurityConstants.SMS_PARAMETER_NAME)) - && StringUtils.hasText(request.getParameter(OAuth2ParameterNames.CODE)); + && StringUtils.hasText(request.getParameter(SecurityConstants.SMS_PARAMETER_NAME)) + && StringUtils.hasText(request.getParameter(OAuth2ParameterNames.CODE)); } @Override - public OAuth2SmsAuthenticationToken buildToken(Authentication clientPrincipal, Set requestedScopes, Map additionalParameters) { + public OAuth2SmsAuthenticationToken buildToken(Authentication clientPrincipal, Set requestedScopes, + Map additionalParameters) { return new OAuth2SmsAuthenticationToken(clientPrincipal, requestedScopes, additionalParameters); } + } diff --git a/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/core/FormIdentityLoginConfigurer.java b/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/core/FormIdentityLoginConfigurer.java index 2ee643a02..2ede12082 100644 --- a/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/core/FormIdentityLoginConfigurer.java +++ b/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/core/FormIdentityLoginConfigurer.java @@ -23,18 +23,20 @@ import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; /** - *

基于授权码模式 统一认证登录 spring security & sas 都可以使用 所以抽取成 HttpConfigurer

+ *

+ * 基于授权码模式 统一认证登录 spring security & sas 都可以使用 所以抽取成 HttpConfigurer + *

* * @author livk */ public final class FormIdentityLoginConfigurer - extends AbstractHttpConfigurer { + extends AbstractHttpConfigurer { @Override public void init(HttpSecurity http) throws Exception { http.formLogin(configurer -> configurer.loginPage("/token/login") - .loginProcessingUrl("/token/form") - .failureHandler(new FormAuthenticationFailureHandler())) + .loginProcessingUrl("/token/form") + .failureHandler(new FormAuthenticationFailureHandler())) .logout(configurer -> configurer.logoutSuccessHandler(new SsoLogoutSuccessHandler()) .deleteCookies("JSESSIONID") .invalidateHttpSession(true)) diff --git a/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/core/UserDetailsAuthenticationProvider.java b/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/core/UserDetailsAuthenticationProvider.java index 47b65817d..a29fd3f63 100644 --- a/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/core/UserDetailsAuthenticationProvider.java +++ b/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/core/UserDetailsAuthenticationProvider.java @@ -61,9 +61,12 @@ public class UserDetailsAuthenticationProvider extends AbstractUserDetailsAuthen private static final String USER_NOT_FOUND_PASSWORD = "userNotFoundPassword"; private final static BasicAuthenticationConverter basicConvert = new BasicAuthenticationConverter(); + private final ObjectProvider oauth2UserDetailsServices; + @Getter private PasswordEncoder passwordEncoder; + /** * The password used to perform {@link PasswordEncoder#matches(CharSequence, String)} * on when the user is not found to avoid SEC-2056. This is necessary, because some @@ -71,20 +74,24 @@ public class UserDetailsAuthenticationProvider extends AbstractUserDetailsAuthen * in a valid format. */ private volatile String userNotFoundEncodedPassword; + @Getter @Setter private UserDetailsService userDetailsService; + @Setter private UserDetailsPasswordService userDetailsPasswordService; - public UserDetailsAuthenticationProvider(PasswordEncoder passwordEncoder, ObjectProvider oauth2UserDetailsServices) { + public UserDetailsAuthenticationProvider(PasswordEncoder passwordEncoder, + ObjectProvider oauth2UserDetailsServices) { setMessageSource(MessageSourceUtils.get()); setPasswordEncoder(passwordEncoder); this.oauth2UserDetailsServices = oauth2UserDetailsServices; } @Override - protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException { + protected void additionalAuthenticationChecks(UserDetails userDetails, + UsernamePasswordAuthenticationToken authentication) throws AuthenticationException { String grantType = WebUtils.request().getParameter(OAuth2ParameterNames.GRANT_TYPE); @@ -93,7 +100,7 @@ protected void additionalAuthenticationChecks(UserDetails userDetails, UsernameP throw new BadCredentialsException(this.messages .getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials")); } - //校验验证码 + // 校验验证码 if (Objects.equals(SecurityConstants.SMS, grantType)) { String code = authentication.getCredentials().toString(); if (!Objects.equals(code, "123456")) { @@ -102,7 +109,7 @@ protected void additionalAuthenticationChecks(UserDetails userDetails, UsernameP .getMessage("AbstractUserDetailsAuthenticationProvider.badCaptcha", "Bad captcha")); } } - //校验密码 + // 校验密码 if (Objects.equals(SecurityConstants.PASSWORD, grantType)) { String presentedPassword = authentication.getCredentials().toString(); String encodedPassword = extractEncodedPassword(userDetails.getPassword()); @@ -133,27 +140,33 @@ protected final UserDetails retrieveUser(String username, UsernamePasswordAuthen .filter(service -> service.support(finalClientId, grantType)) .max(Comparator.comparingInt(Ordered::getOrder)); - optional.orElseThrow((() -> new InternalAuthenticationServiceException("UserDetailsService error , not register"))); + optional + .orElseThrow((() -> new InternalAuthenticationServiceException("UserDetailsService error , not register"))); try { UserDetails loadedUser = optional.get().loadUserByUsername(username); - Optional.ofNullable(loadedUser).orElseThrow(() -> - new InternalAuthenticationServiceException("UserDetailsService returned null, which is an interface contract violation")); + Optional.ofNullable(loadedUser) + .orElseThrow(() -> new InternalAuthenticationServiceException( + "UserDetailsService returned null, which is an interface contract violation")); return loadedUser; - } catch (UsernameNotFoundException ex) { + } + catch (UsernameNotFoundException ex) { mitigateAgainstTimingAttack(authentication); throw ex; - } catch (InternalAuthenticationServiceException ex) { + } + catch (InternalAuthenticationServiceException ex) { throw ex; - } catch (Exception ex) { + } + catch (Exception ex) { throw new InternalAuthenticationServiceException(ex.getMessage(), ex); } } @Override - protected Authentication createSuccessAuthentication(Object principal, Authentication authentication, UserDetails user) { + protected Authentication createSuccessAuthentication(Object principal, Authentication authentication, + UserDetails user) { boolean upgradeEncoding = this.userDetailsPasswordService != null - && this.passwordEncoder.upgradeEncoding(user.getPassword()); + && this.passwordEncoder.upgradeEncoding(user.getPassword()); if (upgradeEncoding) { String presentedPassword = authentication.getCredentials().toString(); String newPassword = this.passwordEncoder.encode(presentedPassword); @@ -179,9 +192,8 @@ private void mitigateAgainstTimingAttack(UsernamePasswordAuthenticationToken aut * Sets the PasswordEncoder instance to be used to encode and validate passwords. If * not set, the password will be compared using * {@link PasswordEncoderFactories#createDelegatingPasswordEncoder()} - * * @param passwordEncoder must be an instance of one of the {@code PasswordEncoder} - * types. + * types. */ public void setPasswordEncoder(PasswordEncoder passwordEncoder) { Assert.notNull(passwordEncoder, "passwordEncoder cannot be null"); @@ -193,4 +205,5 @@ private String extractEncodedPassword(String prefixEncodedPassword) { int start = prefixEncodedPassword.indexOf(SecurityConstants.DEFAULT_ID_SUFFIX); return prefixEncodedPassword.substring(start + SecurityConstants.DEFAULT_ID_SUFFIX.length()); } + } diff --git a/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/core/customizer/OAuth2JwtTokenCustomizer.java b/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/core/customizer/OAuth2JwtTokenCustomizer.java index be861ead6..1991472e4 100644 --- a/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/core/customizer/OAuth2JwtTokenCustomizer.java +++ b/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/core/customizer/OAuth2JwtTokenCustomizer.java @@ -25,7 +25,9 @@ import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenCustomizer; /** - *

JWT token 输出增强

+ *

+ * JWT token 输出增强 + *

* * @author livk */ @@ -33,7 +35,6 @@ public class OAuth2JwtTokenCustomizer implements OAuth2TokenCustomizerBadCaptchaException with the specified message. - * * @param msg the detail message */ public BadCaptchaException(String msg) { @@ -34,10 +33,9 @@ public BadCaptchaException(String msg) { } /** - * Constructs a BadCaptchaException with the specified message and - * root cause. - * - * @param msg the detail message + * Constructs a BadCaptchaException with the specified message and root + * cause. + * @param msg the detail message * @param cause root cause */ public BadCaptchaException(String msg, Throwable cause) { diff --git a/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/core/principal/Oauth2User.java b/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/core/principal/Oauth2User.java index 0fbefd174..858ae37b0 100644 --- a/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/core/principal/Oauth2User.java +++ b/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/core/principal/Oauth2User.java @@ -50,8 +50,8 @@ public class Oauth2User extends User implements OAuth2AuthenticatedPrincipal { private final String mobile; public Oauth2User(Long id, String username, String password, String mobile, boolean enabled, - boolean accountNonExpired, boolean credentialsNonExpired, boolean accountNonLocked, - Collection authorities) { + boolean accountNonExpired, boolean credentialsNonExpired, boolean accountNonLocked, + Collection authorities) { super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities); this.id = id; this.mobile = mobile; @@ -59,7 +59,6 @@ public Oauth2User(Long id, String username, String password, String mobile, bool /** * Get the OAuth 2.0 token attributes - * * @return the OAuth 2.0 token attributes */ @Override diff --git a/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/core/resource/CustomOpaqueTokenIntrospector.java b/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/core/resource/CustomOpaqueTokenIntrospector.java index bc35f2f44..c1217e1a3 100644 --- a/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/core/resource/CustomOpaqueTokenIntrospector.java +++ b/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/core/resource/CustomOpaqueTokenIntrospector.java @@ -50,10 +50,11 @@ public class CustomOpaqueTokenIntrospector implements OpaqueTokenIntrospector { public OAuth2AuthenticatedPrincipal introspect(String token) { OAuth2Authorization oldAuthorization = authorizationService.findByToken(token, OAuth2TokenType.ACCESS_TOKEN); - Optional optional = SpringContextHolder.getBeanProvider(Oauth2UserDetailsService.class) + Optional optional = SpringContextHolder + .getBeanProvider(Oauth2UserDetailsService.class) .orderedStream() .filter(service -> service.support(Objects.requireNonNull(oldAuthorization).getRegisteredClientId(), - oldAuthorization.getAuthorizationGrantType().getValue())) + oldAuthorization.getAuthorizationGrantType().getValue())) .max(Comparator.comparingInt(Ordered::getOrder)); UserDetails userDetails = null; @@ -62,10 +63,12 @@ public OAuth2AuthenticatedPrincipal introspect(String token) { UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = (UsernamePasswordAuthenticationToken) principal; Object tokenPrincipal = usernamePasswordAuthenticationToken.getPrincipal(); userDetails = optional.orElseThrow().loadUserByUser((Oauth2User) tokenPrincipal); - } catch (UsernameNotFoundException notFoundException) { + } + catch (UsernameNotFoundException notFoundException) { log.warn("用户不不存在 {}", notFoundException.getLocalizedMessage()); throw notFoundException; - } catch (Exception ex) { + } + catch (Exception ex) { log.error("资源服务器 introspect Token error {}", ex.getLocalizedMessage()); } return (Oauth2User) userDetails; diff --git a/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/core/resource/ResourceServerAutoConfiguration.java b/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/core/resource/ResourceServerAutoConfiguration.java index 30def3c09..81cdfc0e7 100644 --- a/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/core/resource/ResourceServerAutoConfiguration.java +++ b/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/core/resource/ResourceServerAutoConfiguration.java @@ -34,7 +34,6 @@ public class ResourceServerAutoConfiguration { /** * 资源服务器toke内省处理器 - * * @param authorizationService token 存储实现 * @return TokenIntrospector */ diff --git a/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/handler/AuthenticationFailureEventHandler.java b/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/handler/AuthenticationFailureEventHandler.java index 513c8b3fa..ad5f87baa 100644 --- a/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/handler/AuthenticationFailureEventHandler.java +++ b/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/handler/AuthenticationFailureEventHandler.java @@ -45,15 +45,15 @@ public class AuthenticationFailureEventHandler implements AuthenticationFailureH /** * Called when an authentication attempt fails. - * - * @param request the request during which the authentication attempt occurred. - * @param response the response. + * @param request the request during which the authentication attempt occurred. + * @param response the response. * @param exception the exception which was thrown to reject the authentication - * request. + * request. */ @Override @SneakyThrows - public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) { + public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, + AuthenticationException exception) { String grantType = request.getParameter(OAuth2ParameterNames.GRANT_TYPE); @@ -69,7 +69,8 @@ public void onAuthenticationFailure(HttpServletRequest request, HttpServletRespo sendErrorResponse(request, response, exception); } - private void sendErrorResponse(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException { + private void sendErrorResponse(HttpServletRequest request, HttpServletResponse response, + AuthenticationException exception) throws IOException { OAuth2Error error = ((OAuth2AuthenticationException) exception).getError(); @@ -77,7 +78,8 @@ private void sendErrorResponse(HttpServletRequest request, HttpServletResponse r httpResponse.setStatusCode(HttpStatus.BAD_REQUEST); - this.errorHttpResponseConverter.write(ResponseEntity.status(403).body(error.getDescription()), MediaType.APPLICATION_JSON, httpResponse); + this.errorHttpResponseConverter.write(ResponseEntity.status(403).body(error.getDescription()), + MediaType.APPLICATION_JSON, httpResponse); } } diff --git a/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/handler/AuthenticationSuccessEventHandler.java b/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/handler/AuthenticationSuccessEventHandler.java index f7c916848..9baa19c2a 100644 --- a/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/handler/AuthenticationSuccessEventHandler.java +++ b/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/handler/AuthenticationSuccessEventHandler.java @@ -47,15 +47,15 @@ public class AuthenticationSuccessEventHandler implements AuthenticationSuccessH /** * Called when a user has been successfully authenticated. - * - * @param request the request which caused the successful authentication - * @param response the response + * @param request the request which caused the successful authentication + * @param response the response * @param authentication the Authentication object which was created during - * the authentication process. + * the authentication process. */ @SneakyThrows @Override - public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) { + public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, + Authentication authentication) { log.info("用户:{} 登录成功", authentication.getPrincipal()); @@ -65,7 +65,8 @@ public void onAuthenticationSuccess(HttpServletRequest request, HttpServletRespo sendAccessTokenResponse(request, response, authentication); } - private void sendAccessTokenResponse(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException { + private void sendAccessTokenResponse(HttpServletRequest request, HttpServletResponse response, + Authentication authentication) throws IOException { OAuth2AccessTokenAuthenticationToken accessTokenAuthentication = (OAuth2AccessTokenAuthenticationToken) authentication; @@ -73,7 +74,9 @@ private void sendAccessTokenResponse(HttpServletRequest request, HttpServletResp OAuth2RefreshToken refreshToken = accessTokenAuthentication.getRefreshToken(); Map additionalParameters = accessTokenAuthentication.getAdditionalParameters(); - OAuth2AccessTokenResponse.Builder builder = OAuth2AccessTokenResponse.withToken(accessToken.getTokenValue()).tokenType(accessToken.getTokenType()).scopes(accessToken.getScopes()); + OAuth2AccessTokenResponse.Builder builder = OAuth2AccessTokenResponse.withToken(accessToken.getTokenValue()) + .tokenType(accessToken.getTokenType()) + .scopes(accessToken.getScopes()); if (accessToken.getIssuedAt() != null && accessToken.getExpiresAt() != null) { builder.expiresIn(ChronoUnit.SECONDS.between(accessToken.getIssuedAt(), accessToken.getExpiresAt())); } diff --git a/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/handler/FormAuthenticationFailureHandler.java b/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/handler/FormAuthenticationFailureHandler.java index 6de938da5..211d90545 100644 --- a/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/handler/FormAuthenticationFailureHandler.java +++ b/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/handler/FormAuthenticationFailureHandler.java @@ -24,9 +24,9 @@ import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.authentication.AuthenticationFailureHandler; - /** - *

+ *

+ *

* * @author livk */ @@ -35,15 +35,14 @@ public class FormAuthenticationFailureHandler implements AuthenticationFailureHa /** * Called when an authentication attempt fails. - * - * @param request the request during which the authentication attempt occurred. - * @param response the response. + * @param request the request during which the authentication attempt occurred. + * @param response the response. * @param exception the exception which was thrown to reject the authentication */ @Override @SneakyThrows public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, - AuthenticationException exception) { + AuthenticationException exception) { log.debug("表单登录失败:{}", exception.getLocalizedMessage()); String url = String.format("/token/login?error=%s", exception.getMessage()); response.sendRedirect(url); diff --git a/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/handler/SsoLogoutSuccessHandler.java b/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/handler/SsoLogoutSuccessHandler.java index fe6cd1ffa..9e53b8cbc 100644 --- a/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/handler/SsoLogoutSuccessHandler.java +++ b/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/handler/SsoLogoutSuccessHandler.java @@ -27,7 +27,9 @@ import java.io.IOException; /** - *

sso 退出功能 ,根据客户端传入跳转

+ *

+ * sso 退出功能 ,根据客户端传入跳转 + *

* * @author livk */ @@ -37,7 +39,7 @@ public class SsoLogoutSuccessHandler implements LogoutSuccessHandler { @Override public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) - throws IOException { + throws IOException { if (response == null) { return; } @@ -46,7 +48,8 @@ public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse resp String redirectUrl = request.getParameter(REDIRECT_URL); if (StringUtils.hasText(redirectUrl)) { response.sendRedirect(redirectUrl); - } else if (StringUtils.hasText(request.getHeader(HttpHeaders.REFERER))) { + } + else if (StringUtils.hasText(request.getHeader(HttpHeaders.REFERER))) { // 默认跳转referer 地址 String referer = request.getHeader(HttpHeaders.REFERER); response.sendRedirect(referer); diff --git a/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/provider/OAuth2BaseAuthenticationProvider.java b/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/provider/OAuth2BaseAuthenticationProvider.java index 7884ef8e8..880422fa8 100644 --- a/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/provider/OAuth2BaseAuthenticationProvider.java +++ b/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/provider/OAuth2BaseAuthenticationProvider.java @@ -47,12 +47,15 @@ import java.util.*; /** - *

处理自定义授权

+ *

+ * 处理自定义授权 + *

* * @author livk */ @Slf4j -public abstract class OAuth2BaseAuthenticationProvider implements AuthenticationProvider { +public abstract class OAuth2BaseAuthenticationProvider + implements AuthenticationProvider { private static final String ERROR_URI = "https://datatracker.ietf.org/doc/html/rfc6749#section-4.1.2.1"; @@ -67,14 +70,13 @@ public abstract class OAuth2BaseAuthenticationProvider tokenGenerator) { + OAuth2AuthorizationService authorizationService, + OAuth2TokenGenerator tokenGenerator) { Assert.notNull(authorizationService, "authorizationService cannot be null"); Assert.notNull(tokenGenerator, "tokenGenerator cannot be null"); this.authenticationManager = authenticationManager; @@ -87,7 +89,6 @@ protected OAuth2BaseAuthenticationProvider(AuthenticationManager authenticationM /** * 封装简易principal - * * @param reqParameters * @return */ @@ -95,28 +96,26 @@ protected OAuth2BaseAuthenticationProvider(AuthenticationManager authenticationM /** * 当前provider是否支持此令牌类型 - * * @param authentication * @return */ @Override @SuppressWarnings("unchecked") public boolean supports(Class authentication) { - Class childType = (Class) GenericTypeResolver.resolveTypeArgument(this.getClass(), OAuth2BaseAuthenticationProvider.class); + Class childType = (Class) GenericTypeResolver.resolveTypeArgument(this.getClass(), + OAuth2BaseAuthenticationProvider.class); Assert.notNull(childType, "child Type is null"); return childType.isAssignableFrom(authentication); } /** * 当前的请求客户端是否支持此模式 - * * @param registeredClient */ protected abstract void checkClient(RegisteredClient registeredClient); /** * Performs authentication with the same contract as - * * @param authentication the authentication request object. * @throws AuthenticationException if authentication fails. * @see org.springframework.security.oauth2.server.authorization.authentication.OAuth2AuthorizationCodeAuthenticationProvider#authenticate(Authentication) @@ -129,7 +128,8 @@ public Authentication authenticate(Authentication authentication) throws Authent T baseAuthentication = (T) authentication; - OAuth2ClientAuthenticationToken clientPrincipal = OAuth2AuthenticationProviderUtils.getAuthenticatedClientElseThrowInvalidClient(baseAuthentication); + OAuth2ClientAuthenticationToken clientPrincipal = OAuth2AuthenticationProviderUtils + .getAuthenticatedClientElseThrowInvalidClient(baseAuthentication); RegisteredClient registeredClient = clientPrincipal.getRegisteredClient(); @@ -137,7 +137,9 @@ public Authentication authenticate(Authentication authentication) throws Authent Set authorizedScopes = Objects.requireNonNull(registeredClient).getScopes(); if (!CollectionUtils.isEmpty(baseAuthentication.getScopes())) { - if (baseAuthentication.getScopes().stream().noneMatch(scope -> registeredClient.getScopes().contains(scope))) { + if (baseAuthentication.getScopes() + .stream() + .noneMatch(scope -> registeredClient.getScopes().contains(scope))) { throw new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_SCOPE); } authorizedScopes = Sets.newLinkedHashSet(baseAuthentication.getScopes()); @@ -158,39 +160,45 @@ public Authentication authenticate(Authentication authentication) throws Authent .authorizationGrant(baseAuthentication); OAuth2Authorization.Builder authorizationBuilder = OAuth2Authorization - .withRegisteredClient(registeredClient).principalName(principal.getName()) + .withRegisteredClient(registeredClient) + .principalName(principal.getName()) .authorizationGrantType(baseAuthentication.getGrantType()) .authorizedScopes(authorizedScopes); OAuth2TokenContext tokenContext = tokenContextBuilder.tokenType(OAuth2TokenType.ACCESS_TOKEN).build(); - - OAuth2Token generatedAccessToken = Optional.ofNullable(this.tokenGenerator.generate(tokenContext)).orElseThrow(() -> - new OAuth2AuthenticationException(new OAuth2Error(OAuth2ErrorCodes.SERVER_ERROR, "The token generator failed to generate the access token.", ERROR_URI))); + OAuth2Token generatedAccessToken = Optional.ofNullable(this.tokenGenerator.generate(tokenContext)) + .orElseThrow(() -> new OAuth2AuthenticationException(new OAuth2Error(OAuth2ErrorCodes.SERVER_ERROR, + "The token generator failed to generate the access token.", ERROR_URI))); OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, - generatedAccessToken.getTokenValue(), generatedAccessToken.getIssuedAt(), - generatedAccessToken.getExpiresAt(), tokenContext.getAuthorizedScopes()); + generatedAccessToken.getTokenValue(), generatedAccessToken.getIssuedAt(), + generatedAccessToken.getExpiresAt(), tokenContext.getAuthorizedScopes()); if (generatedAccessToken instanceof ClaimAccessor) { - authorizationBuilder - .token(accessToken, metadata -> metadata.put(OAuth2Authorization.Token.CLAIMS_METADATA_NAME, ((ClaimAccessor) generatedAccessToken).getClaims())); - } else { + authorizationBuilder.token(accessToken, + metadata -> metadata.put(OAuth2Authorization.Token.CLAIMS_METADATA_NAME, + ((ClaimAccessor) generatedAccessToken).getClaims())); + } + else { authorizationBuilder.accessToken(accessToken); } OAuth2RefreshToken refreshToken = null; - if (registeredClient.getAuthorizationGrantTypes().contains(AuthorizationGrantType.REFRESH_TOKEN) && - !clientPrincipal.getClientAuthenticationMethod().equals(ClientAuthenticationMethod.NONE)) { + if (registeredClient.getAuthorizationGrantTypes().contains(AuthorizationGrantType.REFRESH_TOKEN) + && !clientPrincipal.getClientAuthenticationMethod().equals(ClientAuthenticationMethod.NONE)) { tokenContext = tokenContextBuilder.tokenType(OAuth2TokenType.REFRESH_TOKEN).build(); OAuth2Token generatedRefreshToken = this.tokenGenerator.generate(tokenContext); if (generatedRefreshToken == null) { - throw new OAuth2AuthenticationException(new OAuth2Error(OAuth2ErrorCodes.SERVER_ERROR, "The token generator failed to generate the refresh token.", ERROR_URI)); + throw new OAuth2AuthenticationException(new OAuth2Error(OAuth2ErrorCodes.SERVER_ERROR, + "The token generator failed to generate the refresh token.", ERROR_URI)); } if (generatedRefreshToken instanceof OAuth2RefreshToken oAuth2RefreshToken) { refreshToken = oAuth2RefreshToken; - } else { - refreshToken = new OAuth2RefreshToken(generatedRefreshToken.getTokenValue(), generatedRefreshToken.getIssuedAt(), generatedRefreshToken.getExpiresAt()); + } + else { + refreshToken = new OAuth2RefreshToken(generatedRefreshToken.getTokenValue(), + generatedRefreshToken.getIssuedAt(), generatedRefreshToken.getExpiresAt()); } authorizationBuilder.refreshToken(refreshToken); } @@ -202,9 +210,10 @@ public Authentication authenticate(Authentication authentication) throws Authent log.debug("returning OAuth2AccessTokenAuthenticationToken"); return new OAuth2AccessTokenAuthenticationToken(registeredClient, clientPrincipal, accessToken, - refreshToken, Objects.requireNonNull(authorization.getAccessToken().getClaims())); + refreshToken, Objects.requireNonNull(authorization.getAccessToken().getClaims())); - } catch (Exception ex) { + } + catch (Exception ex) { log.error("problem in authenticate", ex); throw oAuth2AuthenticationException(authentication, (AuthenticationException) ex); } @@ -213,26 +222,27 @@ public Authentication authenticate(Authentication authentication) throws Authent /** * 登录异常转换为OAuth2AuthenticationException异常,才能被AuthenticationFailureEventHandler处理 - * - * @param authentication 身份验证 + * @param authentication 身份验证 * @param authenticationException 身份验证异常 * @return {@link OAuth2AuthenticationException} */ private OAuth2AuthenticationException oAuth2AuthenticationException(Authentication authentication, - AuthenticationException authenticationException) { + AuthenticationException authenticationException) { if (authenticationException instanceof UsernameNotFoundException) { return new OAuth2AuthenticationException(new OAuth2Error(OAuth2ErrorCodesExpand.USERNAME_NOT_FOUND, - this.messages.getMessage("JdbcDaoImpl.notFound", new Object[]{authentication.getName()}, "Username {0} not found"), "")); + this.messages.getMessage("JdbcDaoImpl.notFound", new Object[] { authentication.getName() }, + "Username {0} not found"), + "")); } if (authenticationException instanceof BadCaptchaException) { - return new OAuth2AuthenticationException( - new OAuth2Error(OAuth2ErrorCodesExpand.BAD_CAPTCHA, this.messages.getMessage( - "AbstractUserDetailsAuthenticationProvider.badCaptcha", "Bad captcha"), "")); + return new OAuth2AuthenticationException(new OAuth2Error(OAuth2ErrorCodesExpand.BAD_CAPTCHA, + this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCaptcha", "Bad captcha"), + "")); } if (authenticationException instanceof BadCredentialsException) { return new OAuth2AuthenticationException( - new OAuth2Error(OAuth2ErrorCodesExpand.BAD_CREDENTIALS, this.messages.getMessage( - "AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"), "")); + new OAuth2Error(OAuth2ErrorCodesExpand.BAD_CREDENTIALS, this.messages.getMessage( + "AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"), "")); } if (authenticationException instanceof LockedException) { return new OAuth2AuthenticationException(new OAuth2Error(OAuth2ErrorCodesExpand.USER_LOCKED, this.messages @@ -240,8 +250,8 @@ private OAuth2AuthenticationException oAuth2AuthenticationException(Authenticati } if (authenticationException instanceof DisabledException) { return new OAuth2AuthenticationException(new OAuth2Error(OAuth2ErrorCodesExpand.USER_DISABLE, - this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.disabled", "User is disabled"), - "")); + this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.disabled", "User is disabled"), + "")); } if (authenticationException instanceof AccountExpiredException) { return new OAuth2AuthenticationException(new OAuth2Error(OAuth2ErrorCodesExpand.USER_EXPIRED, this.messages @@ -249,9 +259,9 @@ private OAuth2AuthenticationException oAuth2AuthenticationException(Authenticati } if (authenticationException instanceof CredentialsExpiredException) { return new OAuth2AuthenticationException(new OAuth2Error(OAuth2ErrorCodesExpand.CREDENTIALS_EXPIRED, - this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.credentialsExpired", - "User credentials have expired"), - "")); + this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.credentialsExpired", + "User credentials have expired"), + "")); } return new OAuth2AuthenticationException(OAuth2ErrorCodesExpand.UN_KNOW_LOGIN_ERROR); } diff --git a/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/provider/OAuth2PasswordAuthenticationProvider.java b/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/provider/OAuth2PasswordAuthenticationProvider.java index 85e978199..47994ebf8 100644 --- a/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/provider/OAuth2PasswordAuthenticationProvider.java +++ b/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/provider/OAuth2PasswordAuthenticationProvider.java @@ -33,24 +33,26 @@ import java.util.Map; /** - *

处理用户名密码授权

+ *

+ * 处理用户名密码授权 + *

* * @author livk */ -public class OAuth2PasswordAuthenticationProvider extends OAuth2BaseAuthenticationProvider { +public class OAuth2PasswordAuthenticationProvider + extends OAuth2BaseAuthenticationProvider { /** * Constructs an {@code OAuth2AuthorizationCodeAuthenticationProvider} using the * provided parameters. - * * @param authenticationManager - * @param authorizationService the authorization service - * @param tokenGenerator the token generator + * @param authorizationService the authorization service + * @param tokenGenerator the token generator * @since 0.2.3 */ public OAuth2PasswordAuthenticationProvider(AuthenticationManager authenticationManager, - OAuth2AuthorizationService authorizationService, - OAuth2TokenGenerator tokenGenerator) { + OAuth2AuthorizationService authorizationService, + OAuth2TokenGenerator tokenGenerator) { super(authenticationManager, authorizationService, tokenGenerator); } diff --git a/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/provider/OAuth2SmsAuthenticationProvider.java b/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/provider/OAuth2SmsAuthenticationProvider.java index 63e813f0e..de23f6dc7 100644 --- a/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/provider/OAuth2SmsAuthenticationProvider.java +++ b/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/provider/OAuth2SmsAuthenticationProvider.java @@ -40,15 +40,14 @@ public class OAuth2SmsAuthenticationProvider extends OAuth2BaseAuthenticationPro /** * Constructs an {@code OAuth2AuthorizationCodeAuthenticationProvider} using the * provided parameters. - * * @param authenticationManager - * @param authorizationService the authorization service - * @param tokenGenerator the token generator + * @param authorizationService the authorization service + * @param tokenGenerator the token generator * @since 0.2.3 */ public OAuth2SmsAuthenticationProvider(AuthenticationManager authenticationManager, - OAuth2AuthorizationService authorizationService, - OAuth2TokenGenerator tokenGenerator) { + OAuth2AuthorizationService authorizationService, + OAuth2TokenGenerator tokenGenerator) { super(authenticationManager, authorizationService, tokenGenerator); } diff --git a/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/service/Oauth2UserDetailsService.java b/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/service/Oauth2UserDetailsService.java index 24a830bcc..52143f67f 100644 --- a/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/service/Oauth2UserDetailsService.java +++ b/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/service/Oauth2UserDetailsService.java @@ -26,7 +26,6 @@ public interface Oauth2UserDetailsService extends UserDetailsService, Ordered { /** * 是否支持此客户端校验 - * * @param clientId 目标客户端 * @return true/false */ @@ -36,7 +35,6 @@ default boolean support(String clientId, String grantType) { /** * 排序值 默认取最大的 - * * @return 排序值 */ default int getOrder() { @@ -45,7 +43,6 @@ default int getOrder() { /** * 通过用户实体查询 - * * @param Oauth2User user * @return */ diff --git a/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/token/OAuth2BaseAuthenticationToken.java b/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/token/OAuth2BaseAuthenticationToken.java index 4f3be8004..df9a7ba1b 100644 --- a/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/token/OAuth2BaseAuthenticationToken.java +++ b/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/token/OAuth2BaseAuthenticationToken.java @@ -28,19 +28,21 @@ import java.util.Set; /** - *

自定义授权模式抽象

+ *

+ * 自定义授权模式抽象 + *

* * @author livk */ @Getter public abstract class OAuth2BaseAuthenticationToken extends OAuth2AuthorizationGrantAuthenticationToken { + private final Set scopes; - public OAuth2BaseAuthenticationToken(AuthorizationGrantType authorizationGrantType, - Authentication clientPrincipal, - @Nullable Set scopes, - @Nullable Map additionalParameters) { + public OAuth2BaseAuthenticationToken(AuthorizationGrantType authorizationGrantType, Authentication clientPrincipal, + @Nullable Set scopes, @Nullable Map additionalParameters) { super(authorizationGrantType, clientPrincipal, additionalParameters); this.scopes = scopes == null ? Set.of() : Collections.unmodifiableSet(scopes); } + } diff --git a/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/token/OAuth2PasswordAuthenticationToken.java b/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/token/OAuth2PasswordAuthenticationToken.java index 211478b0b..286994999 100644 --- a/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/token/OAuth2PasswordAuthenticationToken.java +++ b/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/token/OAuth2PasswordAuthenticationToken.java @@ -24,15 +24,17 @@ import java.util.Set; /** - *

密码授权token信息

+ *

+ * 密码授权token信息 + *

* * @author livk */ public class OAuth2PasswordAuthenticationToken extends OAuth2BaseAuthenticationToken { - public OAuth2PasswordAuthenticationToken(Authentication clientPrincipal, - Set scopes, - Map additionalParameters) { + public OAuth2PasswordAuthenticationToken(Authentication clientPrincipal, Set scopes, + Map additionalParameters) { super(SecurityConstants.GRANT_TYPE_PASSWORD, clientPrincipal, scopes, additionalParameters); } + } diff --git a/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/token/OAuth2SmsAuthenticationToken.java b/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/token/OAuth2SmsAuthenticationToken.java index 410bb83dc..918e43832 100644 --- a/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/token/OAuth2SmsAuthenticationToken.java +++ b/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/token/OAuth2SmsAuthenticationToken.java @@ -28,9 +28,8 @@ */ public class OAuth2SmsAuthenticationToken extends OAuth2BaseAuthenticationToken { - public OAuth2SmsAuthenticationToken(Authentication clientPrincipal, - Set scopes, - Map additionalParameters) { + public OAuth2SmsAuthenticationToken(Authentication clientPrincipal, Set scopes, + Map additionalParameters) { super(SecurityConstants.GRANT_TYPE_SMS, clientPrincipal, scopes, additionalParameters); } diff --git a/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/util/MessageSourceUtils.java b/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/util/MessageSourceUtils.java index e8c146d59..010f56a07 100644 --- a/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/util/MessageSourceUtils.java +++ b/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/util/MessageSourceUtils.java @@ -39,4 +39,5 @@ public MessageSource get() { messageSource.setDefaultLocale(Locale.CHINA); return messageSource; } + } diff --git a/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/util/OAuth2AuthenticationProviderUtils.java b/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/util/OAuth2AuthenticationProviderUtils.java index 835a88271..6ecb5d09f 100644 --- a/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/util/OAuth2AuthenticationProviderUtils.java +++ b/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/util/OAuth2AuthenticationProviderUtils.java @@ -33,7 +33,8 @@ @UtilityClass public class OAuth2AuthenticationProviderUtils { - public static OAuth2ClientAuthenticationToken getAuthenticatedClientElseThrowInvalidClient(Authentication authentication) { + public static OAuth2ClientAuthenticationToken getAuthenticatedClientElseThrowInvalidClient( + Authentication authentication) { OAuth2ClientAuthenticationToken clientPrincipal = null; if (OAuth2ClientAuthenticationToken.class.isAssignableFrom(authentication.getPrincipal().getClass())) { clientPrincipal = (OAuth2ClientAuthenticationToken) authentication.getPrincipal(); @@ -44,8 +45,7 @@ public static OAuth2ClientAuthenticationToken getAuthenticatedClientElseThrowInv throw new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_CLIENT); } - public static OAuth2Authorization invalidate( - OAuth2Authorization authorization, T token) { + public static OAuth2Authorization invalidate(OAuth2Authorization authorization, T token) { // @formatter:off OAuth2Authorization.Builder authorizationBuilder = OAuth2Authorization.from(authorization) @@ -72,4 +72,5 @@ public static OAuth2Authorization invalidate( return authorizationBuilder.build(); } + } diff --git a/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/util/SecurityUtils.java b/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/util/SecurityUtils.java index dbef317ac..2c7aaecf0 100644 --- a/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/util/SecurityUtils.java +++ b/spring-boot-example/spring-authorization-server/server-commons/src/main/java/com/livk/auth/server/common/util/SecurityUtils.java @@ -65,7 +65,6 @@ public Oauth2User getUser() { /** * 获取用户角色信息 - * * @return 角色集合 */ public List getRoles() { diff --git a/spring-boot-example/spring-batch/src/main/java/com/livk/batch/config/BatchConfig.java b/spring-boot-example/spring-batch/src/main/java/com/livk/batch/config/BatchConfig.java index 7e872addd..f48459c3c 100644 --- a/spring-boot-example/spring-batch/src/main/java/com/livk/batch/config/BatchConfig.java +++ b/spring-boot-example/spring-batch/src/main/java/com/livk/batch/config/BatchConfig.java @@ -56,29 +56,27 @@ public ItemReader reader() { FlatFileItemReader reader = new FlatFileItemReader<>(); reader.setLinesToSkip(1); reader.setResource(new ClassPathResource("data.csv")); - reader.setLineMapper(CsvLineMapper.builder(User.class) - .delimiter("\t") - .fields("userName", "sex", "age", "address") - .build()); -// reader.setLineMapper(new DefaultLineMapper<>() { -// { -// setLineTokenizer(new DelimitedLineTokenizer() { -// { -// // 配置了四行文件 -// setNames("userName", "sex", "age", "address"); -// // 配置列于列之间的间隔符,会通过间隔符对每一行进行切分 -// setDelimiter("\t"); -// } -// }); -// -// // 设置要映射的实体类属性 -// setFieldSetMapper(new BeanWrapperFieldSetMapper<>() { -// { -// setTargetType(User.class); -// } -// }); -// } -// }); + reader.setLineMapper( + CsvLineMapper.builder(User.class).delimiter("\t").fields("userName", "sex", "age", "address").build()); + // reader.setLineMapper(new DefaultLineMapper<>() { + // { + // setLineTokenizer(new DelimitedLineTokenizer() { + // { + // // 配置了四行文件 + // setNames("userName", "sex", "age", "address"); + // // 配置列于列之间的间隔符,会通过间隔符对每一行进行切分 + // setDelimiter("\t"); + // } + // }); + // + // // 设置要映射的实体类属性 + // setFieldSetMapper(new BeanWrapperFieldSetMapper<>() { + // { + // setTargetType(User.class); + // } + // }); + // } + // }); return reader; } @@ -92,17 +90,15 @@ public ItemWriter writer(DataSource dataSource) { JdbcBatchItemWriter writer = new JdbcBatchItemWriter<>(); writer.setDataSource(dataSource); writer.setItemSqlParameterSourceProvider(new BeanPropertyItemSqlParameterSourceProvider<>()); - writer.setSql("insert into sys_user(user_name, sex, age, address, status, create_time ,update_time) " + - "values (:userName, :sex, :age, :address, :status, :createTime, :updateTime)"); + writer.setSql("insert into sys_user(user_name, sex, age, address, status, create_time ,update_time) " + + "values (:userName, :sex, :age, :address, :status, :createTime, :updateTime)"); return writer; } @Bean - public Step csvStep(JobRepository jobRepository, - DataSource dataSource, - DataSourceTransactionManager dataSourceTransactionManager) { - return new StepBuilder("csvStep", jobRepository) - .chunk(5, dataSourceTransactionManager) + public Step csvStep(JobRepository jobRepository, DataSource dataSource, + DataSourceTransactionManager dataSourceTransactionManager) { + return new StepBuilder("csvStep", jobRepository).chunk(5, dataSourceTransactionManager) .reader(reader()) .listener(new JobReadListener()) .processor(processor()) @@ -119,12 +115,8 @@ public Step csvStep(JobRepository jobRepository, } @Bean - public Job csvJob(JobRepository jobRepository, Step step, - JobCompletionListener listener) { - return new JobBuilder("csvJob", jobRepository) - .start(step) - .listener(listener) - .build(); + public Job csvJob(JobRepository jobRepository, Step step, JobCompletionListener listener) { + return new JobBuilder("csvJob", jobRepository).start(step).listener(listener).build(); } @Bean @@ -134,4 +126,5 @@ public TaskExecutorJobLauncher taskExecutorJobLauncher(JobRepository jobReposito jobLauncher.setJobRepository(jobRepository); return jobLauncher; } + } diff --git a/spring-boot-example/spring-batch/src/main/java/com/livk/batch/domain/User.java b/spring-boot-example/spring-batch/src/main/java/com/livk/batch/domain/User.java index 1075e1d8e..6d1a888ac 100644 --- a/spring-boot-example/spring-batch/src/main/java/com/livk/batch/domain/User.java +++ b/spring-boot-example/spring-batch/src/main/java/com/livk/batch/domain/User.java @@ -44,4 +44,5 @@ public class User { private Date createTime; private Date updateTime; + } diff --git a/spring-boot-example/spring-batch/src/main/java/com/livk/batch/support/CsvBeanValidator.java b/spring-boot-example/spring-batch/src/main/java/com/livk/batch/support/CsvBeanValidator.java index a737a8215..14f662c0e 100644 --- a/spring-boot-example/spring-batch/src/main/java/com/livk/batch/support/CsvBeanValidator.java +++ b/spring-boot-example/spring-batch/src/main/java/com/livk/batch/support/CsvBeanValidator.java @@ -26,7 +26,6 @@ import java.util.Set; - /** *

* CsvBeanValidator diff --git a/spring-boot-example/spring-batch/src/main/java/com/livk/batch/support/CsvItemProcessor.java b/spring-boot-example/spring-batch/src/main/java/com/livk/batch/support/CsvItemProcessor.java index 0c5cecc1d..56677a570 100644 --- a/spring-boot-example/spring-batch/src/main/java/com/livk/batch/support/CsvItemProcessor.java +++ b/spring-boot-example/spring-batch/src/main/java/com/livk/batch/support/CsvItemProcessor.java @@ -44,14 +44,16 @@ public User process(@NonNull User item) throws ValidationException { validator.validate(item); if (item.getSex().equals("男")) { item.setSex("1"); - } else { + } + else { item.setSex("2"); } item.setStatus(1); item.setCreateTime(new Date()); item.setUpdateTime(new Date()); return item; - } catch (ValidationException e) { + } + catch (ValidationException e) { return null; } } diff --git a/spring-boot-example/spring-batch/src/main/java/com/livk/batch/support/CsvLineMapper.java b/spring-boot-example/spring-batch/src/main/java/com/livk/batch/support/CsvLineMapper.java index a4c5cfcfe..b556c4779 100644 --- a/spring-boot-example/spring-batch/src/main/java/com/livk/batch/support/CsvLineMapper.java +++ b/spring-boot-example/spring-batch/src/main/java/com/livk/batch/support/CsvLineMapper.java @@ -71,15 +71,20 @@ private void set(T t, String field, String valueStr) { Class type = declaredField.getType(); if (Integer.class.equals(type)) { value = Integer.parseInt(valueStr); - } else if (Long.class.equals(type)) { + } + else if (Long.class.equals(type)) { value = Long.parseLong(valueStr); - } else if (Float.class.equals(type)) { + } + else if (Float.class.equals(type)) { value = Float.parseFloat(valueStr); - } else if (Double.class.equals(type)) { + } + else if (Double.class.equals(type)) { value = Double.parseDouble(valueStr); - } else if (Boolean.class.equals(type)) { + } + else if (Boolean.class.equals(type)) { value = Boolean.parseBoolean(valueStr); - } else { + } + else { value = valueStr; } field = StringUtils.capitalize(field); @@ -89,6 +94,7 @@ private void set(T t, String field, String valueStr) { @RequiredArgsConstructor(access = AccessLevel.PRIVATE) public static class Builder { + private final Class targetClass; private String[] fields; @@ -111,5 +117,7 @@ public CsvLineMapper build() { Assert.notNull(delimiter, "delimiter not null"); return new CsvLineMapper<>(targetClass, fields, delimiter); } + } + } diff --git a/spring-boot-example/spring-batch/src/main/java/com/livk/batch/support/JobCompletionListener.java b/spring-boot-example/spring-batch/src/main/java/com/livk/batch/support/JobCompletionListener.java index 0b8330edd..fa17e0ad7 100644 --- a/spring-boot-example/spring-batch/src/main/java/com/livk/batch/support/JobCompletionListener.java +++ b/spring-boot-example/spring-batch/src/main/java/com/livk/batch/support/JobCompletionListener.java @@ -45,7 +45,8 @@ public void beforeJob(JobExecution jobExecution) { public void afterJob(JobExecution jobExecution) { if (jobExecution.getStatus() == BatchStatus.COMPLETED) { log.info("任务id={}结束于{}", jobExecution.getJobId(), jobExecution.getEndTime()); - } else { + } + else { log.info("任务id={}执行异常状态={}", jobExecution.getJobId(), jobExecution.getStatus()); } } diff --git a/spring-boot-example/spring-batch/src/main/java/com/livk/batch/support/JobReadListener.java b/spring-boot-example/spring-batch/src/main/java/com/livk/batch/support/JobReadListener.java index 3ee894ec3..6f32561f1 100644 --- a/spring-boot-example/spring-batch/src/main/java/com/livk/batch/support/JobReadListener.java +++ b/spring-boot-example/spring-batch/src/main/java/com/livk/batch/support/JobReadListener.java @@ -46,4 +46,5 @@ public void afterRead(@Nullable User item) { public void onReadError(Exception ex) { log.error("spring batch read an error occurred ,message:{}", ex.getMessage(), ex); } + } diff --git a/spring-boot-example/spring-batch/src/main/java/com/livk/batch/support/JobWriteListener.java b/spring-boot-example/spring-batch/src/main/java/com/livk/batch/support/JobWriteListener.java index 62413cc72..2197b1217 100644 --- a/spring-boot-example/spring-batch/src/main/java/com/livk/batch/support/JobWriteListener.java +++ b/spring-boot-example/spring-batch/src/main/java/com/livk/batch/support/JobWriteListener.java @@ -47,4 +47,5 @@ public void afterWrite(@Nullable Chunk items) { public void onWriteError(@Nullable Exception e, @Nullable Chunk items) { log.error("spring batch write an error occurred ,message:{} data:{}", e.getMessage(), items, e); } + } diff --git a/spring-boot-example/spring-batch/src/test/java/com/livk/batch/controller/JobControllerTest.java b/spring-boot-example/spring-batch/src/test/java/com/livk/batch/controller/JobControllerTest.java index 8434ec521..9534d56a5 100644 --- a/spring-boot-example/spring-batch/src/test/java/com/livk/batch/controller/JobControllerTest.java +++ b/spring-boot-example/spring-batch/src/test/java/com/livk/batch/controller/JobControllerTest.java @@ -37,13 +37,9 @@ * * @author livk */ -@SpringBootTest({ - "spring.datasource.driver-class-name=org.h2.Driver", - "spring.datasource.url=jdbc:h2:mem:test", - "spring.sql.init.schema-locations=classpath*:/org/springframework/batch/core/schema-h2.sql", - "spring.sql.init.platform=h2", - "spring.sql.init.mode=embedded" -}) +@SpringBootTest({ "spring.datasource.driver-class-name=org.h2.Driver", "spring.datasource.url=jdbc:h2:mem:test", + "spring.sql.init.schema-locations=classpath*:/org/springframework/batch/core/schema-h2.sql", + "spring.sql.init.platform=h2", "spring.sql.init.mode=embedded" }) @AutoConfigureMockMvc class JobControllerTest { @@ -55,12 +51,12 @@ class JobControllerTest { @Test void doJobTest() throws Exception { - mockMvc.perform(get("/doJob")) - .andExpect(status().isOk()); + mockMvc.perform(get("/doJob")).andExpect(status().isOk()); List names = jdbcTemplate.queryForList("select * from sys_user") .stream() .map(map -> map.get("user_name").toString()) .toList(); assertLinesMatch(List.of("张三", "李四", "王雪", "孙云", "赵柳", "孙雪"), names); } + } diff --git a/spring-boot-example/spring-boot-starter/livk-spring-boot-starter/src/main/java/com/livk/env/DynamicEnvironment.java b/spring-boot-example/spring-boot-starter/livk-spring-boot-starter/src/main/java/com/livk/env/DynamicEnvironment.java index da70527df..53a11136f 100644 --- a/spring-boot-example/spring-boot-starter/livk-spring-boot-starter/src/main/java/com/livk/env/DynamicEnvironment.java +++ b/spring-boot-example/spring-boot-starter/livk-spring-boot-starter/src/main/java/com/livk/env/DynamicEnvironment.java @@ -58,7 +58,8 @@ public void postProcessEnvironment(ConfigurableEnvironment environment, SpringAp PropertiesPropertySource livkSource = new PropertiesPropertySource("livkSource", properties); propertySources.addLast(livkSource); } - } catch (IOException e) { + } + catch (IOException e) { log.error("error:{}", e.getMessage(), e); } } diff --git a/spring-boot-example/spring-boot-starter/livk-spring-boot-starter/src/main/java/com/livk/selector/LivkAutoConfiguration.java b/spring-boot-example/spring-boot-starter/livk-spring-boot-starter/src/main/java/com/livk/selector/LivkAutoConfiguration.java index c8a6c3f8f..ea752a0ce 100644 --- a/spring-boot-example/spring-boot-starter/livk-spring-boot-starter/src/main/java/com/livk/selector/LivkAutoConfiguration.java +++ b/spring-boot-example/spring-boot-starter/livk-spring-boot-starter/src/main/java/com/livk/selector/LivkAutoConfiguration.java @@ -38,4 +38,5 @@ public class LivkAutoConfiguration { public void init() { log.info("{} is init", LivkAutoConfiguration.class); } + } diff --git a/spring-boot-example/spring-boot-starter/livk-spring-boot-starter/src/main/java/com/livk/spi/AbstractServiceLoad.java b/spring-boot-example/spring-boot-starter/livk-spring-boot-starter/src/main/java/com/livk/spi/AbstractServiceLoad.java index 3d35ae012..4c9f30bb5 100644 --- a/spring-boot-example/spring-boot-starter/livk-spring-boot-starter/src/main/java/com/livk/spi/AbstractServiceLoad.java +++ b/spring-boot-example/spring-boot-starter/livk-spring-boot-starter/src/main/java/com/livk/spi/AbstractServiceLoad.java @@ -45,7 +45,8 @@ private Class getServiceClass() { @Override public void afterPropertiesSet() { - servicesMap = ProviderLoader.JDK_SERVICE.load(getServiceClass()).stream() + servicesMap = ProviderLoader.JDK_SERVICE.load(getServiceClass()) + .stream() .collect(Collectors.toMap(this::getKey, Function.identity())); log.info("data:{}", servicesMap); } diff --git a/spring-boot-example/spring-boot-starter/spring-filter-starter/src/main/java/com/livk/filter/context/ReactiveTenantContextHolder.java b/spring-boot-example/spring-boot-starter/spring-filter-starter/src/main/java/com/livk/filter/context/ReactiveTenantContextHolder.java index bfc47270e..2d326d001 100644 --- a/spring-boot-example/spring-boot-starter/spring-filter-starter/src/main/java/com/livk/filter/context/ReactiveTenantContextHolder.java +++ b/spring-boot-example/spring-boot-starter/spring-filter-starter/src/main/java/com/livk/filter/context/ReactiveTenantContextHolder.java @@ -61,4 +61,5 @@ public Mono get() { .filter(ReactiveTenantContextHolder::hasContext) .flatMap(ReactiveTenantContextHolder::getContext); } + } diff --git a/spring-boot-example/spring-boot-starter/spring-filter-starter/src/main/java/com/livk/filter/context/TenantContextHolder.java b/spring-boot-example/spring-boot-starter/spring-filter-starter/src/main/java/com/livk/filter/context/TenantContextHolder.java index 8f0b1c686..6d7d6d5ec 100644 --- a/spring-boot-example/spring-boot-starter/spring-filter-starter/src/main/java/com/livk/filter/context/TenantContextHolder.java +++ b/spring-boot-example/spring-boot-starter/spring-filter-starter/src/main/java/com/livk/filter/context/TenantContextHolder.java @@ -36,8 +36,9 @@ public class TenantContextHolder { public final static String ATTRIBUTES = "tenant"; private final static ThreadLocal TENANT_ID = new NamedThreadLocal<>("tenant context"); - private final static ThreadLocal INHERITABLE_TENANT_ID = new NamedInheritableThreadLocal<>("inheritable tenant ip context"); + private final static ThreadLocal INHERITABLE_TENANT_ID = new NamedInheritableThreadLocal<>( + "inheritable tenant ip context"); public String getTenantId() { String tenantId = TENANT_ID.get(); @@ -56,11 +57,13 @@ public void setTenantId(String tenantId, boolean inheritable) { if (inheritable) { INHERITABLE_TENANT_ID.set(tenantId); TENANT_ID.remove(); - } else { + } + else { TENANT_ID.set(tenantId); INHERITABLE_TENANT_ID.remove(); } - } else { + } + else { remove(); } } diff --git a/spring-boot-example/spring-boot-starter/spring-filter-starter/src/main/java/com/livk/filter/mvc/TenantFilter.java b/spring-boot-example/spring-boot-starter/spring-filter-starter/src/main/java/com/livk/filter/mvc/TenantFilter.java index 182c59f25..150c21372 100644 --- a/spring-boot-example/spring-boot-starter/spring-filter-starter/src/main/java/com/livk/filter/mvc/TenantFilter.java +++ b/spring-boot-example/spring-boot-starter/spring-filter-starter/src/main/java/com/livk/filter/mvc/TenantFilter.java @@ -43,7 +43,7 @@ public class TenantFilter implements Filter { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) - throws IOException, ServletException { + throws IOException, ServletException { TenantContextHolder.setTenantId(((HttpServletRequest) request).getHeader(TenantContextHolder.ATTRIBUTES)); HttpServletRequestWrapper requestWrapper = new HttpServletRequestWrapper((HttpServletRequest) request); chain.doFilter(requestWrapper, response); diff --git a/spring-boot-example/spring-boot-starter/spring-filter-starter/src/main/java/com/livk/filter/mvc/TenantHandlerInterceptor.java b/spring-boot-example/spring-boot-starter/spring-filter-starter/src/main/java/com/livk/filter/mvc/TenantHandlerInterceptor.java index 374f629d6..59441b673 100644 --- a/spring-boot-example/spring-boot-starter/spring-filter-starter/src/main/java/com/livk/filter/mvc/TenantHandlerInterceptor.java +++ b/spring-boot-example/spring-boot-starter/spring-filter-starter/src/main/java/com/livk/filter/mvc/TenantHandlerInterceptor.java @@ -34,14 +34,14 @@ public class TenantHandlerInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler) - throws Exception { + throws Exception { TenantContextHolder.setTenantId(request.getHeader(TenantContextHolder.ATTRIBUTES)); return HandlerInterceptor.super.preHandle(request, response, handler); } @Override public void afterCompletion(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, - @NonNull Object handler, Exception ex) { + @NonNull Object handler, Exception ex) { TenantContextHolder.remove(); } diff --git a/spring-boot-example/spring-boot-starter/spring-filter-starter/src/main/java/com/livk/filter/reactor/TenantWebFilter.java b/spring-boot-example/spring-boot-starter/spring-filter-starter/src/main/java/com/livk/filter/reactor/TenantWebFilter.java index 64371cf8b..7f1687bb0 100644 --- a/spring-boot-example/spring-boot-starter/spring-filter-starter/src/main/java/com/livk/filter/reactor/TenantWebFilter.java +++ b/spring-boot-example/spring-boot-starter/spring-filter-starter/src/main/java/com/livk/filter/reactor/TenantWebFilter.java @@ -37,11 +37,11 @@ public class TenantWebFilter implements WebFilter { @Override public Mono filter(ServerWebExchange exchange, WebFilterChain chain) { String tenantId = exchange.getRequest().getHeaders().getFirst(ReactiveTenantContextHolder.ATTRIBUTES); - exchange.getResponse().beforeCommit(() -> Mono.deferContextual(Mono::just) - .contextWrite(ReactiveTenantContextHolder.clearContext()) - .then()); - return chain.filter(exchange) - .contextWrite(ReactiveTenantContextHolder.withContext(tenantId)); + exchange.getResponse() + .beforeCommit(() -> Mono.deferContextual(Mono::just) + .contextWrite(ReactiveTenantContextHolder.clearContext()) + .then()); + return chain.filter(exchange).contextWrite(ReactiveTenantContextHolder.withContext(tenantId)); } } diff --git a/spring-boot-example/spring-boot-starter/spring-livk-example/src/main/java/com/livk/spring/App.java b/spring-boot-example/spring-boot-starter/spring-livk-example/src/main/java/com/livk/spring/App.java index cfba67b3e..6d854586b 100644 --- a/spring-boot-example/spring-boot-starter/spring-livk-example/src/main/java/com/livk/spring/App.java +++ b/spring-boot-example/spring-boot-starter/spring-livk-example/src/main/java/com/livk/spring/App.java @@ -33,7 +33,7 @@ */ @LivkImport @EnableLivk -@EnableHttpClient({HttpClientType.REST_TEMPLATE, HttpClientType.WEB_CLIENT}) +@EnableHttpClient({ HttpClientType.REST_TEMPLATE, HttpClientType.WEB_CLIENT }) @SpringBootApplication public class App { diff --git a/spring-boot-example/spring-boot-starter/spring-livk-example/src/main/java/com/livk/spring/FilterController.java b/spring-boot-example/spring-boot-starter/spring-livk-example/src/main/java/com/livk/spring/FilterController.java index eb65036f3..9210552a0 100644 --- a/spring-boot-example/spring-boot-starter/spring-livk-example/src/main/java/com/livk/spring/FilterController.java +++ b/spring-boot-example/spring-boot-starter/spring-livk-example/src/main/java/com/livk/spring/FilterController.java @@ -52,4 +52,5 @@ public HttpEntity tenant(@RequestHeader(TenantContextHolder.ATTRIBUTES) public HttpEntity uuid() { return ResponseEntity.ok(uuidRequest.currentUUID().toString()); } + } diff --git a/spring-boot-example/spring-boot-starter/spring-livk-example/src/main/java/com/livk/spring/factory/UUIDBeanFactoryPostProcessor.java b/spring-boot-example/spring-boot-starter/spring-livk-example/src/main/java/com/livk/spring/factory/UUIDBeanFactoryPostProcessor.java index 8bafc5bbe..28449c37a 100644 --- a/spring-boot-example/spring-boot-starter/spring-livk-example/src/main/java/com/livk/spring/factory/UUIDBeanFactoryPostProcessor.java +++ b/spring-boot-example/spring-boot-starter/spring-livk-example/src/main/java/com/livk/spring/factory/UUIDBeanFactoryPostProcessor.java @@ -29,8 +29,10 @@ * @author livk */ public class UUIDBeanFactoryPostProcessor implements BeanFactoryPostProcessor { + @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { beanFactory.registerResolvableDependency(UUIDRequest.class, new UUIDObjectFactory()); } + } diff --git a/spring-boot-example/spring-boot-starter/spring-livk-example/src/main/java/com/livk/spring/factory/UUIDBeanFactoryPostProcessorLoad.java b/spring-boot-example/spring-boot-starter/spring-livk-example/src/main/java/com/livk/spring/factory/UUIDBeanFactoryPostProcessorLoad.java index 7255c939e..75101eac8 100644 --- a/spring-boot-example/spring-boot-starter/spring-livk-example/src/main/java/com/livk/spring/factory/UUIDBeanFactoryPostProcessorLoad.java +++ b/spring-boot-example/spring-boot-starter/spring-livk-example/src/main/java/com/livk/spring/factory/UUIDBeanFactoryPostProcessorLoad.java @@ -28,8 +28,10 @@ @AutoConfiguration @SpringFactories public class UUIDBeanFactoryPostProcessorLoad implements ApplicationContextInitializer { + @Override public void initialize(ConfigurableApplicationContext applicationContext) { applicationContext.addBeanFactoryPostProcessor(new UUIDBeanFactoryPostProcessor()); } + } diff --git a/spring-boot-example/spring-boot-starter/spring-livk-example/src/main/java/com/livk/spring/factory/UUIDConTextHolder.java b/spring-boot-example/spring-boot-starter/spring-livk-example/src/main/java/com/livk/spring/factory/UUIDConTextHolder.java index b5ccb1e7b..a76e150ad 100644 --- a/spring-boot-example/spring-boot-starter/spring-livk-example/src/main/java/com/livk/spring/factory/UUIDConTextHolder.java +++ b/spring-boot-example/spring-boot-starter/spring-livk-example/src/main/java/com/livk/spring/factory/UUIDConTextHolder.java @@ -30,6 +30,7 @@ */ @UtilityClass public class UUIDConTextHolder { + private static final ThreadLocal UUID_CONTEXT = new ThreadLocal<>(); public UUID get() { @@ -43,4 +44,5 @@ public void set() { public void remove() { UUID_CONTEXT.remove(); } + } diff --git a/spring-boot-example/spring-boot-starter/spring-livk-example/src/main/java/com/livk/spring/factory/UUIDFilter.java b/spring-boot-example/spring-boot-starter/spring-livk-example/src/main/java/com/livk/spring/factory/UUIDFilter.java index 2e18c442f..53f82c0c3 100644 --- a/spring-boot-example/spring-boot-starter/spring-livk-example/src/main/java/com/livk/spring/factory/UUIDFilter.java +++ b/spring-boot-example/spring-boot-starter/spring-livk-example/src/main/java/com/livk/spring/factory/UUIDFilter.java @@ -37,10 +37,13 @@ @Component @WebFilter(filterName = "UUIDFilter", urlPatterns = "/*") public class UUIDFilter extends OncePerRequestFilter { + @Override - protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) + throws ServletException, IOException { UUIDConTextHolder.set(); filterChain.doFilter(request, response); UUIDConTextHolder.remove(); } + } diff --git a/spring-boot-example/spring-boot-starter/spring-livk-example/src/main/java/com/livk/spring/factory/UUIDObjectFactory.java b/spring-boot-example/spring-boot-starter/spring-livk-example/src/main/java/com/livk/spring/factory/UUIDObjectFactory.java index 780f3bbba..fed302613 100644 --- a/spring-boot-example/spring-boot-starter/spring-livk-example/src/main/java/com/livk/spring/factory/UUIDObjectFactory.java +++ b/spring-boot-example/spring-boot-starter/spring-livk-example/src/main/java/com/livk/spring/factory/UUIDObjectFactory.java @@ -25,8 +25,7 @@ /** *

* {@see AutowireUtils#resolveAutowiringValue(Object, Class)} - * 需要注册interface并且当前类实现{@link Serializable} - * 则会被spring代理 + * 需要注册interface并且当前类实现{@link Serializable} 则会被spring代理 *

* * @author livk @@ -37,4 +36,5 @@ public class UUIDObjectFactory implements ObjectFactory, Serializab public UUIDRequest getObject() throws BeansException { return UUIDConTextHolder::get; } + } diff --git a/spring-boot-example/spring-boot-starter/spring-livk-example/src/main/java/com/livk/spring/factory/UUIDRequest.java b/spring-boot-example/spring-boot-starter/spring-livk-example/src/main/java/com/livk/spring/factory/UUIDRequest.java index 886441b49..73ac0fd2d 100644 --- a/spring-boot-example/spring-boot-starter/spring-livk-example/src/main/java/com/livk/spring/factory/UUIDRequest.java +++ b/spring-boot-example/spring-boot-starter/spring-livk-example/src/main/java/com/livk/spring/factory/UUIDRequest.java @@ -29,4 +29,5 @@ public interface UUIDRequest { UUID currentUUID(); + } diff --git a/spring-boot-example/spring-boot-starter/spring-livk-example/src/test/java/com/livk/spring/FilterControllerTest.java b/spring-boot-example/spring-boot-starter/spring-livk-example/src/test/java/com/livk/spring/FilterControllerTest.java index 87c26d512..98dd37f8e 100644 --- a/spring-boot-example/spring-boot-starter/spring-livk-example/src/test/java/com/livk/spring/FilterControllerTest.java +++ b/spring-boot-example/spring-boot-starter/spring-livk-example/src/test/java/com/livk/spring/FilterControllerTest.java @@ -69,13 +69,18 @@ void uuid() throws Exception { String uuid1 = mockMvc.perform(get("/uuid")) .andExpect(status().isOk()) .andDo(print()) - .andReturn().getResponse().getContentAsString(); + .andReturn() + .getResponse() + .getContentAsString(); String uuid2 = mockMvc.perform(get("/uuid")) .andExpect(status().isOk()) .andDo(print()) - .andReturn().getResponse().getContentAsString(); + .andReturn() + .getResponse() + .getContentAsString(); assertNotEquals(uuid1, uuid2); } + } diff --git a/spring-boot-example/spring-clickhouse/spring-clickhouse-jdbc/src/main/java/com/livk/ck/jdbc/controller/UserController.java b/spring-boot-example/spring-clickhouse/spring-clickhouse-jdbc/src/main/java/com/livk/ck/jdbc/controller/UserController.java index d9a13c5bd..f23bad474 100644 --- a/spring-boot-example/spring-clickhouse/spring-clickhouse-jdbc/src/main/java/com/livk/ck/jdbc/controller/UserController.java +++ b/spring-boot-example/spring-clickhouse/spring-clickhouse-jdbc/src/main/java/com/livk/ck/jdbc/controller/UserController.java @@ -54,4 +54,5 @@ public HttpEntity remove(@PathVariable String regTime) { public HttpEntity save(@RequestBody User user) { return ResponseEntity.ok(userService.save(user)); } + } diff --git a/spring-boot-example/spring-clickhouse/spring-clickhouse-jdbc/src/main/java/com/livk/ck/jdbc/entity/User.java b/spring-boot-example/spring-clickhouse/spring-clickhouse-jdbc/src/main/java/com/livk/ck/jdbc/entity/User.java index 9b0b156c3..452e3fcee 100644 --- a/spring-boot-example/spring-clickhouse/spring-clickhouse-jdbc/src/main/java/com/livk/ck/jdbc/entity/User.java +++ b/spring-boot-example/spring-clickhouse/spring-clickhouse-jdbc/src/main/java/com/livk/ck/jdbc/entity/User.java @@ -39,6 +39,7 @@ public class User { private String appId; private String version; + @DateTimeFormat(pattern = "yyyy-MM-dd") private Date regTime; diff --git a/spring-boot-example/spring-clickhouse/spring-clickhouse-jdbc/src/main/java/com/livk/ck/jdbc/mapper/UserMapper.java b/spring-boot-example/spring-clickhouse/spring-clickhouse-jdbc/src/main/java/com/livk/ck/jdbc/mapper/UserMapper.java index 489cbdd92..fdfee86d5 100644 --- a/spring-boot-example/spring-clickhouse/spring-clickhouse-jdbc/src/main/java/com/livk/ck/jdbc/mapper/UserMapper.java +++ b/spring-boot-example/spring-clickhouse/spring-clickhouse-jdbc/src/main/java/com/livk/ck/jdbc/mapper/UserMapper.java @@ -40,4 +40,5 @@ public interface UserMapper { @Insert("insert into user values (#{id},#{appId},#{version},#{regTime})") int insert(User user); + } diff --git a/spring-boot-example/spring-clickhouse/spring-clickhouse-jdbc/src/main/java/com/livk/ck/jdbc/service/UserService.java b/spring-boot-example/spring-clickhouse/spring-clickhouse-jdbc/src/main/java/com/livk/ck/jdbc/service/UserService.java index 5ee464f53..074f9871e 100644 --- a/spring-boot-example/spring-clickhouse/spring-clickhouse-jdbc/src/main/java/com/livk/ck/jdbc/service/UserService.java +++ b/spring-boot-example/spring-clickhouse/spring-clickhouse-jdbc/src/main/java/com/livk/ck/jdbc/service/UserService.java @@ -36,4 +36,5 @@ public interface UserService { boolean remove(@Param("regTime") String regTime); boolean save(User user); + } diff --git a/spring-boot-example/spring-clickhouse/spring-clickhouse-jdbc/src/main/java/com/livk/ck/jdbc/service/impl/UserServiceImpl.java b/spring-boot-example/spring-clickhouse/spring-clickhouse-jdbc/src/main/java/com/livk/ck/jdbc/service/impl/UserServiceImpl.java index 315ecb6e5..38756d374 100644 --- a/spring-boot-example/spring-clickhouse/spring-clickhouse-jdbc/src/main/java/com/livk/ck/jdbc/service/impl/UserServiceImpl.java +++ b/spring-boot-example/spring-clickhouse/spring-clickhouse-jdbc/src/main/java/com/livk/ck/jdbc/service/impl/UserServiceImpl.java @@ -52,4 +52,5 @@ public boolean remove(String regTime) { public boolean save(User user) { return userMapper.insert(user) > 0; } + } diff --git a/spring-boot-example/spring-clickhouse/spring-clickhouse-jdbc/src/test/java/com/livk/ck/jdbc/controller/UserControllerTest.java b/spring-boot-example/spring-clickhouse/spring-clickhouse-jdbc/src/test/java/com/livk/ck/jdbc/controller/UserControllerTest.java index c37465dbd..17f8dce72 100644 --- a/spring-boot-example/spring-clickhouse/spring-clickhouse-jdbc/src/test/java/com/livk/ck/jdbc/controller/UserControllerTest.java +++ b/spring-boot-example/spring-clickhouse/spring-clickhouse-jdbc/src/test/java/com/livk/ck/jdbc/controller/UserControllerTest.java @@ -56,9 +56,7 @@ class UserControllerTest { @Order(2) @Test void testList() throws Exception { - mockMvc.perform(get("/user")) - .andDo(print()) - .andExpect(status().isOk()); + mockMvc.perform(get("/user")).andDo(print()).andExpect(status().isOk()); } @Order(3) @@ -74,15 +72,13 @@ void testRemove() throws Exception { @Order(1) @Test void testSave() throws Exception { - User user = new User().setId(Integer.MAX_VALUE) - .setAppId("appId") - .setVersion("version") - .setRegTime(new Date()); - mockMvc.perform(post("/user") - .contentType(MediaType.APPLICATION_JSON) + User user = new User().setId(Integer.MAX_VALUE).setAppId("appId").setVersion("version").setRegTime(new Date()); + mockMvc + .perform(post("/user").contentType(MediaType.APPLICATION_JSON) .content(JsonMapperUtils.writeValueAsString(user))) .andDo(print()) .andExpect(status().isOk()) .andExpect(content().string("true")); } + } diff --git a/spring-boot-example/spring-clickhouse/spring-clickhouse-r2dbc/src/main/java/com/livk/ck/r2dbc/ClickHouseR2dbcApp.java b/spring-boot-example/spring-clickhouse/spring-clickhouse-r2dbc/src/main/java/com/livk/ck/r2dbc/ClickHouseR2dbcApp.java index 20b005407..bc51839af 100644 --- a/spring-boot-example/spring-clickhouse/spring-clickhouse-r2dbc/src/main/java/com/livk/ck/r2dbc/ClickHouseR2dbcApp.java +++ b/spring-boot-example/spring-clickhouse/spring-clickhouse-r2dbc/src/main/java/com/livk/ck/r2dbc/ClickHouseR2dbcApp.java @@ -33,11 +33,9 @@ * * @author livk */ -@SpringBootApplication(exclude = { - R2dbcAutoConfiguration.class, - R2dbcDataAutoConfiguration.class -}) +@SpringBootApplication(exclude = { R2dbcAutoConfiguration.class, R2dbcDataAutoConfiguration.class }) public class ClickHouseR2dbcApp { + public static void main(String[] args) { SpringLauncher.run(args); } @@ -46,4 +44,5 @@ public static void main(String[] args) { public ConnectionFactory connectionFactory(@Value("${spring.r2dbc.url}") String url) { return ConnectionFactories.get(url); } + } diff --git a/spring-boot-example/spring-clickhouse/spring-clickhouse-r2dbc/src/main/java/com/livk/ck/r2dbc/entity/User.java b/spring-boot-example/spring-clickhouse/spring-clickhouse-r2dbc/src/main/java/com/livk/ck/r2dbc/entity/User.java index db5ffda1f..213bed33e 100644 --- a/spring-boot-example/spring-clickhouse/spring-clickhouse-r2dbc/src/main/java/com/livk/ck/r2dbc/entity/User.java +++ b/spring-boot-example/spring-clickhouse/spring-clickhouse-r2dbc/src/main/java/com/livk/ck/r2dbc/entity/User.java @@ -45,10 +45,12 @@ public class User { private String appId; private String version; + @DateTimeFormat(pattern = "yyyy-MM-dd") private Date regTime; public static User collect(Row row, RowMetadata rowMetadata) { return new User(); } + } diff --git a/spring-boot-example/spring-clickhouse/spring-clickhouse-r2dbc/src/main/java/com/livk/ck/r2dbc/repository/UserRepository.java b/spring-boot-example/spring-clickhouse/spring-clickhouse-r2dbc/src/main/java/com/livk/ck/r2dbc/repository/UserRepository.java index 22ef4f199..54660fafa 100644 --- a/spring-boot-example/spring-clickhouse/spring-clickhouse-r2dbc/src/main/java/com/livk/ck/r2dbc/repository/UserRepository.java +++ b/spring-boot-example/spring-clickhouse/spring-clickhouse-r2dbc/src/main/java/com/livk/ck/r2dbc/repository/UserRepository.java @@ -44,31 +44,32 @@ public UserRepository(ConnectionFactory connectionFactory) { } public Flux findAll() { - return mono.flatMapMany(connection -> - connection.createStatement("select id, app_id, version, reg_time from user").execute()) + return mono.flatMapMany( + connection -> connection.createStatement("select id, app_id, version, reg_time from user").execute()) .flatMap(result -> result.map(User::collect)); } public Mono deleteById(Mono id) { - return id.flatMap(i -> - mono.flatMapMany(connection -> - connection.createStatement("alter table user delete where id=:id") - .bind("id", i) - .execute() - ).then() - ); + return id.flatMap( + i -> mono + .flatMapMany(connection -> connection.createStatement("alter table user delete where id=:id") + .bind("id", i) + .execute()) + .then()); } public Mono save(User user) { SimpleDateFormat formatter = new SimpleDateFormat(DateUtils.YMD); String time = formatter.format(user.getRegTime()); - return mono.flatMapMany(connection -> - connection.createStatement("insert into user values (:id,:appId,:version,:regTime)") - .bind("id", user.getId()) - .bind("appId", user.getAppId()) - .bind("version", user.getVersion()) - .bind("regTime", time) - .execute() - ).then(); + return mono + .flatMapMany( + connection -> connection.createStatement("insert into user values (:id,:appId,:version,:regTime)") + .bind("id", user.getId()) + .bind("appId", user.getAppId()) + .bind("version", user.getVersion()) + .bind("regTime", time) + .execute()) + .then(); } + } diff --git a/spring-boot-example/spring-clickhouse/spring-clickhouse-r2dbc/src/main/java/com/livk/ck/r2dbc/service/UserService.java b/spring-boot-example/spring-clickhouse/spring-clickhouse-r2dbc/src/main/java/com/livk/ck/r2dbc/service/UserService.java index becaa3b4a..c3131c437 100644 --- a/spring-boot-example/spring-clickhouse/spring-clickhouse-r2dbc/src/main/java/com/livk/ck/r2dbc/service/UserService.java +++ b/spring-boot-example/spring-clickhouse/spring-clickhouse-r2dbc/src/main/java/com/livk/ck/r2dbc/service/UserService.java @@ -35,4 +35,5 @@ public interface UserService { Mono remove(Mono id); Mono save(Mono userMono); + } diff --git a/spring-boot-example/spring-clickhouse/spring-clickhouse-r2dbc/src/main/java/com/livk/ck/r2dbc/service/impl/UserServiceImpl.java b/spring-boot-example/spring-clickhouse/spring-clickhouse-r2dbc/src/main/java/com/livk/ck/r2dbc/service/impl/UserServiceImpl.java index 51e07b6fd..d51bb7650 100644 --- a/spring-boot-example/spring-clickhouse/spring-clickhouse-r2dbc/src/main/java/com/livk/ck/r2dbc/service/impl/UserServiceImpl.java +++ b/spring-boot-example/spring-clickhouse/spring-clickhouse-r2dbc/src/main/java/com/livk/ck/r2dbc/service/impl/UserServiceImpl.java @@ -52,4 +52,5 @@ public Mono remove(Mono id) { public Mono save(Mono userMono) { return userMono.flatMap(userRepository::save); } + } diff --git a/spring-boot-example/spring-clickhouse/spring-clickhouse-r2dbc/src/test/java/com/livk/ck/r2dbc/controller/UserControllerTest.java b/spring-boot-example/spring-clickhouse/spring-clickhouse-r2dbc/src/test/java/com/livk/ck/r2dbc/controller/UserControllerTest.java index b0e343550..2d5d93ced 100644 --- a/spring-boot-example/spring-clickhouse/spring-clickhouse-r2dbc/src/test/java/com/livk/ck/r2dbc/controller/UserControllerTest.java +++ b/spring-boot-example/spring-clickhouse/spring-clickhouse-r2dbc/src/test/java/com/livk/ck/r2dbc/controller/UserControllerTest.java @@ -43,6 +43,7 @@ @AutoConfigureWebTestClient(timeout = "15000") @TestMethodOrder(MethodOrderer.OrderAnnotation.class) class UserControllerTest { + @Autowired WebTestClient client; @@ -61,26 +62,14 @@ void testUsers() { @Order(1) @Test void testSave() { - User user = new User().setId(Integer.MAX_VALUE) - .setAppId("appId") - .setVersion("version") - .setRegTime(new Date()); - client.post() - .uri("/user") - .bodyValue(user) - .accept(MediaType.APPLICATION_JSON) - .exchange() - .expectStatus() - .isOk(); + User user = new User().setId(Integer.MAX_VALUE).setAppId("appId").setVersion("version").setRegTime(new Date()); + client.post().uri("/user").bodyValue(user).accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isOk(); } @Order(3) @Test void testDelete() { - client.delete() - .uri("/user/{id}", Integer.MAX_VALUE) - .exchange() - .expectStatus() - .isOk(); + client.delete().uri("/user/{id}", Integer.MAX_VALUE).exchange().expectStatus().isOk(); } + } diff --git a/spring-boot-example/spring-crypto/crypto-commons/src/main/java/com/livk/crypto/CryptoAutoConfiguration.java b/spring-boot-example/spring-crypto/crypto-commons/src/main/java/com/livk/crypto/CryptoAutoConfiguration.java index a097fd663..f46aa6e86 100644 --- a/spring-boot-example/spring-crypto/crypto-commons/src/main/java/com/livk/crypto/CryptoAutoConfiguration.java +++ b/spring-boot-example/spring-crypto/crypto-commons/src/main/java/com/livk/crypto/CryptoAutoConfiguration.java @@ -64,6 +64,7 @@ public static class CryptoMvcAutoConfiguration implements WebMvcConfigurer { public void addFormatters(FormatterRegistry registry) { registry.addFormatterForFieldAnnotation(new SpringAnnotationFormatterFactory(cryptoFormatters)); } + } @AutoConfiguration @@ -77,5 +78,7 @@ public static class CryptoWebfluxAutoConfiguration implements WebFluxConfigurer public void addFormatters(FormatterRegistry registry) { registry.addFormatterForFieldAnnotation(new SpringAnnotationFormatterFactory(cryptoFormatters)); } + } + } diff --git a/spring-boot-example/spring-crypto/crypto-commons/src/main/java/com/livk/crypto/CryptoProperties.java b/spring-boot-example/spring-crypto/crypto-commons/src/main/java/com/livk/crypto/CryptoProperties.java index 9e9fcfc6c..1807fa054 100644 --- a/spring-boot-example/spring-crypto/crypto-commons/src/main/java/com/livk/crypto/CryptoProperties.java +++ b/spring-boot-example/spring-crypto/crypto-commons/src/main/java/com/livk/crypto/CryptoProperties.java @@ -34,4 +34,5 @@ public class CryptoProperties { private CryptoType type; private Map metadata; + } diff --git a/spring-boot-example/spring-crypto/crypto-commons/src/main/java/com/livk/crypto/CryptoType.java b/spring-boot-example/spring-crypto/crypto-commons/src/main/java/com/livk/crypto/CryptoType.java index b79ca1280..afdb247d1 100644 --- a/spring-boot-example/spring-crypto/crypto-commons/src/main/java/com/livk/crypto/CryptoType.java +++ b/spring-boot-example/spring-crypto/crypto-commons/src/main/java/com/livk/crypto/CryptoType.java @@ -51,7 +51,8 @@ public String unwrap(String str) { str = str.replaceFirst(algorithm + "\\(", ""); int length = str.length(); return str.substring(0, length - 1); - } else { + } + else { return str; } } @@ -59,4 +60,5 @@ public String unwrap(String str) { private boolean checkWrapper(String str) { return str.startsWith(algorithm + "(") && str.endsWith(")"); } + } diff --git a/spring-boot-example/spring-crypto/crypto-commons/src/main/java/com/livk/crypto/annotation/CryptoDecrypt.java b/spring-boot-example/spring-crypto/crypto-commons/src/main/java/com/livk/crypto/annotation/CryptoDecrypt.java index 0f3a46417..a1171591f 100644 --- a/spring-boot-example/spring-crypto/crypto-commons/src/main/java/com/livk/crypto/annotation/CryptoDecrypt.java +++ b/spring-boot-example/spring-crypto/crypto-commons/src/main/java/com/livk/crypto/annotation/CryptoDecrypt.java @@ -31,7 +31,7 @@ * * @author livk */ -@Target({ElementType.PARAMETER, ElementType.FIELD}) +@Target({ ElementType.PARAMETER, ElementType.FIELD }) @Retention(RetentionPolicy.RUNTIME) @JacksonAnnotationsInside @JsonDeserialize(using = CryptoJsonDeserializer.class) diff --git a/spring-boot-example/spring-crypto/crypto-commons/src/main/java/com/livk/crypto/annotation/CryptoEncrypt.java b/spring-boot-example/spring-crypto/crypto-commons/src/main/java/com/livk/crypto/annotation/CryptoEncrypt.java index e61097794..5052c59c7 100644 --- a/spring-boot-example/spring-crypto/crypto-commons/src/main/java/com/livk/crypto/annotation/CryptoEncrypt.java +++ b/spring-boot-example/spring-crypto/crypto-commons/src/main/java/com/livk/crypto/annotation/CryptoEncrypt.java @@ -30,15 +30,16 @@ /** * @author livk */ -@Target({ElementType.FIELD}) +@Target({ ElementType.FIELD }) @Retention(RetentionPolicy.RUNTIME) @JacksonAnnotationsInside @JsonSerialize(using = CryptoJsonSerializer.class) public @interface CryptoEncrypt { + /** * Value crypto type. - * * @return the crypto type */ CryptoType value(); + } diff --git a/spring-boot-example/spring-crypto/crypto-commons/src/main/java/com/livk/crypto/exception/FormatterNotFountException.java b/spring-boot-example/spring-crypto/crypto-commons/src/main/java/com/livk/crypto/exception/FormatterNotFountException.java index d685b7839..4f5425f17 100644 --- a/spring-boot-example/spring-crypto/crypto-commons/src/main/java/com/livk/crypto/exception/FormatterNotFountException.java +++ b/spring-boot-example/spring-crypto/crypto-commons/src/main/java/com/livk/crypto/exception/FormatterNotFountException.java @@ -24,10 +24,10 @@ public class FormatterNotFountException extends RuntimeException { /** * Instantiates a new Formatter not fount exception. - * * @param message the message */ public FormatterNotFountException(String message) { super(message); } + } diff --git a/spring-boot-example/spring-crypto/crypto-commons/src/main/java/com/livk/crypto/exception/MetadataFailureAnalyzer.java b/spring-boot-example/spring-crypto/crypto-commons/src/main/java/com/livk/crypto/exception/MetadataFailureAnalyzer.java index ede5ad5f4..aa1e65ff6 100644 --- a/spring-boot-example/spring-crypto/crypto-commons/src/main/java/com/livk/crypto/exception/MetadataFailureAnalyzer.java +++ b/spring-boot-example/spring-crypto/crypto-commons/src/main/java/com/livk/crypto/exception/MetadataFailureAnalyzer.java @@ -27,8 +27,10 @@ */ @SpringFactories(FailureAnalyzer.class) public class MetadataFailureAnalyzer extends AbstractFailureAnalyzer { + @Override protected FailureAnalysis analyze(Throwable rootFailure, MetadataIllegalException cause) { return new FailureAnalysis(cause.getMessage(), cause.getAction(), cause); } + } diff --git a/spring-boot-example/spring-crypto/crypto-commons/src/main/java/com/livk/crypto/exception/MetadataIllegalException.java b/spring-boot-example/spring-crypto/crypto-commons/src/main/java/com/livk/crypto/exception/MetadataIllegalException.java index 099ca7977..ec06da77d 100644 --- a/spring-boot-example/spring-crypto/crypto-commons/src/main/java/com/livk/crypto/exception/MetadataIllegalException.java +++ b/spring-boot-example/spring-crypto/crypto-commons/src/main/java/com/livk/crypto/exception/MetadataIllegalException.java @@ -29,11 +29,11 @@ public class MetadataIllegalException extends RuntimeException { /** * Instantiates a new Metadata illegal exception. - * * @param message the message */ public MetadataIllegalException(String message, String action) { super(message); this.action = action; } + } diff --git a/spring-boot-example/spring-crypto/crypto-commons/src/main/java/com/livk/crypto/fotmat/AbstractCryptoFormatter.java b/spring-boot-example/spring-crypto/crypto-commons/src/main/java/com/livk/crypto/fotmat/AbstractCryptoFormatter.java index 97f2368ff..64f378d21 100644 --- a/spring-boot-example/spring-crypto/crypto-commons/src/main/java/com/livk/crypto/fotmat/AbstractCryptoFormatter.java +++ b/spring-boot-example/spring-crypto/crypto-commons/src/main/java/com/livk/crypto/fotmat/AbstractCryptoFormatter.java @@ -41,7 +41,8 @@ public final String format(T value) { String convert = convert(value); byte[] encrypt = encrypt(convert.getBytes(StandardCharsets.UTF_8)); return Base64.getEncoder().encodeToString(encrypt); - } catch (Exception e) { + } + catch (Exception e) { LOG.error("format error:{}", e.getMessage()); throw new RuntimeException(e); } @@ -54,7 +55,8 @@ public final T parse(String text) { byte[] decrypt = decrypt(decode); String result = new String(decrypt, StandardCharsets.UTF_8); return convert(result); - } catch (Exception e) { + } + catch (Exception e) { LOG.error("parse error:{}", e.getMessage()); throw new RuntimeException(e); } @@ -62,7 +64,6 @@ public final T parse(String text) { /** * Decrypt byte [ ]. - * * @param bytes the bytes * @return the byte [ ] */ @@ -70,7 +71,6 @@ public final T parse(String text) { /** * Encrypt byte [ ]. - * * @param bytes the bytes * @return the byte [ ] */ @@ -78,7 +78,6 @@ public final T parse(String text) { /** * Convert t. - * * @param decryptValue the decrypt value * @return the t */ @@ -86,9 +85,9 @@ public final T parse(String text) { /** * Convert string. - * * @param encryptValue the encrypt value * @return the string */ protected abstract String convert(T encryptValue) throws Exception; + } diff --git a/spring-boot-example/spring-crypto/crypto-commons/src/main/java/com/livk/crypto/fotmat/CryptoFormatter.java b/spring-boot-example/spring-crypto/crypto-commons/src/main/java/com/livk/crypto/fotmat/CryptoFormatter.java index 56fcfa568..f284ff890 100644 --- a/spring-boot-example/spring-crypto/crypto-commons/src/main/java/com/livk/crypto/fotmat/CryptoFormatter.java +++ b/spring-boot-example/spring-crypto/crypto-commons/src/main/java/com/livk/crypto/fotmat/CryptoFormatter.java @@ -40,7 +40,6 @@ public interface CryptoFormatter extends Formatter { /** * From context object provider. - * * @return the object provider */ static Map, List>> fromContext() { @@ -54,7 +53,6 @@ static Map, List>> fromContext(BeanFactory beanFacto .collect(Collectors.groupingBy(CryptoFormatter::supportClass)); } - @Override default T parse(String text, Locale locale) throws ParseException { return parse(text); @@ -67,7 +65,6 @@ default String print(T object, Locale locale) { /** * Support class. - * * @return the class */ default Class supportClass() { @@ -80,8 +77,8 @@ default Class supportClass() { /** * Type crypto type. - * * @return the crypto type */ CryptoType type(); + } diff --git a/spring-boot-example/spring-crypto/crypto-commons/src/main/java/com/livk/crypto/fotmat/SpringAnnotationFormatterFactory.java b/spring-boot-example/spring-crypto/crypto-commons/src/main/java/com/livk/crypto/fotmat/SpringAnnotationFormatterFactory.java index 163a99715..1533d51f1 100644 --- a/spring-boot-example/spring-crypto/crypto-commons/src/main/java/com/livk/crypto/fotmat/SpringAnnotationFormatterFactory.java +++ b/spring-boot-example/spring-crypto/crypto-commons/src/main/java/com/livk/crypto/fotmat/SpringAnnotationFormatterFactory.java @@ -38,8 +38,7 @@ public class SpringAnnotationFormatterFactory implements AnnotationFormatterFact private final Map, List>> map; public SpringAnnotationFormatterFactory(ObjectProvider> cryptoFormatters) { - map = cryptoFormatters.orderedStream() - .collect(Collectors.groupingBy(CryptoFormatter::supportClass)); + map = cryptoFormatters.orderedStream().collect(Collectors.groupingBy(CryptoFormatter::supportClass)); } @Override @@ -64,4 +63,5 @@ public Parser getParser(CryptoDecrypt annotation, Class fieldType) { throw new FormatterNotFountException("fieldType:" + fieldType + " Parser NotFount!"); }; } + } diff --git a/spring-boot-example/spring-crypto/crypto-commons/src/main/java/com/livk/crypto/jackson/CryptoJsonDeserializer.java b/spring-boot-example/spring-crypto/crypto-commons/src/main/java/com/livk/crypto/jackson/CryptoJsonDeserializer.java index f42903ea6..b22e48927 100644 --- a/spring-boot-example/spring-crypto/crypto-commons/src/main/java/com/livk/crypto/jackson/CryptoJsonDeserializer.java +++ b/spring-boot-example/spring-crypto/crypto-commons/src/main/java/com/livk/crypto/jackson/CryptoJsonDeserializer.java @@ -48,13 +48,15 @@ public Object deserialize(JsonParser p, DeserializationContext context) throws I } try { return parser.parse(type.unwrap(text)); - } catch (ParseException e) { + } + catch (ParseException e) { throw new JsonParseException(p, e.getMessage()); } } @Override - public JsonDeserializer createContextual(DeserializationContext context, BeanProperty property) throws JsonMappingException { + public JsonDeserializer createContextual(DeserializationContext context, BeanProperty property) + throws JsonMappingException { javaType = property.getType(); defaultJsonDeserializer = context.findContextualValueDeserializer(javaType, property); return this; @@ -68,4 +70,5 @@ private CryptoFormatter getCryptoFormatter(CryptoType type) { } return null; } + } diff --git a/spring-boot-example/spring-crypto/crypto-commons/src/main/java/com/livk/crypto/jackson/CryptoJsonSerializer.java b/spring-boot-example/spring-crypto/crypto-commons/src/main/java/com/livk/crypto/jackson/CryptoJsonSerializer.java index 83cdfacab..b04c4f9e1 100644 --- a/spring-boot-example/spring-crypto/crypto-commons/src/main/java/com/livk/crypto/jackson/CryptoJsonSerializer.java +++ b/spring-boot-example/spring-crypto/crypto-commons/src/main/java/com/livk/crypto/jackson/CryptoJsonSerializer.java @@ -47,7 +47,8 @@ public void serialize(Object value, JsonGenerator gen, SerializerProvider serial @SuppressWarnings("unchecked") @Override - public JsonSerializer createContextual(SerializerProvider prov, BeanProperty property) throws JsonMappingException { + public JsonSerializer createContextual(SerializerProvider prov, BeanProperty property) + throws JsonMappingException { JavaType javaType = property.getType(); CryptoEncrypt encrypt = Optional.ofNullable(property.getAnnotation((CryptoEncrypt.class))) .orElse(property.getContextAnnotation(CryptoEncrypt.class)); @@ -66,4 +67,5 @@ private CryptoFormatter getCryptoFormatter(Class rawClass, CryptoType type } return null; } + } diff --git a/spring-boot-example/spring-crypto/crypto-commons/src/main/java/com/livk/crypto/support/AesSecurity.java b/spring-boot-example/spring-crypto/crypto-commons/src/main/java/com/livk/crypto/support/AesSecurity.java index ebddda5c1..ebdac11da 100644 --- a/spring-boot-example/spring-crypto/crypto-commons/src/main/java/com/livk/crypto/support/AesSecurity.java +++ b/spring-boot-example/spring-crypto/crypto-commons/src/main/java/com/livk/crypto/support/AesSecurity.java @@ -35,6 +35,7 @@ */ @Slf4j public class AesSecurity extends AbstractCryptoFormatter { + private static final String DEFAULT_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding"; private final SecretKeySpec spec; @@ -49,7 +50,8 @@ public AesSecurity(Map metadata) { kg.init(256, new SecureRandom(salt.getBytes())); SecretKey secretKey = kg.generateKey(); spec = new SecretKeySpec(secretKey.getEncoded(), CryptoType.AES.getAlgorithm()); - } catch (Exception e) { + } + catch (Exception e) { throw new RuntimeException(e); } } @@ -82,4 +84,5 @@ protected String convert(Long encryptValue) { public CryptoType type() { return CryptoType.AES; } + } diff --git a/spring-boot-example/spring-crypto/crypto-commons/src/main/java/com/livk/crypto/support/PbeSecurity.java b/spring-boot-example/spring-crypto/crypto-commons/src/main/java/com/livk/crypto/support/PbeSecurity.java index 4ad11c1d7..11218f559 100644 --- a/spring-boot-example/spring-crypto/crypto-commons/src/main/java/com/livk/crypto/support/PbeSecurity.java +++ b/spring-boot-example/spring-crypto/crypto-commons/src/main/java/com/livk/crypto/support/PbeSecurity.java @@ -56,12 +56,12 @@ public PbeSecurity(Map metadata) { SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(CIPHER_NAME); secretKey = secretKeyFactory.generateSecret(keySpec); pbeParameterSpec = new PBEParameterSpec(salt.getBytes(), 1000); - } catch (Exception e) { + } + catch (Exception e) { throw new RuntimeException(e); } } - @Override protected byte[] decrypt(byte[] decode) throws Exception { Cipher cipher = Cipher.getInstance(CIPHER_NAME); @@ -90,4 +90,5 @@ protected String convert(Long encryptValue) { public CryptoType type() { return CryptoType.PBE; } + } diff --git a/spring-boot-example/spring-crypto/spring-crypto-mvc/src/main/java/com/livk/crypto/mvc/CryptoMvcApp.java b/spring-boot-example/spring-crypto/spring-crypto-mvc/src/main/java/com/livk/crypto/mvc/CryptoMvcApp.java index a961477a3..f229dffa6 100644 --- a/spring-boot-example/spring-crypto/spring-crypto-mvc/src/main/java/com/livk/crypto/mvc/CryptoMvcApp.java +++ b/spring-boot-example/spring-crypto/spring-crypto-mvc/src/main/java/com/livk/crypto/mvc/CryptoMvcApp.java @@ -25,7 +25,9 @@ */ @SpringBootApplication public class CryptoMvcApp { + public static void main(String[] args) { SpringLauncher.run(args); } + } diff --git a/spring-boot-example/spring-crypto/spring-crypto-mvc/src/main/java/com/livk/crypto/mvc/controller/InfoController.java b/spring-boot-example/spring-crypto/spring-crypto-mvc/src/main/java/com/livk/crypto/mvc/controller/InfoController.java index 485c69aea..f0414875b 100644 --- a/spring-boot-example/spring-crypto/spring-crypto-mvc/src/main/java/com/livk/crypto/mvc/controller/InfoController.java +++ b/spring-boot-example/spring-crypto/spring-crypto-mvc/src/main/java/com/livk/crypto/mvc/controller/InfoController.java @@ -40,9 +40,10 @@ public Map info(@RequestBody Info info) { @GetMapping public Map info(@RequestHeader("id") @CryptoDecrypt Long headerId, - @RequestParam("id") @CryptoDecrypt Long paramId) { + @RequestParam("id") @CryptoDecrypt Long paramId) { log.info("RequestHeader:{}", headerId); log.info("RequestParam:{}", paramId); return Map.of("id", new Info(headerId, paramId)); } + } diff --git a/spring-boot-example/spring-crypto/spring-crypto-mvc/src/main/java/com/livk/crypto/mvc/entity/Info.java b/spring-boot-example/spring-crypto/spring-crypto-mvc/src/main/java/com/livk/crypto/mvc/entity/Info.java index e1cdf27a6..d4be172ee 100644 --- a/spring-boot-example/spring-crypto/spring-crypto-mvc/src/main/java/com/livk/crypto/mvc/entity/Info.java +++ b/spring-boot-example/spring-crypto/spring-crypto-mvc/src/main/java/com/livk/crypto/mvc/entity/Info.java @@ -31,6 +31,7 @@ @NoArgsConstructor @AllArgsConstructor public class Info { + @CryptoEncrypt(CryptoType.AES) @CryptoDecrypt private Long headerId; @@ -38,4 +39,5 @@ public class Info { @CryptoEncrypt(CryptoType.AES) @CryptoDecrypt private Long paramId; + } diff --git a/spring-boot-example/spring-crypto/spring-crypto-mvc/src/test/java/com/livk/crypto/mvc/controller/InfoMvcControllerTest.java b/spring-boot-example/spring-crypto/spring-crypto-mvc/src/test/java/com/livk/crypto/mvc/controller/InfoMvcControllerTest.java index 643112bac..6deb70f5d 100644 --- a/spring-boot-example/spring-crypto/spring-crypto-mvc/src/test/java/com/livk/crypto/mvc/controller/InfoMvcControllerTest.java +++ b/spring-boot-example/spring-crypto/spring-crypto-mvc/src/test/java/com/livk/crypto/mvc/controller/InfoMvcControllerTest.java @@ -53,9 +53,7 @@ class InfoMvcControllerTest { void infoGet() throws Exception { String encoding = aesSecurity.print(654321L, Locale.CHINA); encoding = CryptoType.AES.wrapper(encoding); - mockMvc.perform(get("/info") - .param("id", encoding) - .header("id", encoding)) + mockMvc.perform(get("/info").param("id", encoding).header("id", encoding)) .andDo(print()) .andExpect(status().isOk()) .andExpect(jsonPath("id.paramId", encoding).exists()) @@ -67,12 +65,11 @@ void infoPost() throws Exception { String encoding = aesSecurity.print(654321L, Locale.CHINA); encoding = CryptoType.AES.wrapper(encoding); String json = JsonMapperUtils.writeValueAsString(Map.of("headerId", encoding, "paramId", encoding)); - mockMvc.perform(post("/info") - .contentType(MediaType.APPLICATION_JSON) - .content(json)) + mockMvc.perform(post("/info").contentType(MediaType.APPLICATION_JSON).content(json)) .andDo(print()) .andExpect(status().isOk()) .andExpect(jsonPath("body.paramId", encoding).exists()) .andExpect(jsonPath("body.headerId", encoding).exists()); } + } diff --git a/spring-boot-example/spring-crypto/spring-crypto-webflux/src/main/java/com/livk/crypto/webflux/CryptoWebFluxApp.java b/spring-boot-example/spring-crypto/spring-crypto-webflux/src/main/java/com/livk/crypto/webflux/CryptoWebFluxApp.java index 3950c2f5c..9535d313e 100644 --- a/spring-boot-example/spring-crypto/spring-crypto-webflux/src/main/java/com/livk/crypto/webflux/CryptoWebFluxApp.java +++ b/spring-boot-example/spring-crypto/spring-crypto-webflux/src/main/java/com/livk/crypto/webflux/CryptoWebFluxApp.java @@ -25,7 +25,9 @@ */ @SpringBootApplication public class CryptoWebFluxApp { + public static void main(String[] args) { SpringLauncher.run(args); } + } diff --git a/spring-boot-example/spring-crypto/spring-crypto-webflux/src/main/java/com/livk/crypto/webflux/controller/InfoController.java b/spring-boot-example/spring-crypto/spring-crypto-webflux/src/main/java/com/livk/crypto/webflux/controller/InfoController.java index 31db298c6..01b18c3a0 100644 --- a/spring-boot-example/spring-crypto/spring-crypto-webflux/src/main/java/com/livk/crypto/webflux/controller/InfoController.java +++ b/spring-boot-example/spring-crypto/spring-crypto-webflux/src/main/java/com/livk/crypto/webflux/controller/InfoController.java @@ -40,9 +40,10 @@ public Map info(@RequestBody Info info) { @GetMapping public Map info(@RequestHeader("id") @CryptoDecrypt Long headerId, - @RequestParam("id") @CryptoDecrypt Long paramId) { + @RequestParam("id") @CryptoDecrypt Long paramId) { log.info("RequestHeader:{}", headerId); log.info("RequestParam:{}", paramId); return Map.of("id", new Info(headerId, paramId)); } + } diff --git a/spring-boot-example/spring-crypto/spring-crypto-webflux/src/main/java/com/livk/crypto/webflux/entity/Info.java b/spring-boot-example/spring-crypto/spring-crypto-webflux/src/main/java/com/livk/crypto/webflux/entity/Info.java index 473aed134..297d123a6 100644 --- a/spring-boot-example/spring-crypto/spring-crypto-webflux/src/main/java/com/livk/crypto/webflux/entity/Info.java +++ b/spring-boot-example/spring-crypto/spring-crypto-webflux/src/main/java/com/livk/crypto/webflux/entity/Info.java @@ -31,6 +31,7 @@ @NoArgsConstructor @AllArgsConstructor public class Info { + @CryptoEncrypt(CryptoType.PBE) @CryptoDecrypt private Long headerId; @@ -38,4 +39,5 @@ public class Info { @CryptoEncrypt(CryptoType.PBE) @CryptoDecrypt private Long paramId; + } diff --git a/spring-boot-example/spring-crypto/spring-crypto-webflux/src/test/java/com/livk/crypto/webflux/controller/InfoWebFluxControllerTest.java b/spring-boot-example/spring-crypto/spring-crypto-webflux/src/test/java/com/livk/crypto/webflux/controller/InfoWebFluxControllerTest.java index 0a691b73f..bd813d871 100644 --- a/spring-boot-example/spring-crypto/spring-crypto-webflux/src/test/java/com/livk/crypto/webflux/controller/InfoWebFluxControllerTest.java +++ b/spring-boot-example/spring-crypto/spring-crypto-webflux/src/test/java/com/livk/crypto/webflux/controller/InfoWebFluxControllerTest.java @@ -51,9 +51,7 @@ void infoGet() { String encodingStr = pbeSecurity.print(654321L, Locale.CHINA); String encoding = CryptoType.PBE.wrapper(encodingStr); client.get() - .uri(uriBuilder -> uriBuilder.path("/info") - .queryParam("id", encoding) - .build()) + .uri(uriBuilder -> uriBuilder.path("/info").queryParam("id", encoding).build()) .header("id", encoding) .exchange() .expectStatus() @@ -87,4 +85,5 @@ void infoPost() { assertEquals(encoding, JsonNodeUtils.findNode(jsonNode, "body.headerId").asText()); }); } + } diff --git a/spring-boot-example/spring-data-rest/src/main/java/com/livk/rest/RestApp.java b/spring-boot-example/spring-data-rest/src/main/java/com/livk/rest/RestApp.java index aa3b175ee..481027bf8 100644 --- a/spring-boot-example/spring-data-rest/src/main/java/com/livk/rest/RestApp.java +++ b/spring-boot-example/spring-data-rest/src/main/java/com/livk/rest/RestApp.java @@ -8,7 +8,9 @@ */ @SpringBootApplication public class RestApp { + public static void main(String[] args) { SpringLauncher.run(args); } + } diff --git a/spring-boot-example/spring-data-rest/src/main/java/com/livk/rest/entity/User.java b/spring-boot-example/spring-data-rest/src/main/java/com/livk/rest/entity/User.java index f308fe5f1..e301ca95a 100644 --- a/spring-boot-example/spring-data-rest/src/main/java/com/livk/rest/entity/User.java +++ b/spring-boot-example/spring-data-rest/src/main/java/com/livk/rest/entity/User.java @@ -11,6 +11,7 @@ @Data @Entity(name = "`user`") public class User implements Serializable { + @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @@ -21,4 +22,5 @@ public class User implements Serializable { @Column(length = 20) private Integer age; + } diff --git a/spring-boot-example/spring-data-rest/src/test/java/com/livk/rest/RestAppTest.java b/spring-boot-example/spring-data-rest/src/test/java/com/livk/rest/RestAppTest.java index 91f629d12..76b8eba13 100644 --- a/spring-boot-example/spring-data-rest/src/test/java/com/livk/rest/RestAppTest.java +++ b/spring-boot-example/spring-data-rest/src/test/java/com/livk/rest/RestAppTest.java @@ -52,8 +52,7 @@ void testSave() throws Exception { user.setUsername("root"); user.setPassword("root"); user.setAge(18); - mockMvc.perform(post("/rest/api/user") - .content(support.writeValueAsBytes(user))) + mockMvc.perform(post("/rest/api/user").content(support.writeValueAsBytes(user))) .andDo(print()) .andExpect(status().is2xxSuccessful()); } @@ -67,8 +66,7 @@ void testUpdate() throws Exception { user.setUsername("admin"); user.setPassword("admin"); user.setAge(19); - mockMvc.perform(put("/rest/api/user/{id}", 1) - .content(support.writeValueAsBytes(user))) + mockMvc.perform(put("/rest/api/user/{id}", 1).content(support.writeValueAsBytes(user))) .andDo(print()) .andExpect(status().is2xxSuccessful()); } @@ -76,17 +74,13 @@ void testUpdate() throws Exception { @Order(6) @Test void testDelete() throws Exception { - mockMvc.perform(delete("/rest/api/user/{id}", 1)) - .andDo(print()) - .andExpect(status().is2xxSuccessful()); + mockMvc.perform(delete("/rest/api/user/{id}", 1)).andDo(print()).andExpect(status().is2xxSuccessful()); } @Order(4) @Test void testAuth() throws Exception { - mockMvc.perform(get("/rest/api/user/search/auth") - .param("name", "admin") - .param("pwd", "admin")) + mockMvc.perform(get("/rest/api/user/search/auth").param("name", "admin").param("pwd", "admin")) .andDo(print()) .andExpect(status().is2xxSuccessful()) .andExpect(jsonPath("username", "admin").exists()) @@ -108,4 +102,5 @@ void testList() throws Exception { .andExpect(jsonPath("page.totalPages", 1).exists()) .andExpect(jsonPath("page.number", 0).exists()); } + } diff --git a/spring-boot-example/spring-doc/spring-doc-mvc/src/main/java/com/livk/doc/mvc/MvcDocApp.java b/spring-boot-example/spring-doc/spring-doc-mvc/src/main/java/com/livk/doc/mvc/MvcDocApp.java index c560da6c8..8b2e7e0df 100644 --- a/spring-boot-example/spring-doc/spring-doc-mvc/src/main/java/com/livk/doc/mvc/MvcDocApp.java +++ b/spring-boot-example/spring-doc/spring-doc-mvc/src/main/java/com/livk/doc/mvc/MvcDocApp.java @@ -29,7 +29,9 @@ */ @SpringBootApplication public class MvcDocApp { + public static void main(String[] args) { SpringLauncher.run(args); } + } diff --git a/spring-boot-example/spring-doc/spring-doc-mvc/src/main/java/com/livk/doc/mvc/config/SpringDocConfig.java b/spring-boot-example/spring-doc/spring-doc-mvc/src/main/java/com/livk/doc/mvc/config/SpringDocConfig.java index e9efe31e1..208275ba0 100644 --- a/spring-boot-example/spring-doc/spring-doc-mvc/src/main/java/com/livk/doc/mvc/config/SpringDocConfig.java +++ b/spring-boot-example/spring-doc/spring-doc-mvc/src/main/java/com/livk/doc/mvc/config/SpringDocConfig.java @@ -37,9 +37,7 @@ public class SpringDocConfig { @Bean public OpenAPI openAPI() { return new OpenAPI() - .info(new Info().title("spring doc webmvc api") - .description("spring doc webmvc api") - .version("1.0.0")); + .info(new Info().title("spring doc webmvc api").description("spring doc webmvc api").version("1.0.0")); } @Bean @@ -50,4 +48,5 @@ public GroupedOpenApi openApi() { .pathsToMatch("/**") .build(); } + } diff --git a/spring-boot-example/spring-doc/spring-doc-mvc/src/main/java/com/livk/doc/mvc/controller/DocController.java b/spring-boot-example/spring-doc/spring-doc-mvc/src/main/java/com/livk/doc/mvc/controller/DocController.java index 50c798b21..241ddd90a 100644 --- a/spring-boot-example/spring-doc/spring-doc-mvc/src/main/java/com/livk/doc/mvc/controller/DocController.java +++ b/spring-boot-example/spring-doc/spring-doc-mvc/src/main/java/com/livk/doc/mvc/controller/DocController.java @@ -42,4 +42,5 @@ public class DocController { public HttpEntity get() { return ResponseEntity.ok("hello world"); } + } diff --git a/spring-boot-example/spring-doc/spring-doc-mvc/src/test/java/com/livk/doc/mvc/controller/DocControllerTest.java b/spring-boot-example/spring-doc/spring-doc-mvc/src/test/java/com/livk/doc/mvc/controller/DocControllerTest.java index c871a1460..7027481e1 100644 --- a/spring-boot-example/spring-doc/spring-doc-mvc/src/test/java/com/livk/doc/mvc/controller/DocControllerTest.java +++ b/spring-boot-example/spring-doc/spring-doc-mvc/src/test/java/com/livk/doc/mvc/controller/DocControllerTest.java @@ -45,4 +45,5 @@ public void test() throws Exception { .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(jsonPath("openapi", "3.0.1").exists()); } + } diff --git a/spring-boot-example/spring-doc/spring-doc-webflux/src/main/java/com/livk/doc/webflux/WebfluxDocApp.java b/spring-boot-example/spring-doc/spring-doc-webflux/src/main/java/com/livk/doc/webflux/WebfluxDocApp.java index 76bb3d6b4..664a2e655 100644 --- a/spring-boot-example/spring-doc/spring-doc-webflux/src/main/java/com/livk/doc/webflux/WebfluxDocApp.java +++ b/spring-boot-example/spring-doc/spring-doc-webflux/src/main/java/com/livk/doc/webflux/WebfluxDocApp.java @@ -29,7 +29,9 @@ */ @SpringBootApplication public class WebfluxDocApp { + public static void main(String[] args) { SpringLauncher.run(args); } + } diff --git a/spring-boot-example/spring-doc/spring-doc-webflux/src/main/java/com/livk/doc/webflux/config/SpringDocConfig.java b/spring-boot-example/spring-doc/spring-doc-webflux/src/main/java/com/livk/doc/webflux/config/SpringDocConfig.java index ab1cf7085..57f5cb650 100644 --- a/spring-boot-example/spring-doc/spring-doc-webflux/src/main/java/com/livk/doc/webflux/config/SpringDocConfig.java +++ b/spring-boot-example/spring-doc/spring-doc-webflux/src/main/java/com/livk/doc/webflux/config/SpringDocConfig.java @@ -37,9 +37,7 @@ public class SpringDocConfig { @Bean public OpenAPI openAPI() { return new OpenAPI() - .info(new Info().title("spring doc webflux api") - .description("spring doc webflux api") - .version("1.0.0")); + .info(new Info().title("spring doc webflux api").description("spring doc webflux api").version("1.0.0")); } @Bean @@ -50,4 +48,5 @@ public GroupedOpenApi openApi() { .pathsToMatch("/**") .build(); } + } diff --git a/spring-boot-example/spring-doc/spring-doc-webflux/src/main/java/com/livk/doc/webflux/controller/DocController.java b/spring-boot-example/spring-doc/spring-doc-webflux/src/main/java/com/livk/doc/webflux/controller/DocController.java index 4c2d8dd28..79bc792d9 100644 --- a/spring-boot-example/spring-doc/spring-doc-webflux/src/main/java/com/livk/doc/webflux/controller/DocController.java +++ b/spring-boot-example/spring-doc/spring-doc-webflux/src/main/java/com/livk/doc/webflux/controller/DocController.java @@ -43,4 +43,5 @@ public class DocController { public Mono> get() { return Mono.just(ResponseEntity.ok("hello world")); } + } diff --git a/spring-boot-example/spring-doc/spring-doc-webflux/src/test/java/com/livk/doc/webflux/controller/DocControllerTest.java b/spring-boot-example/spring-doc/spring-doc-webflux/src/test/java/com/livk/doc/webflux/controller/DocControllerTest.java index 4cc0a705d..91fe8a880 100644 --- a/spring-boot-example/spring-doc/spring-doc-webflux/src/test/java/com/livk/doc/webflux/controller/DocControllerTest.java +++ b/spring-boot-example/spring-doc/spring-doc-webflux/src/test/java/com/livk/doc/webflux/controller/DocControllerTest.java @@ -34,6 +34,7 @@ @SpringBootTest @AutoConfigureWebTestClient class DocControllerTest { + @Autowired WebTestClient client; @@ -49,4 +50,5 @@ public void test() { .expectBody(JsonNode.class) .value(jsonNode -> assertEquals("3.0.1", JsonNodeUtils.findNode(jsonNode, "openapi").asText())); } + } diff --git a/spring-boot-example/spring-easyexcel/spring-easyexcel-batch/src/main/java/com/livk/excel/batch/config/BatchConfig.java b/spring-boot-example/spring-easyexcel/spring-easyexcel-batch/src/main/java/com/livk/excel/batch/config/BatchConfig.java index 9ba3988ed..5d918abdd 100644 --- a/spring-boot-example/spring-easyexcel/spring-easyexcel-batch/src/main/java/com/livk/excel/batch/config/BatchConfig.java +++ b/spring-boot-example/spring-easyexcel/spring-easyexcel-batch/src/main/java/com/livk/excel/batch/config/BatchConfig.java @@ -42,4 +42,5 @@ public class BatchConfig { public ItemWriter> writer(SqlSessionFactory sqlSessionFactory) { return new MyBatisBatchItemWriter<>(sqlSessionFactory, "com.livk.excel.batch.mapper.InfoMapper.saveBatch"); } + } diff --git a/spring-boot-example/spring-easyexcel/spring-easyexcel-batch/src/main/java/com/livk/excel/batch/controller/InfoController.java b/spring-boot-example/spring-easyexcel/spring-easyexcel-batch/src/main/java/com/livk/excel/batch/controller/InfoController.java index 43d020399..cf43581f0 100644 --- a/spring-boot-example/spring-easyexcel/spring-easyexcel-batch/src/main/java/com/livk/excel/batch/controller/InfoController.java +++ b/spring-boot-example/spring-easyexcel/spring-easyexcel-batch/src/main/java/com/livk/excel/batch/controller/InfoController.java @@ -69,30 +69,32 @@ public class InfoController { private final JobRepository jobRepository; private final DataSourceTransactionManager dataSourceTransactionManager; + private final JobLauncher jobLauncher; @RequestExcel(parse = InfoExcelListener.class) @PostMapping("upload") - public HttpEntity upload(@ExcelParam List dataExcels) throws JobInstanceAlreadyCompleteException, JobExecutionAlreadyRunningException, JobParametersInvalidException, JobRestartException { + public HttpEntity upload(@ExcelParam List dataExcels) throws JobInstanceAlreadyCompleteException, + JobExecutionAlreadyRunningException, JobParametersInvalidException, JobRestartException { Step step = excelStep(dataExcels); Job job = excelJob(step); - jobLauncher.run(job, new JobParametersBuilder() - .addDate("date", new Date()) - .toJobParameters()); + jobLauncher.run(job, new JobParametersBuilder().addDate("date", new Date()).toJobParameters()); return ResponseEntity.ok(null); } @PostMapping("excel") public HttpEntity> up(@RequestParam("file") MultipartFile file) throws IOException { - EasyExcelItemReader itemReader = new EasyExcelItemReader<>(file.getInputStream(), new TypeExcelMapReadListener<>() { - }); + EasyExcelItemReader itemReader = new EasyExcelItemReader<>(file.getInputStream(), + new TypeExcelMapReadListener<>() { + }); List list = new ArrayList<>(); while (true) { Info o = itemReader.read(); if (o != null) { o.setId(System.currentTimeMillis()); list.add(o); - } else { + } + else { break; } } @@ -110,9 +112,7 @@ private Step excelStep(List dataExcels) { } public Job excelJob(Step step) { - return new JobBuilder("excelJob", jobRepository) - .start(step) - .listener(new JobListener()) - .build(); + return new JobBuilder("excelJob", jobRepository).start(step).listener(new JobListener()).build(); } + } diff --git a/spring-boot-example/spring-easyexcel/spring-easyexcel-batch/src/main/java/com/livk/excel/batch/listener/JobListener.java b/spring-boot-example/spring-easyexcel/spring-easyexcel-batch/src/main/java/com/livk/excel/batch/listener/JobListener.java index 2ccc50810..ca83933d2 100644 --- a/spring-boot-example/spring-easyexcel/spring-easyexcel-batch/src/main/java/com/livk/excel/batch/listener/JobListener.java +++ b/spring-boot-example/spring-easyexcel/spring-easyexcel-batch/src/main/java/com/livk/excel/batch/listener/JobListener.java @@ -41,8 +41,10 @@ public void beforeJob(JobExecution jobExecution) { public void afterJob(JobExecution jobExecution) { if (jobExecution.getStatus() == BatchStatus.COMPLETED) { log.info("任务id={}结束于{}", jobExecution.getJobId(), jobExecution.getEndTime()); - } else { + } + else { log.info("任务id={}执行异常状态={}", jobExecution.getJobId(), jobExecution.getStatus()); } } + } diff --git a/spring-boot-example/spring-easyexcel/spring-easyexcel-batch/src/main/java/com/livk/excel/batch/mapper/InfoMapper.java b/spring-boot-example/spring-easyexcel/spring-easyexcel-batch/src/main/java/com/livk/excel/batch/mapper/InfoMapper.java index a565984be..1ce6a81c5 100644 --- a/spring-boot-example/spring-easyexcel/spring-easyexcel-batch/src/main/java/com/livk/excel/batch/mapper/InfoMapper.java +++ b/spring-boot-example/spring-easyexcel/spring-easyexcel-batch/src/main/java/com/livk/excel/batch/mapper/InfoMapper.java @@ -31,5 +31,7 @@ */ @Mapper public interface InfoMapper { + void saveBatch(List infos); + } diff --git a/spring-boot-example/spring-easyexcel/spring-easyexcel-batch/src/main/java/com/livk/excel/batch/support/EasyExcelItemReader.java b/spring-boot-example/spring-easyexcel/spring-easyexcel-batch/src/main/java/com/livk/excel/batch/support/EasyExcelItemReader.java index 3c0a42006..eddb185ce 100644 --- a/spring-boot-example/spring-easyexcel/spring-easyexcel-batch/src/main/java/com/livk/excel/batch/support/EasyExcelItemReader.java +++ b/spring-boot-example/spring-easyexcel/spring-easyexcel-batch/src/main/java/com/livk/excel/batch/support/EasyExcelItemReader.java @@ -39,9 +39,9 @@ public class EasyExcelItemReader implements ItemReader { @SuppressWarnings("unchecked") public EasyExcelItemReader(InputStream inputStream, ExcelMapReadListener excelReadListener) { - Class targetClass = (Class) GenericTypeResolver.resolveTypeArgument(excelReadListener.getClass(), ExcelMapReadListener.class); - EasyExcel.read(inputStream, targetClass, excelReadListener) - .sheet().doRead(); + Class targetClass = (Class) GenericTypeResolver.resolveTypeArgument(excelReadListener.getClass(), + ExcelMapReadListener.class); + EasyExcel.read(inputStream, targetClass, excelReadListener).sheet().doRead(); data = new ArrayList<>(excelReadListener.getCollectionData()); } @@ -52,4 +52,5 @@ public T read() { } return null; } + } diff --git a/spring-boot-example/spring-easyexcel/spring-easyexcel-batch/src/main/java/com/livk/excel/batch/support/MyBatisBatchItemWriter.java b/spring-boot-example/spring-easyexcel/spring-easyexcel-batch/src/main/java/com/livk/excel/batch/support/MyBatisBatchItemWriter.java index e1c01c20b..a29ed08b6 100644 --- a/spring-boot-example/spring-easyexcel/spring-easyexcel-batch/src/main/java/com/livk/excel/batch/support/MyBatisBatchItemWriter.java +++ b/spring-boot-example/spring-easyexcel/spring-easyexcel-batch/src/main/java/com/livk/excel/batch/support/MyBatisBatchItemWriter.java @@ -47,9 +47,11 @@ public void write(@NonNull Chunk chunk) { sqlSession.update(statementId, item); } sqlSession.commit(); - } catch (Exception e) { + } + catch (Exception e) { sqlSession.rollback(); } sqlSession.close(); } + } diff --git a/spring-boot-example/spring-graphql/spring-graphql-mybatis/src/main/java/com/livk/graphql/mybatis/GraphqlMybatisExample.java b/spring-boot-example/spring-graphql/spring-graphql-mybatis/src/main/java/com/livk/graphql/mybatis/GraphqlMybatisExample.java index 30002254d..b1bd332f9 100644 --- a/spring-boot-example/spring-graphql/spring-graphql-mybatis/src/main/java/com/livk/graphql/mybatis/GraphqlMybatisExample.java +++ b/spring-boot-example/spring-graphql/spring-graphql-mybatis/src/main/java/com/livk/graphql/mybatis/GraphqlMybatisExample.java @@ -29,7 +29,9 @@ */ @SpringBootApplication public class GraphqlMybatisExample { + public static void main(String[] args) { SpringLauncher.run(args); } + } diff --git a/spring-boot-example/spring-graphql/spring-graphql-mybatis/src/main/java/com/livk/graphql/mybatis/controller/AuthorController.java b/spring-boot-example/spring-graphql/spring-graphql-mybatis/src/main/java/com/livk/graphql/mybatis/controller/AuthorController.java index ad1c41419..234785b17 100644 --- a/spring-boot-example/spring-graphql/spring-graphql-mybatis/src/main/java/com/livk/graphql/mybatis/controller/AuthorController.java +++ b/spring-boot-example/spring-graphql/spring-graphql-mybatis/src/main/java/com/livk/graphql/mybatis/controller/AuthorController.java @@ -44,4 +44,5 @@ public class AuthorController { public Mono createAuthor(@Argument AuthorDTO dto) { return Mono.justOrEmpty(authorMapper.save(BeanUtils.copy(dto, Author.class)) != 0); } + } diff --git a/spring-boot-example/spring-graphql/spring-graphql-mybatis/src/main/java/com/livk/graphql/mybatis/controller/BookController.java b/spring-boot-example/spring-graphql/spring-graphql-mybatis/src/main/java/com/livk/graphql/mybatis/controller/BookController.java index f32ac9748..34daf4f8c 100644 --- a/spring-boot-example/spring-graphql/spring-graphql-mybatis/src/main/java/com/livk/graphql/mybatis/controller/BookController.java +++ b/spring-boot-example/spring-graphql/spring-graphql-mybatis/src/main/java/com/livk/graphql/mybatis/controller/BookController.java @@ -66,5 +66,5 @@ public Mono getAuthor(Book book) { public Mono createBook(@Argument BookDTO dto) { return Mono.justOrEmpty(bookMapper.save(BeanUtils.copy(dto, Book.class)) != 0); } -} +} diff --git a/spring-boot-example/spring-graphql/spring-graphql-mybatis/src/main/java/com/livk/graphql/mybatis/controller/GreetingController.java b/spring-boot-example/spring-graphql/spring-graphql-mybatis/src/main/java/com/livk/graphql/mybatis/controller/GreetingController.java index 6f7bf7661..776ea9400 100644 --- a/spring-boot-example/spring-graphql/spring-graphql-mybatis/src/main/java/com/livk/graphql/mybatis/controller/GreetingController.java +++ b/spring-boot-example/spring-graphql/spring-graphql-mybatis/src/main/java/com/livk/graphql/mybatis/controller/GreetingController.java @@ -34,10 +34,12 @@ */ @Controller public class GreetingController { + @SubscriptionMapping public Flux greetings() { return Flux.fromStream(Stream.generate(() -> "Hello GraphQL " + UUID.randomUUID())) .delayElements(Duration.ofSeconds(5)) .take(10); } + } diff --git a/spring-boot-example/spring-graphql/spring-graphql-mybatis/src/main/java/com/livk/graphql/mybatis/entity/Author.java b/spring-boot-example/spring-graphql/spring-graphql-mybatis/src/main/java/com/livk/graphql/mybatis/entity/Author.java index 606036733..43ad12c22 100644 --- a/spring-boot-example/spring-graphql/spring-graphql-mybatis/src/main/java/com/livk/graphql/mybatis/entity/Author.java +++ b/spring-boot-example/spring-graphql/spring-graphql-mybatis/src/main/java/com/livk/graphql/mybatis/entity/Author.java @@ -28,8 +28,13 @@ */ @Data public class Author { + private Long id; + private String idCardNo; + private String name; + private Integer age; + } diff --git a/spring-boot-example/spring-graphql/spring-graphql-mybatis/src/main/java/com/livk/graphql/mybatis/entity/Book.java b/spring-boot-example/spring-graphql/spring-graphql-mybatis/src/main/java/com/livk/graphql/mybatis/entity/Book.java index a5fe433cd..3adde7ffa 100644 --- a/spring-boot-example/spring-graphql/spring-graphql-mybatis/src/main/java/com/livk/graphql/mybatis/entity/Book.java +++ b/spring-boot-example/spring-graphql/spring-graphql-mybatis/src/main/java/com/livk/graphql/mybatis/entity/Book.java @@ -28,9 +28,15 @@ */ @Data public class Book { + private Long id; + private String isbn; + private String title; + private Integer pages; + private String authorIdCardNo; + } diff --git a/spring-boot-example/spring-graphql/spring-graphql-mybatis/src/main/java/com/livk/graphql/mybatis/entity/dto/AuthorDTO.java b/spring-boot-example/spring-graphql/spring-graphql-mybatis/src/main/java/com/livk/graphql/mybatis/entity/dto/AuthorDTO.java index 1aab0a974..48d2fa3b3 100644 --- a/spring-boot-example/spring-graphql/spring-graphql-mybatis/src/main/java/com/livk/graphql/mybatis/entity/dto/AuthorDTO.java +++ b/spring-boot-example/spring-graphql/spring-graphql-mybatis/src/main/java/com/livk/graphql/mybatis/entity/dto/AuthorDTO.java @@ -28,7 +28,11 @@ */ @Data public class AuthorDTO { + private String idCardNo; + private String name; + private Integer age; + } diff --git a/spring-boot-example/spring-graphql/spring-graphql-mybatis/src/main/java/com/livk/graphql/mybatis/entity/dto/BookDTO.java b/spring-boot-example/spring-graphql/spring-graphql-mybatis/src/main/java/com/livk/graphql/mybatis/entity/dto/BookDTO.java index 55f6665f0..7dfb2ece0 100644 --- a/spring-boot-example/spring-graphql/spring-graphql-mybatis/src/main/java/com/livk/graphql/mybatis/entity/dto/BookDTO.java +++ b/spring-boot-example/spring-graphql/spring-graphql-mybatis/src/main/java/com/livk/graphql/mybatis/entity/dto/BookDTO.java @@ -28,8 +28,13 @@ */ @Data public class BookDTO { + private String isbn; + private String title; + private Integer pages; + private String authorIdCardNo; + } diff --git a/spring-boot-example/spring-graphql/spring-graphql-mybatis/src/main/java/com/livk/graphql/mybatis/mapper/AuthorMapper.java b/spring-boot-example/spring-graphql/spring-graphql-mybatis/src/main/java/com/livk/graphql/mybatis/mapper/AuthorMapper.java index 5b6431679..713960450 100644 --- a/spring-boot-example/spring-graphql/spring-graphql-mybatis/src/main/java/com/livk/graphql/mybatis/mapper/AuthorMapper.java +++ b/spring-boot-example/spring-graphql/spring-graphql-mybatis/src/main/java/com/livk/graphql/mybatis/mapper/AuthorMapper.java @@ -29,6 +29,7 @@ */ @Mapper public interface AuthorMapper { + @Insert("insert into author(id_card_no, name, age) values (#{idCardNo},#{name},#{age})") int save(Author author); @@ -37,4 +38,5 @@ public interface AuthorMapper { @Select("select * from author where id_card_no = #{authorIdCardNo}") Author getByIdCardNo(@Param("authorIdCardNo") String authorIdCardNo); + } diff --git a/spring-boot-example/spring-graphql/spring-graphql-mybatis/src/main/java/com/livk/graphql/mybatis/mapper/BookMapper.java b/spring-boot-example/spring-graphql/spring-graphql-mybatis/src/main/java/com/livk/graphql/mybatis/mapper/BookMapper.java index 3e6bf0bc2..e24e3eca3 100644 --- a/spring-boot-example/spring-graphql/spring-graphql-mybatis/src/main/java/com/livk/graphql/mybatis/mapper/BookMapper.java +++ b/spring-boot-example/spring-graphql/spring-graphql-mybatis/src/main/java/com/livk/graphql/mybatis/mapper/BookMapper.java @@ -31,6 +31,7 @@ */ @Mapper public interface BookMapper { + @Select("select * from book") List list(); @@ -42,4 +43,5 @@ public interface BookMapper { @Insert("insert into book(isbn, title, pages, author_id_card_no) values (#{isbn},#{title},#{pages},#{authorIdCardNo})") int save(Book book); + } diff --git a/spring-boot-example/spring-graphql/spring-graphql-mybatis/src/test/java/com/livk/graphql/mybatis/controller/BookControllerTest.java b/spring-boot-example/spring-graphql/spring-graphql-mybatis/src/test/java/com/livk/graphql/mybatis/controller/BookControllerTest.java index bc5bc0ba0..6c3995719 100644 --- a/spring-boot-example/spring-graphql/spring-graphql-mybatis/src/test/java/com/livk/graphql/mybatis/controller/BookControllerTest.java +++ b/spring-boot-example/spring-graphql/spring-graphql-mybatis/src/test/java/com/livk/graphql/mybatis/controller/BookControllerTest.java @@ -41,12 +41,8 @@ * * @author livk */ -@SpringBootTest({ - "spring.datasource.driver-class-name=org.h2.Driver", - "spring.datasource.url=jdbc:h2:mem:test", - "spring.sql.init.platform=h2", - "spring.sql.init.mode=embedded" -}) +@SpringBootTest({ "spring.datasource.driver-class-name=org.h2.Driver", "spring.datasource.url=jdbc:h2:mem:test", + "spring.sql.init.platform=h2", "spring.sql.init.mode=embedded" }) @AutoConfigureWebTestClient(timeout = "15000") @TestMethodOrder(MethodOrderer.OrderAnnotation.class) class BookControllerTest { @@ -75,40 +71,32 @@ public void init() { @Test @SuppressWarnings("rawtypes") void list() { - //language=GraphQL + // language=GraphQL String document = """ - query{ - bookList { - title - author { - name - } - } - }"""; - List result = tester.document(document) - .execute() - .path("bookList") - .entityList(Map.class) - .get(); + query{ + bookList { + title + author { + name + } + } + }"""; + List result = tester.document(document).execute().path("bookList").entityList(Map.class).get(); assertNotNull(result); - //language=GraphQL + // language=GraphQL String d1 = """ - query{ - bookList { - isbn - title - author { - name - age - } - } - }"""; - List r1 = tester.document(d1) - .execute() - .path("bookList") - .entityList(Map.class) - .get(); + query{ + bookList { + isbn + title + author { + name + age + } + } + }"""; + List r1 = tester.document(d1).execute().path("bookList").entityList(Map.class).get(); assertNotNull(r1); } @@ -116,23 +104,19 @@ void list() { @Test @SuppressWarnings("rawtypes") void bookByIsbn() { - //language=GraphQL + // language=GraphQL String document = """ - query{ - bookByIsbn(isbn: "9787121377921"){ - isbn - title - author { - name - age - } - } - }"""; - Map result = tester.document(document) - .execute() - .path("bookByIsbn") - .entity(Map.class) - .get(); + query{ + bookByIsbn(isbn: "9787121377921"){ + isbn + title + author { + name + age + } + } + }"""; + Map result = tester.document(document).execute().path("bookByIsbn").entity(Map.class).get(); assertNotNull(result); } @@ -140,56 +124,44 @@ void bookByIsbn() { @Test void createBook() { bookMapper.clear(); - //language=GraphQL + // language=GraphQL String d1 = """ - mutation{ - createBook(dto: { - isbn: "9787121282089", - title: "JavaEE开发的颠覆者:Spring Boot实战", - pages: 524, - authorIdCardNo: "341234567891234567" - } ) - }"""; - //language=GraphQL + mutation{ + createBook(dto: { + isbn: "9787121282089", + title: "JavaEE开发的颠覆者:Spring Boot实战", + pages: 524, + authorIdCardNo: "341234567891234567" + } ) + }"""; + // language=GraphQL String d2 = """ - mutation{ - createBook(dto: { - isbn: "9787121377921", - title: "从企业级开发到云原生微服务:Spring Boot实战", - pages: 504, - authorIdCardNo: "341234567891234567" - } ) - }"""; - //language=GraphQL + mutation{ + createBook(dto: { + isbn: "9787121377921", + title: "从企业级开发到云原生微服务:Spring Boot实战", + pages: 504, + authorIdCardNo: "341234567891234567" + } ) + }"""; + // language=GraphQL String d3 = """ - mutation{ - createBook(dto: { - isbn: "9787121347962", - title: "架构整洁之道", - pages: 348, - authorIdCardNo: "341234567891234568" - } ) - }"""; - - Boolean r1 = tester.document(d1) - .execute() - .path("createBook") - .entity(Boolean.class) - .get(); + mutation{ + createBook(dto: { + isbn: "9787121347962", + title: "架构整洁之道", + pages: 348, + authorIdCardNo: "341234567891234568" + } ) + }"""; + + Boolean r1 = tester.document(d1).execute().path("createBook").entity(Boolean.class).get(); assertTrue(r1); - Boolean r2 = tester.document(d2) - .execute() - .path("createBook") - .entity(Boolean.class) - .get(); + Boolean r2 = tester.document(d2).execute().path("createBook").entity(Boolean.class).get(); assertTrue(r2); - Boolean r3 = tester.document(d3) - .execute() - .path("createBook") - .entity(Boolean.class) - .get(); + Boolean r3 = tester.document(d3).execute().path("createBook").entity(Boolean.class).get(); assertTrue(r3); } @@ -197,35 +169,28 @@ void createBook() { @Test void createAuthor() { authorMapper.clear(); - //language=GraphQL + // language=GraphQL String document = """ - mutation{ - createAuthor(dto: { - idCardNo: "341234567891234567", - name: "汪云飞", - age: 38 - }) - }"""; - Boolean result = tester.document(document) - .execute() - .path("createAuthor") - .entity(Boolean.class) - .get(); + mutation{ + createAuthor(dto: { + idCardNo: "341234567891234567", + name: "汪云飞", + age: 38 + }) + }"""; + Boolean result = tester.document(document).execute().path("createAuthor").entity(Boolean.class).get(); assertTrue(result); - //language=GraphQL + // language=GraphQL String d2 = """ - mutation{ - createAuthor(dto: { - idCardNo: "341234567891234568", - name: "罗伯特C.马丁", - age: 70 } - ) - }"""; - Boolean result2 = tester.document(d2) - .execute() - .path("createAuthor") - .entity(Boolean.class) - .get(); + mutation{ + createAuthor(dto: { + idCardNo: "341234567891234568", + name: "罗伯特C.马丁", + age: 70 } + ) + }"""; + Boolean result2 = tester.document(d2).execute().path("createAuthor").entity(Boolean.class).get(); assertTrue(result2); } + } diff --git a/spring-boot-example/spring-graphql/spring-graphql-mybatis/src/test/java/com/livk/graphql/mybatis/controller/GreetingControllerTest.java b/spring-boot-example/spring-graphql/spring-graphql-mybatis/src/test/java/com/livk/graphql/mybatis/controller/GreetingControllerTest.java index 33a867f25..44c98f4a8 100644 --- a/spring-boot-example/spring-graphql/spring-graphql-mybatis/src/test/java/com/livk/graphql/mybatis/controller/GreetingControllerTest.java +++ b/spring-boot-example/spring-graphql/spring-graphql-mybatis/src/test/java/com/livk/graphql/mybatis/controller/GreetingControllerTest.java @@ -38,12 +38,8 @@ * * @author livk */ -@SpringBootTest({ - "spring.datasource.driver-class-name=org.h2.Driver", - "spring.datasource.url=jdbc:h2:mem:test", - "spring.sql.init.platform=h2", - "spring.sql.init.mode=embedded" -}) +@SpringBootTest({ "spring.datasource.driver-class-name=org.h2.Driver", "spring.datasource.url=jdbc:h2:mem:test", + "spring.sql.init.platform=h2", "spring.sql.init.mode=embedded" }) @AutoConfigureWebTestClient(timeout = "15000") class GreetingControllerTest { @@ -64,16 +60,13 @@ public void init() { @Test @SuppressWarnings("rawtypes") void greetings() { - //language=GraphQL + // language=GraphQL String document = """ - subscription { - greetings - }"""; - Map result = tester.document(document) - .execute() - .path("upstreamPublisher") - .entity(Map.class) - .get(); + subscription { + greetings + }"""; + Map result = tester.document(document).execute().path("upstreamPublisher").entity(Map.class).get(); assertNotNull(result); } + } diff --git a/spring-boot-example/spring-graphql/spring-graphql-r2dbc/src/main/java/com/livk/graphql/r2dbc/GraphqlR2dbcExample.java b/spring-boot-example/spring-graphql/spring-graphql-r2dbc/src/main/java/com/livk/graphql/r2dbc/GraphqlR2dbcExample.java index 1ad3a5b63..121267efa 100644 --- a/spring-boot-example/spring-graphql/spring-graphql-r2dbc/src/main/java/com/livk/graphql/r2dbc/GraphqlR2dbcExample.java +++ b/spring-boot-example/spring-graphql/spring-graphql-r2dbc/src/main/java/com/livk/graphql/r2dbc/GraphqlR2dbcExample.java @@ -29,7 +29,9 @@ */ @SpringBootApplication public class GraphqlR2dbcExample { + public static void main(String[] args) { SpringLauncher.run(args); } + } diff --git a/spring-boot-example/spring-graphql/spring-graphql-r2dbc/src/main/java/com/livk/graphql/r2dbc/controller/AuthorController.java b/spring-boot-example/spring-graphql/spring-graphql-r2dbc/src/main/java/com/livk/graphql/r2dbc/controller/AuthorController.java index e6142b6dc..79964194b 100644 --- a/spring-boot-example/spring-graphql/spring-graphql-r2dbc/src/main/java/com/livk/graphql/r2dbc/controller/AuthorController.java +++ b/spring-boot-example/spring-graphql/spring-graphql-r2dbc/src/main/java/com/livk/graphql/r2dbc/controller/AuthorController.java @@ -44,4 +44,5 @@ public class AuthorController { public Mono createAuthor(@Argument AuthorDTO dto) { return authorRepository.save(BeanUtils.copy(dto, Author.class)); } + } diff --git a/spring-boot-example/spring-graphql/spring-graphql-r2dbc/src/main/java/com/livk/graphql/r2dbc/controller/BookController.java b/spring-boot-example/spring-graphql/spring-graphql-r2dbc/src/main/java/com/livk/graphql/r2dbc/controller/BookController.java index d5b20d5d5..3fed632e5 100644 --- a/spring-boot-example/spring-graphql/spring-graphql-r2dbc/src/main/java/com/livk/graphql/r2dbc/controller/BookController.java +++ b/spring-boot-example/spring-graphql/spring-graphql-r2dbc/src/main/java/com/livk/graphql/r2dbc/controller/BookController.java @@ -66,5 +66,5 @@ public Mono getAuthor(Book book) { public Mono createBook(@Argument BookDTO dto) { return bookRepository.save(BeanUtils.copy(dto, Book.class)); } -} +} diff --git a/spring-boot-example/spring-graphql/spring-graphql-r2dbc/src/main/java/com/livk/graphql/r2dbc/controller/GreetingController.java b/spring-boot-example/spring-graphql/spring-graphql-r2dbc/src/main/java/com/livk/graphql/r2dbc/controller/GreetingController.java index 623aed447..3411f3e2f 100644 --- a/spring-boot-example/spring-graphql/spring-graphql-r2dbc/src/main/java/com/livk/graphql/r2dbc/controller/GreetingController.java +++ b/spring-boot-example/spring-graphql/spring-graphql-r2dbc/src/main/java/com/livk/graphql/r2dbc/controller/GreetingController.java @@ -34,10 +34,12 @@ */ @Controller public class GreetingController { + @SubscriptionMapping public Flux greetings() { return Flux.fromStream(Stream.generate(() -> "Hello GraphQL " + UUID.randomUUID())) .delayElements(Duration.ofSeconds(5)) .take(10); } + } diff --git a/spring-boot-example/spring-graphql/spring-graphql-r2dbc/src/main/java/com/livk/graphql/r2dbc/entity/Author.java b/spring-boot-example/spring-graphql/spring-graphql-r2dbc/src/main/java/com/livk/graphql/r2dbc/entity/Author.java index 0fcf198ec..7b1d409bf 100644 --- a/spring-boot-example/spring-graphql/spring-graphql-r2dbc/src/main/java/com/livk/graphql/r2dbc/entity/Author.java +++ b/spring-boot-example/spring-graphql/spring-graphql-r2dbc/src/main/java/com/livk/graphql/r2dbc/entity/Author.java @@ -28,8 +28,13 @@ */ @Data public class Author { + private Long id; + private String idCardNo; + private String name; + private Integer age; + } diff --git a/spring-boot-example/spring-graphql/spring-graphql-r2dbc/src/main/java/com/livk/graphql/r2dbc/entity/Book.java b/spring-boot-example/spring-graphql/spring-graphql-r2dbc/src/main/java/com/livk/graphql/r2dbc/entity/Book.java index 3dad29f9f..03027d03f 100644 --- a/spring-boot-example/spring-graphql/spring-graphql-r2dbc/src/main/java/com/livk/graphql/r2dbc/entity/Book.java +++ b/spring-boot-example/spring-graphql/spring-graphql-r2dbc/src/main/java/com/livk/graphql/r2dbc/entity/Book.java @@ -28,9 +28,15 @@ */ @Data public class Book { + private Long id; + private String isbn; + private String title; + private Integer pages; + private String authorIdCardNo; + } diff --git a/spring-boot-example/spring-graphql/spring-graphql-r2dbc/src/main/java/com/livk/graphql/r2dbc/entity/dto/AuthorDTO.java b/spring-boot-example/spring-graphql/spring-graphql-r2dbc/src/main/java/com/livk/graphql/r2dbc/entity/dto/AuthorDTO.java index c8832d2fc..b624a1d7c 100644 --- a/spring-boot-example/spring-graphql/spring-graphql-r2dbc/src/main/java/com/livk/graphql/r2dbc/entity/dto/AuthorDTO.java +++ b/spring-boot-example/spring-graphql/spring-graphql-r2dbc/src/main/java/com/livk/graphql/r2dbc/entity/dto/AuthorDTO.java @@ -28,7 +28,11 @@ */ @Data public class AuthorDTO { + private String idCardNo; + private String name; + private Integer age; + } diff --git a/spring-boot-example/spring-graphql/spring-graphql-r2dbc/src/main/java/com/livk/graphql/r2dbc/entity/dto/BookDTO.java b/spring-boot-example/spring-graphql/spring-graphql-r2dbc/src/main/java/com/livk/graphql/r2dbc/entity/dto/BookDTO.java index 5e74e43d4..b253c0a99 100644 --- a/spring-boot-example/spring-graphql/spring-graphql-r2dbc/src/main/java/com/livk/graphql/r2dbc/entity/dto/BookDTO.java +++ b/spring-boot-example/spring-graphql/spring-graphql-r2dbc/src/main/java/com/livk/graphql/r2dbc/entity/dto/BookDTO.java @@ -28,8 +28,13 @@ */ @Data public class BookDTO { + private String isbn; + private String title; + private Integer pages; + private String authorIdCardNo; + } diff --git a/spring-boot-example/spring-graphql/spring-graphql-r2dbc/src/main/java/com/livk/graphql/r2dbc/repository/AuthorRepository.java b/spring-boot-example/spring-graphql/spring-graphql-r2dbc/src/main/java/com/livk/graphql/r2dbc/repository/AuthorRepository.java index 3eeefeaef..2245f007d 100644 --- a/spring-boot-example/spring-graphql/spring-graphql-r2dbc/src/main/java/com/livk/graphql/r2dbc/repository/AuthorRepository.java +++ b/spring-boot-example/spring-graphql/spring-graphql-r2dbc/src/main/java/com/livk/graphql/r2dbc/repository/AuthorRepository.java @@ -29,5 +29,7 @@ * @author livk */ public interface AuthorRepository extends R2dbcRepository { + Mono findByIdCardNo(String authorIdCardNo); + } diff --git a/spring-boot-example/spring-graphql/spring-graphql-r2dbc/src/main/java/com/livk/graphql/r2dbc/repository/BookRepository.java b/spring-boot-example/spring-graphql/spring-graphql-r2dbc/src/main/java/com/livk/graphql/r2dbc/repository/BookRepository.java index 21d6a9d7f..9d87ead5b 100644 --- a/spring-boot-example/spring-graphql/spring-graphql-r2dbc/src/main/java/com/livk/graphql/r2dbc/repository/BookRepository.java +++ b/spring-boot-example/spring-graphql/spring-graphql-r2dbc/src/main/java/com/livk/graphql/r2dbc/repository/BookRepository.java @@ -29,5 +29,7 @@ * @author livk */ public interface BookRepository extends R2dbcRepository { + Mono findByIsbn(String isbn); + } diff --git a/spring-boot-example/spring-graphql/spring-graphql-r2dbc/src/test/java/com/livk/graphql/r2dbc/controller/BookControllerTest.java b/spring-boot-example/spring-graphql/spring-graphql-r2dbc/src/test/java/com/livk/graphql/r2dbc/controller/BookControllerTest.java index f784d9205..b8fd3d5d9 100644 --- a/spring-boot-example/spring-graphql/spring-graphql-r2dbc/src/test/java/com/livk/graphql/r2dbc/controller/BookControllerTest.java +++ b/spring-boot-example/spring-graphql/spring-graphql-r2dbc/src/test/java/com/livk/graphql/r2dbc/controller/BookControllerTest.java @@ -71,40 +71,32 @@ public void init() { @Test @SuppressWarnings("rawtypes") void list() { - //language=GraphQL + // language=GraphQL String document = """ - query{ - bookList { - title - author { - name - } - } - }"""; - List result = tester.document(document) - .execute() - .path("bookList") - .entityList(Map.class) - .get(); + query{ + bookList { + title + author { + name + } + } + }"""; + List result = tester.document(document).execute().path("bookList").entityList(Map.class).get(); assertNotNull(result); - //language=GraphQL + // language=GraphQL String d1 = """ - query{ - bookList { - isbn - title - author { - name - age - } - } - }"""; - List r1 = tester.document(d1) - .execute() - .path("bookList") - .entityList(Map.class) - .get(); + query{ + bookList { + isbn + title + author { + name + age + } + } + }"""; + List r1 = tester.document(d1).execute().path("bookList").entityList(Map.class).get(); assertNotNull(r1); } @@ -112,23 +104,19 @@ void list() { @Test @SuppressWarnings("rawtypes") void bookByIsbn() { - //language=GraphQL + // language=GraphQL String document = """ - query{ - bookByIsbn(isbn: "9787121377921"){ - isbn - title - author { - name - age - } - } - }"""; - Map result = tester.document(document) - .execute() - .path("bookByIsbn") - .entity(Map.class) - .get(); + query{ + bookByIsbn(isbn: "9787121377921"){ + isbn + title + author { + name + age + } + } + }"""; + Map result = tester.document(document).execute().path("bookByIsbn").entity(Map.class).get(); assertNotNull(result); } @@ -136,56 +124,44 @@ void bookByIsbn() { @Test void createBook() { bookRepository.deleteAll().subscribe(); - //language=GraphQL + // language=GraphQL String d1 = """ - mutation{ - createBook(dto: { - isbn: "9787121282089", - title: "JavaEE开发的颠覆者:Spring Boot实战", - pages: 524, - authorIdCardNo: "341234567891234567" - } ){ title pages } - }"""; - //language=GraphQL + mutation{ + createBook(dto: { + isbn: "9787121282089", + title: "JavaEE开发的颠覆者:Spring Boot实战", + pages: 524, + authorIdCardNo: "341234567891234567" + } ){ title pages } + }"""; + // language=GraphQL String d2 = """ - mutation{ - createBook(dto: { - isbn: "9787121377921", - title: "从企业级开发到云原生微服务:Spring Boot实战", - pages: 504, - authorIdCardNo: "341234567891234567" - } ){ title pages } - }"""; - //language=GraphQL + mutation{ + createBook(dto: { + isbn: "9787121377921", + title: "从企业级开发到云原生微服务:Spring Boot实战", + pages: 504, + authorIdCardNo: "341234567891234567" + } ){ title pages } + }"""; + // language=GraphQL String d3 = """ - mutation{ - createBook(dto: { - isbn: "9787121347962", - title: "架构整洁之道", - pages: 348, - authorIdCardNo: "341234567891234568" - } ){ title pages } - }"""; - - Book r1 = tester.document(d1) - .execute() - .path("createBook") - .entity(Book.class) - .get(); + mutation{ + createBook(dto: { + isbn: "9787121347962", + title: "架构整洁之道", + pages: 348, + authorIdCardNo: "341234567891234568" + } ){ title pages } + }"""; + + Book r1 = tester.document(d1).execute().path("createBook").entity(Book.class).get(); assertNotNull(r1); - Book r2 = tester.document(d2) - .execute() - .path("createBook") - .entity(Book.class) - .get(); + Book r2 = tester.document(d2).execute().path("createBook").entity(Book.class).get(); assertNotNull(r2); - Book r3 = tester.document(d3) - .execute() - .path("createBook") - .entity(Book.class) - .get(); + Book r3 = tester.document(d3).execute().path("createBook").entity(Book.class).get(); assertNotNull(r3); } @@ -193,35 +169,28 @@ void createBook() { @Test void createAuthor() { authorRepository.deleteAll().subscribe(); - //language=GraphQL + // language=GraphQL String document = """ - mutation{ - createAuthor(dto: { - idCardNo: "341234567891234567", - name: "汪云飞", - age: 38 - }){name age} - }"""; - Author result = tester.document(document) - .execute() - .path("createAuthor") - .entity(Author.class) - .get(); + mutation{ + createAuthor(dto: { + idCardNo: "341234567891234567", + name: "汪云飞", + age: 38 + }){name age} + }"""; + Author result = tester.document(document).execute().path("createAuthor").entity(Author.class).get(); assertNotNull(result); - //language=GraphQL + // language=GraphQL String d2 = """ - mutation{ - createAuthor(dto: { - idCardNo: "341234567891234568", - name: "罗伯特C.马丁", - age: 70 - }){name age} - }"""; - Author result2 = tester.document(d2) - .execute() - .path("createAuthor") - .entity(Author.class) - .get(); + mutation{ + createAuthor(dto: { + idCardNo: "341234567891234568", + name: "罗伯特C.马丁", + age: 70 + }){name age} + }"""; + Author result2 = tester.document(d2).execute().path("createAuthor").entity(Author.class).get(); assertNotNull(result2); } + } diff --git a/spring-boot-example/spring-graphql/spring-graphql-r2dbc/src/test/java/com/livk/graphql/r2dbc/controller/GreetingControllerTest.java b/spring-boot-example/spring-graphql/spring-graphql-r2dbc/src/test/java/com/livk/graphql/r2dbc/controller/GreetingControllerTest.java index cff47ff82..8b94de8b6 100644 --- a/spring-boot-example/spring-graphql/spring-graphql-r2dbc/src/test/java/com/livk/graphql/r2dbc/controller/GreetingControllerTest.java +++ b/spring-boot-example/spring-graphql/spring-graphql-r2dbc/src/test/java/com/livk/graphql/r2dbc/controller/GreetingControllerTest.java @@ -59,16 +59,13 @@ public void init() { @Test @SuppressWarnings("rawtypes") void greetings() { - //language=GraphQL + // language=GraphQL String document = """ - subscription { - greetings - }"""; - Map result = tester.document(document) - .execute() - .path("upstreamPublisher") - .entity(Map.class) - .get(); + subscription { + greetings + }"""; + Map result = tester.document(document).execute().path("upstreamPublisher").entity(Map.class).get(); assertNotNull(result); } + } diff --git a/spring-boot-example/spring-hateoas/src/main/java/com/livk/spring/controller/GreetingController.java b/spring-boot-example/spring-hateoas/src/main/java/com/livk/spring/controller/GreetingController.java index 32be68f85..1c9485f4c 100644 --- a/spring-boot-example/spring-hateoas/src/main/java/com/livk/spring/controller/GreetingController.java +++ b/spring-boot-example/spring-hateoas/src/main/java/com/livk/spring/controller/GreetingController.java @@ -40,10 +40,10 @@ public class GreetingController { @GetMapping("/greeting") public Mono> greeting( - @RequestParam(value = "name", required = false, defaultValue = "World") String name) { + @RequestParam(value = "name", required = false, defaultValue = "World") String name) { Greeting greeting = new Greeting(String.format(TEMPLATE, name)); - greeting.add( - WebMvcLinkBuilder.linkTo(WebMvcLinkBuilder.methodOn(this.getClass()).greeting(name)).withSelfRel()); + greeting + .add(WebMvcLinkBuilder.linkTo(WebMvcLinkBuilder.methodOn(this.getClass()).greeting(name)).withSelfRel()); return Mono.just(ResponseEntity.ok(greeting)); } diff --git a/spring-boot-example/spring-hateoas/src/main/java/com/livk/spring/domain/Greeting.java b/spring-boot-example/spring-hateoas/src/main/java/com/livk/spring/domain/Greeting.java index 63861dc8e..7f91f4dfa 100644 --- a/spring-boot-example/spring-hateoas/src/main/java/com/livk/spring/domain/Greeting.java +++ b/spring-boot-example/spring-hateoas/src/main/java/com/livk/spring/domain/Greeting.java @@ -41,4 +41,5 @@ public class Greeting extends AbstractEntity { private final String contents; private final Instant instant = Instant.now(); + } diff --git a/spring-boot-example/spring-hateoas/src/test/java/com/livk/spring/controller/GreetingControllerTest.java b/spring-boot-example/spring-hateoas/src/test/java/com/livk/spring/controller/GreetingControllerTest.java index e9aed432e..f22733e33 100644 --- a/spring-boot-example/spring-hateoas/src/test/java/com/livk/spring/controller/GreetingControllerTest.java +++ b/spring-boot-example/spring-hateoas/src/test/java/com/livk/spring/controller/GreetingControllerTest.java @@ -37,4 +37,5 @@ void greeting() { assertEquals("hello,World!", JsonNodeUtils.findNode(jsonNode, "content").asText()); }); } + } diff --git a/spring-boot-example/spring-kafka/src/main/java/com/livk/kafka/KafkaApp.java b/spring-boot-example/spring-kafka/src/main/java/com/livk/kafka/KafkaApp.java index 86e928cbf..ca33cc6cd 100644 --- a/spring-boot-example/spring-kafka/src/main/java/com/livk/kafka/KafkaApp.java +++ b/spring-boot-example/spring-kafka/src/main/java/com/livk/kafka/KafkaApp.java @@ -28,6 +28,7 @@ @Slf4j @SpringBootApplication public class KafkaApp { + public static void main(String[] args) { SpringLauncher.run(args); } @@ -36,4 +37,5 @@ public static void main(String[] args) { public void consumer(String input) { log.info("data:{}", input); } + } diff --git a/spring-boot-example/spring-kafka/src/main/java/com/livk/kafka/config/KafkaConfig.java b/spring-boot-example/spring-kafka/src/main/java/com/livk/kafka/config/KafkaConfig.java index 9fe42b237..9b81d8f0e 100644 --- a/spring-boot-example/spring-kafka/src/main/java/com/livk/kafka/config/KafkaConfig.java +++ b/spring-boot-example/spring-kafka/src/main/java/com/livk/kafka/config/KafkaConfig.java @@ -29,6 +29,7 @@ */ @Configuration public class KafkaConfig { + @Bean public KafkaAdmin myKafkaAdmin(KafkaProperties kafkaProperties) { KafkaAdmin admin = new KafkaAdmin(kafkaProperties.buildAdminProperties()); diff --git a/spring-boot-example/spring-kafka/src/main/java/com/livk/kafka/controller/ProducerController.java b/spring-boot-example/spring-kafka/src/main/java/com/livk/kafka/controller/ProducerController.java index de8e3ec99..8e3e335c6 100644 --- a/spring-boot-example/spring-kafka/src/main/java/com/livk/kafka/controller/ProducerController.java +++ b/spring-boot-example/spring-kafka/src/main/java/com/livk/kafka/controller/ProducerController.java @@ -44,21 +44,24 @@ public class ProducerController { public void producer() { kafkaTemplate.send(KafkaConstant.TOPIC, UUID.randomUUID().toString()); // 异步获取结果 - kafkaTemplate.send(KafkaConstant.NEW_TOPIC, UUID.randomUUID().toString()) - .whenComplete((result, throwable) -> { - if (throwable != null) { - log.error("ex:{}", throwable.getMessage()); - } else { - log.info("result:{}", result); - } - }); + kafkaTemplate.send(KafkaConstant.NEW_TOPIC, UUID.randomUUID().toString()).whenComplete((result, throwable) -> { + if (throwable != null) { + log.error("ex:{}", throwable.getMessage()); + } + else { + log.info("result:{}", result); + } + }); // 同步获取结果 - CompletableFuture> future = kafkaTemplate.send(KafkaConstant.NEW_TOPIC, UUID.randomUUID().toString()); + CompletableFuture> future = kafkaTemplate.send(KafkaConstant.NEW_TOPIC, + UUID.randomUUID().toString()); try { SendResult result = future.get(); log.info("result:{}", result); - } catch (Exception e) { + } + catch (Exception e) { log.error("ex:{}", e.getMessage()); } } + } diff --git a/spring-boot-example/spring-kafka/src/test/java/com/livk/kafka/controller/ProducerControllerTest.java b/spring-boot-example/spring-kafka/src/test/java/com/livk/kafka/controller/ProducerControllerTest.java index 92767859d..faa34d0bc 100644 --- a/spring-boot-example/spring-kafka/src/test/java/com/livk/kafka/controller/ProducerControllerTest.java +++ b/spring-boot-example/spring-kafka/src/test/java/com/livk/kafka/controller/ProducerControllerTest.java @@ -41,8 +41,7 @@ class ProducerControllerTest { @Test void producer() throws Exception { - mockMvc.perform(get("/kafka/send")) - .andDo(print()) - .andExpect(status().isOk()); + mockMvc.perform(get("/kafka/send")).andDo(print()).andExpect(status().isOk()); } + } diff --git a/spring-boot-example/spring-mail/src/main/java/com/livk/mail/controller/MailController.java b/spring-boot-example/spring-mail/src/main/java/com/livk/mail/controller/MailController.java index c645fd23e..caae74225 100644 --- a/spring-boot-example/spring-mail/src/main/java/com/livk/mail/controller/MailController.java +++ b/spring-boot-example/spring-mail/src/main/java/com/livk/mail/controller/MailController.java @@ -53,7 +53,7 @@ public HttpEntity send() throws IOException, TemplateException { // 往里面塞第一层节点 root.put("UserName", "Livk-Cloud"); - String[] temp = new String[]{"dog", "cat", "tiger"}; + String[] temp = new String[] { "dog", "cat", "tiger" }; List pets = new ArrayList<>(); Collections.addAll(pets, temp); // 往里面塞个List对象 @@ -62,7 +62,8 @@ public HttpEntity send() throws IOException, TemplateException { Template template = mailTemplate.getConfiguration().getTemplate("hello.ftl"); String text = FreeMarkerTemplateUtils.processTemplateIntoString(template, root); - mailTemplate.send(Pair.of("1375632510@qq.com", "I am Livk"), "This is subject 主题", text, root, "1375632510@qq.com"); + mailTemplate.send(Pair.of("1375632510@qq.com", "I am Livk"), "This is subject 主题", text, root, + "1375632510@qq.com"); return ResponseEntity.ok().build(); } diff --git a/spring-boot-example/spring-mail/src/main/java/com/livk/mail/support/MailMessageBuilder.java b/spring-boot-example/spring-mail/src/main/java/com/livk/mail/support/MailMessageBuilder.java index ab45a3179..4fe6d7c97 100644 --- a/spring-boot-example/spring-mail/src/main/java/com/livk/mail/support/MailMessageBuilder.java +++ b/spring-boot-example/spring-mail/src/main/java/com/livk/mail/support/MailMessageBuilder.java @@ -37,6 +37,7 @@ */ @NoArgsConstructor(access = AccessLevel.PRIVATE) public class MailMessageBuilder { + private MimeMessageHelper mimeMessageHelper; public static MailMessageBuilder builder(JavaMailSender javaMailSender) { @@ -44,7 +45,8 @@ public static MailMessageBuilder builder(JavaMailSender javaMailSender) { MailMessageBuilder builder = new MailMessageBuilder(); builder.mimeMessageHelper = new MimeMessageHelper(javaMailSender.createMimeMessage(), true); return builder; - } catch (MessagingException e) { + } + catch (MessagingException e) { throw new RuntimeException(e); } } @@ -53,7 +55,8 @@ public MailMessageBuilder from(Pair from) { try { mimeMessageHelper.setFrom(from.key(), from.value()); return this; - } catch (MessagingException | UnsupportedEncodingException e) { + } + catch (MessagingException | UnsupportedEncodingException e) { throw new RuntimeException(e); } } @@ -65,7 +68,8 @@ public MailMessageBuilder to(String... to) { try { mimeMessageHelper.setTo(to); return this; - } catch (MessagingException e) { + } + catch (MessagingException e) { throw new RuntimeException(e); } } @@ -74,7 +78,8 @@ public MailMessageBuilder subject(String subject) { try { mimeMessageHelper.setSubject(subject); return this; - } catch (MessagingException e) { + } + catch (MessagingException e) { throw new RuntimeException(e); } } @@ -83,7 +88,8 @@ public MailMessageBuilder text(String text, boolean isHtml) { try { mimeMessageHelper.setText(text, isHtml); return this; - } catch (MessagingException e) { + } + catch (MessagingException e) { throw new RuntimeException(e); } } @@ -94,7 +100,8 @@ public MailMessageBuilder file(File file) { mimeMessageHelper.addAttachment(file.getName(), file); } return this; - } catch (MessagingException e) { + } + catch (MessagingException e) { throw new RuntimeException(e); } } @@ -102,4 +109,5 @@ public MailMessageBuilder file(File file) { public MimeMessage build() { return mimeMessageHelper.getMimeMessage(); } + } diff --git a/spring-boot-example/spring-mail/src/main/java/com/livk/mail/support/MailTemplate.java b/spring-boot-example/spring-mail/src/main/java/com/livk/mail/support/MailTemplate.java index 55e3da759..a4d03ce99 100644 --- a/spring-boot-example/spring-mail/src/main/java/com/livk/mail/support/MailTemplate.java +++ b/spring-boot-example/spring-mail/src/main/java/com/livk/mail/support/MailTemplate.java @@ -42,20 +42,21 @@ @Component @RequiredArgsConstructor public class MailTemplate { + @Getter private final Configuration configuration; + @Getter private final JavaMailSender javaMailSender; /** * 发送邮件 - * - * @param to 目标地址 - * @param from 发送地址 + * @param to 目标地址 + * @param from 发送地址 * @param subject 主题 - * @param text 内容 - * @param isHtml 是否为Html - * @param file 是否需要携带文件,不携带则为Null + * @param text 内容 + * @param isHtml 是否为Html + * @param file 是否需要携带文件,不携带则为Null */ public void send(Pair from, String subject, String text, boolean isHtml, File file, String... to) { try { @@ -67,7 +68,8 @@ public void send(Pair from, String subject, String text, boolean .file(file) .build(); this.send(mimeMessage); - } catch (Exception e) { + } + catch (Exception e) { log.error("send email error:{}", e.getMessage()); } } @@ -75,19 +77,19 @@ public void send(Pair from, String subject, String text, boolean public void send(MimeMessage mimeMessage) { try { javaMailSender.send(mimeMessage); - } catch (Exception e) { + } + catch (Exception e) { log.error("send email error:{}", e.getMessage()); } } /** * 发送邮件 - * - * @param to 目标地址 - * @param from 发送地址 + * @param to 目标地址 + * @param from 发送地址 * @param subject 主题 - * @param text 内容 - * @param isHtml 是否为Html + * @param text 内容 + * @param isHtml 是否为Html */ public void send(Pair from, String subject, String text, boolean isHtml, String... to) { send(from, subject, text, isHtml, null, to); @@ -95,12 +97,11 @@ public void send(Pair from, String subject, String text, boolean /** * 发送邮件 - * - * @param to 目标地址 - * @param from 发送地址 + * @param to 目标地址 + * @param from 发送地址 * @param subject 主题 - * @param text 内容 - * @param file 是否需要携带文件,不携带则为Null + * @param text 内容 + * @param file 是否需要携带文件,不携带则为Null */ public void send(Pair from, String subject, String text, File file, String... to) { send(from, subject, text, false, file, to); @@ -108,11 +109,10 @@ public void send(Pair from, String subject, String text, File fi /** * 发送邮件 - * - * @param to 目标地址 - * @param from 发送地址 + * @param to 目标地址 + * @param from 发送地址 * @param subject 主题 - * @param text 内容 + * @param text 内容 */ public void send(Pair from, String subject, String text, String... to) { send(from, subject, text, false, null, to); @@ -120,34 +120,36 @@ public void send(Pair from, String subject, String text, String. /** * 发送邮件 - * - * @param to 目标地址 - * @param from 发送地址 - * @param subject 主题 + * @param to 目标地址 + * @param from 发送地址 + * @param subject 主题 * @param template 模板 - * @param data 模板填充内容 - * @param file 是否需要携带文件,不携带则为Null + * @param data 模板填充内容 + * @param file 是否需要携带文件,不携带则为Null */ - public void send(Pair from, String subject, String template, Map data, File file, String... to) { + public void send(Pair from, String subject, String template, Map data, File file, + String... to) { try { Template tem = configuration.getTemplate(template); String templateStr = FreeMarkerTemplateUtils.processTemplateIntoString(tem, data); send(from, subject, templateStr, true, file, to); - } catch (Exception e) { + } + catch (Exception e) { log.error("send email error:{}", e.getMessage()); } } /** * 发送邮件 - * - * @param to 目标地址 - * @param from 发送地址 - * @param subject 主题 + * @param to 目标地址 + * @param from 发送地址 + * @param subject 主题 * @param template 模板 - * @param data 模板填充内容 + * @param data 模板填充内容 */ - public void send(Pair from, String subject, String template, Map data, String... to) { + public void send(Pair from, String subject, String template, Map data, + String... to) { send(from, subject, template, data, null, to); } + } diff --git a/spring-boot-example/spring-mail/src/main/java/com/livk/mail/util/FreemarkerUtils.java b/spring-boot-example/spring-mail/src/main/java/com/livk/mail/util/FreemarkerUtils.java index bd315e8fc..1edcd6c17 100644 --- a/spring-boot-example/spring-mail/src/main/java/com/livk/mail/util/FreemarkerUtils.java +++ b/spring-boot-example/spring-mail/src/main/java/com/livk/mail/util/FreemarkerUtils.java @@ -37,7 +37,8 @@ @UtilityClass public class FreemarkerUtils extends FreeMarkerTemplateUtils { - private static final Configuration CONFIGURATION = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS); + private static final Configuration CONFIGURATION = new Configuration( + Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS); private static final String TEMPLATE_NAME = "template"; @@ -49,9 +50,11 @@ public String parse(String templateName, String freemarker, Map try (StringReader reader = new StringReader(freemarker)) { Template template = new Template(templateName, reader, CONFIGURATION); return processTemplateIntoString(template, model); - } catch (Exception e) { + } + catch (Exception e) { log.error("{}", e.getMessage()); throw new RuntimeException(e); } } + } diff --git a/spring-boot-example/spring-mail/src/test/java/com/livk/mail/MailTest.java b/spring-boot-example/spring-mail/src/test/java/com/livk/mail/MailTest.java index fa5e9ad4d..bfdbd1ef2 100644 --- a/spring-boot-example/spring-mail/src/test/java/com/livk/mail/MailTest.java +++ b/spring-boot-example/spring-mail/src/test/java/com/livk/mail/MailTest.java @@ -66,7 +66,7 @@ public void test() throws Exception { // 往里面塞第一层节点 root.put("UserName", "Livk-Cloud"); - String[] temp = new String[]{"dog", "cat", "tiger"}; + String[] temp = new String[] { "dog", "cat", "tiger" }; List pets = new ArrayList<>(); Collections.addAll(pets, temp); // 往里面塞个List对象 @@ -83,7 +83,7 @@ public void test() throws Exception { helper.setTo("1375632510@qq.com"); helper.setSubject("This is subject 主题"); helper.setText(text, true); -// sender.send(mimeMessage); + // sender.send(mimeMessage); } @Test @@ -117,10 +117,10 @@ public void testSql() { String format = DateUtils.format(LocalDateTime.now(), DateUtils.YMD_HMS); String values = String.join(",", "livk", "1", "26", "shenzhen", "1", format, format); String values2 = String.join(",", "livk", "1", "26", "shenzhen", "1", format, format); - Map map = Map.of("tableName", "sys_user", - "columns", columns, - "valuesArray", List.of(values, values2)); - String resultSql = "INSERT INTO sys_user(user_name,sex,age,address,status,create_time,update_time) VALUES (livk,1,26,shenzhen,1," + format + "," + format + "),(livk,1,26,shenzhen,1," + format + "," + format + ")"; + Map map = Map.of("tableName", "sys_user", "columns", columns, "valuesArray", + List.of(values, values2)); + String resultSql = "INSERT INTO sys_user(user_name,sex,age,address,status,create_time,update_time) VALUES (livk,1,26,shenzhen,1," + + format + "," + format + "),(livk,1,26,shenzhen,1," + format + "," + format + ")"; String parse = parse(sql, map); log.info("parse result:{}", parse); assertEquals(resultSql, parse); @@ -130,28 +130,31 @@ public String parse(String freemarker, Map model) { try (StringWriter out = new StringWriter()) { new Template("template", new StringReader(freemarker), configuration).process(model, out); return out.toString(); - } catch (Exception e) { + } + catch (Exception e) { log.error("{}", e.getMessage()); return ""; } } - public String parseFtlContent(String content, Map model) { // 获取配置 StringWriter out = new StringWriter(); try { new Template("template", new StringReader(content), configuration).process(model, out); - } catch (TemplateException | IOException e) { + } + catch (TemplateException | IOException e) { return ""; } String htmlContent = out.toString(); try { out.close(); - } catch (IOException e) { + } + catch (IOException e) { return ""; } return htmlContent; } + } diff --git a/spring-boot-example/spring-micrometer/micrometer-tracing/src/main/java/com/livk/micrometer/tracing/MicrometerTraceApp.java b/spring-boot-example/spring-micrometer/micrometer-tracing/src/main/java/com/livk/micrometer/tracing/MicrometerTraceApp.java index 180e95e0f..a6254fef3 100644 --- a/spring-boot-example/spring-micrometer/micrometer-tracing/src/main/java/com/livk/micrometer/tracing/MicrometerTraceApp.java +++ b/spring-boot-example/spring-micrometer/micrometer-tracing/src/main/java/com/livk/micrometer/tracing/MicrometerTraceApp.java @@ -53,4 +53,5 @@ public String home() { wrap.shutdown(); return "Hello World!"; } + } diff --git a/spring-boot-example/spring-micrometer/micrometer-tracing/src/test/java/com/livk/micrometer/tracing/MicrometerTraceAppTest.java b/spring-boot-example/spring-micrometer/micrometer-tracing/src/test/java/com/livk/micrometer/tracing/MicrometerTraceAppTest.java index 365e41c9c..6343ddfae 100644 --- a/spring-boot-example/spring-micrometer/micrometer-tracing/src/test/java/com/livk/micrometer/tracing/MicrometerTraceAppTest.java +++ b/spring-boot-example/spring-micrometer/micrometer-tracing/src/test/java/com/livk/micrometer/tracing/MicrometerTraceAppTest.java @@ -38,6 +38,7 @@ @SpringBootTest @AutoConfigureMockMvc class MicrometerTraceAppTest { + @Autowired MockMvc mockMvc; @@ -48,5 +49,5 @@ void testHome() throws Exception { .andExpect(status().isOk()) .andExpect(content().string("Hello World!")); } -} +} diff --git a/spring-boot-example/spring-mybatis/mybatis-export/src/main/java/com/livk/export/ExportApp.java b/spring-boot-example/spring-mybatis/mybatis-export/src/main/java/com/livk/export/ExportApp.java index e13c9bb94..657c4b90c 100644 --- a/spring-boot-example/spring-mybatis/mybatis-export/src/main/java/com/livk/export/ExportApp.java +++ b/spring-boot-example/spring-mybatis/mybatis-export/src/main/java/com/livk/export/ExportApp.java @@ -25,7 +25,9 @@ */ @SpringBootApplication public class ExportApp { + public static void main(String[] args) { SpringLauncher.run(args); } + } diff --git a/spring-boot-example/spring-mybatis/mybatis-export/src/main/java/com/livk/export/controller/AuthorsController.java b/spring-boot-example/spring-mybatis/mybatis-export/src/main/java/com/livk/export/controller/AuthorsController.java index 07429092b..b95b43865 100644 --- a/spring-boot-example/spring-mybatis/mybatis-export/src/main/java/com/livk/export/controller/AuthorsController.java +++ b/spring-boot-example/spring-mybatis/mybatis-export/src/main/java/com/livk/export/controller/AuthorsController.java @@ -49,4 +49,5 @@ public HttpEntity download(HttpServletResponse response) throws IOExceptio } return ResponseEntity.ok().build(); } + } diff --git a/spring-boot-example/spring-mybatis/mybatis-export/src/main/java/com/livk/export/entity/Authors.java b/spring-boot-example/spring-mybatis/mybatis-export/src/main/java/com/livk/export/entity/Authors.java index a4bb4aa87..f1feebe1a 100644 --- a/spring-boot-example/spring-mybatis/mybatis-export/src/main/java/com/livk/export/entity/Authors.java +++ b/spring-boot-example/spring-mybatis/mybatis-export/src/main/java/com/livk/export/entity/Authors.java @@ -26,6 +26,7 @@ */ @Data public class Authors { + private Integer id; private String firstName; @@ -37,4 +38,5 @@ public class Authors { private Date birthdate; private Date added; + } diff --git a/spring-boot-example/spring-mybatis/mybatis-export/src/main/java/com/livk/export/mapper/AuthorsMapper.java b/spring-boot-example/spring-mybatis/mybatis-export/src/main/java/com/livk/export/mapper/AuthorsMapper.java index 5c7ec5fab..1af2d599f 100644 --- a/spring-boot-example/spring-mybatis/mybatis-export/src/main/java/com/livk/export/mapper/AuthorsMapper.java +++ b/spring-boot-example/spring-mybatis/mybatis-export/src/main/java/com/livk/export/mapper/AuthorsMapper.java @@ -31,4 +31,5 @@ public interface AuthorsMapper { List select(); void insertBatch(List authorsList); + } diff --git a/spring-boot-example/spring-mybatis/mybatis-export/src/main/java/com/livk/export/service/AuthorsService.java b/spring-boot-example/spring-mybatis/mybatis-export/src/main/java/com/livk/export/service/AuthorsService.java index 6e08a03bf..421c5f7a3 100644 --- a/spring-boot-example/spring-mybatis/mybatis-export/src/main/java/com/livk/export/service/AuthorsService.java +++ b/spring-boot-example/spring-mybatis/mybatis-export/src/main/java/com/livk/export/service/AuthorsService.java @@ -25,4 +25,5 @@ public interface AuthorsService { void download(PrintWriter writer); + } diff --git a/spring-boot-example/spring-mybatis/mybatis-export/src/main/java/com/livk/export/service/impl/AuthorsServiceImpl.java b/spring-boot-example/spring-mybatis/mybatis-export/src/main/java/com/livk/export/service/impl/AuthorsServiceImpl.java index 41f5e13de..6099b8b1c 100644 --- a/spring-boot-example/spring-mybatis/mybatis-export/src/main/java/com/livk/export/service/impl/AuthorsServiceImpl.java +++ b/spring-boot-example/spring-mybatis/mybatis-export/src/main/java/com/livk/export/service/impl/AuthorsServiceImpl.java @@ -41,4 +41,5 @@ public void download(PrintWriter writer) { sqlSessionTemplate.select("com.livk.export.mapper.AuthorsMapper.select", customResultHandler); writer.flush(); } + } diff --git a/spring-boot-example/spring-mybatis/mybatis-export/src/main/java/com/livk/export/support/CustomResultHandler.java b/spring-boot-example/spring-mybatis/mybatis-export/src/main/java/com/livk/export/support/CustomResultHandler.java index 3d3a0656d..7d28e8979 100644 --- a/spring-boot-example/spring-mybatis/mybatis-export/src/main/java/com/livk/export/support/CustomResultHandler.java +++ b/spring-boot-example/spring-mybatis/mybatis-export/src/main/java/com/livk/export/support/CustomResultHandler.java @@ -37,4 +37,5 @@ public void handleResult(ResultContext resultContext) { Authors authors = resultContext.getResultObject(); downloadProcessor.processData(authors); } + } diff --git a/spring-boot-example/spring-mybatis/mybatis-export/src/main/java/com/livk/export/support/DownloadProcessor.java b/spring-boot-example/spring-mybatis/mybatis-export/src/main/java/com/livk/export/support/DownloadProcessor.java index 13829003d..e8abc2f95 100644 --- a/spring-boot-example/spring-mybatis/mybatis-export/src/main/java/com/livk/export/support/DownloadProcessor.java +++ b/spring-boot-example/spring-mybatis/mybatis-export/src/main/java/com/livk/export/support/DownloadProcessor.java @@ -33,4 +33,5 @@ public void processData(E record) { writer.write(record.toString()); writer.write("\n"); } + } diff --git a/spring-boot-example/spring-mybatis/mybatis-export/src/test/java/com/livk/export/mapper/AuthorsMapperTest.java b/spring-boot-example/spring-mybatis/mybatis-export/src/test/java/com/livk/export/mapper/AuthorsMapperTest.java index 922d7ca0f..99890efca 100644 --- a/spring-boot-example/spring-mybatis/mybatis-export/src/test/java/com/livk/export/mapper/AuthorsMapperTest.java +++ b/spring-boot-example/spring-mybatis/mybatis-export/src/test/java/com/livk/export/mapper/AuthorsMapperTest.java @@ -69,4 +69,5 @@ void insert() { sqlSession.commit(); } } + } diff --git a/spring-boot-example/spring-mybatis/mybatis-tree/src/main/java/com/livk/mybatis/tree/TreeApp.java b/spring-boot-example/spring-mybatis/mybatis-tree/src/main/java/com/livk/mybatis/tree/TreeApp.java index 1ceaff883..07014d72c 100644 --- a/spring-boot-example/spring-mybatis/mybatis-tree/src/main/java/com/livk/mybatis/tree/TreeApp.java +++ b/spring-boot-example/spring-mybatis/mybatis-tree/src/main/java/com/livk/mybatis/tree/TreeApp.java @@ -25,7 +25,9 @@ */ @SpringBootApplication public class TreeApp { + public static void main(String[] args) { SpringLauncher.run(args); } + } diff --git a/spring-boot-example/spring-mybatis/mybatis-tree/src/main/java/com/livk/mybatis/tree/controller/MenuController.java b/spring-boot-example/spring-mybatis/mybatis-tree/src/main/java/com/livk/mybatis/tree/controller/MenuController.java index c16a6fc58..ff9109db7 100644 --- a/spring-boot-example/spring-mybatis/mybatis-tree/src/main/java/com/livk/mybatis/tree/controller/MenuController.java +++ b/spring-boot-example/spring-mybatis/mybatis-tree/src/main/java/com/livk/mybatis/tree/controller/MenuController.java @@ -46,4 +46,5 @@ public class MenuController { public HttpEntity> list() { return ResponseEntity.ok(menuMapper.list()); } + } diff --git a/spring-boot-example/spring-mybatis/mybatis-tree/src/main/java/com/livk/mybatis/tree/mapper/MenuMapper.java b/spring-boot-example/spring-mybatis/mybatis-tree/src/main/java/com/livk/mybatis/tree/mapper/MenuMapper.java index 06cdce439..6a07ccadd 100644 --- a/spring-boot-example/spring-mybatis/mybatis-tree/src/main/java/com/livk/mybatis/tree/mapper/MenuMapper.java +++ b/spring-boot-example/spring-mybatis/mybatis-tree/src/main/java/com/livk/mybatis/tree/mapper/MenuMapper.java @@ -33,4 +33,5 @@ public interface MenuMapper { List list(); + } diff --git a/spring-boot-example/spring-mybatis/mybatis-tree/src/test/java/com/livk/mybatis/tree/controller/MenuControllerTest.java b/spring-boot-example/spring-mybatis/mybatis-tree/src/test/java/com/livk/mybatis/tree/controller/MenuControllerTest.java index 5d103bf8a..0113f9f7b 100644 --- a/spring-boot-example/spring-mybatis/mybatis-tree/src/test/java/com/livk/mybatis/tree/controller/MenuControllerTest.java +++ b/spring-boot-example/spring-mybatis/mybatis-tree/src/test/java/com/livk/mybatis/tree/controller/MenuControllerTest.java @@ -34,13 +34,9 @@ * * @author livk */ -@SpringBootTest({ - "spring.datasource.driver-class-name=org.h2.Driver", - "spring.datasource.url=jdbc:h2:mem:test", - "spring.sql.init.schema-locations=classpath:menu.sql", - "spring.sql.init.platform=h2", - "spring.sql.init.mode=embedded", -}) +@SpringBootTest({ "spring.datasource.driver-class-name=org.h2.Driver", "spring.datasource.url=jdbc:h2:mem:test", + "spring.sql.init.schema-locations=classpath:menu.sql", "spring.sql.init.platform=h2", + "spring.sql.init.mode=embedded", }) @AutoConfigureMockMvc class MenuControllerTest { @@ -49,8 +45,7 @@ class MenuControllerTest { @Test void list() throws Exception { - mockMvc.perform(get("/menu")) - .andDo(print()) - .andExpect(status().isOk()); + mockMvc.perform(get("/menu")).andDo(print()).andExpect(status().isOk()); } + } diff --git a/spring-boot-example/spring-netty/netty-client/src/main/java/com/livk/netty/client/NettyClientApp.java b/spring-boot-example/spring-netty/netty-client/src/main/java/com/livk/netty/client/NettyClientApp.java index 675723954..99ba6e5b8 100644 --- a/spring-boot-example/spring-netty/netty-client/src/main/java/com/livk/netty/client/NettyClientApp.java +++ b/spring-boot-example/spring-netty/netty-client/src/main/java/com/livk/netty/client/NettyClientApp.java @@ -27,6 +27,7 @@ */ @SpringBootApplication public class NettyClientApp { + public static void main(String[] args) { SpringLauncher.run(args); } @@ -35,4 +36,5 @@ public static void main(String[] args) { public NettyClient nettyClient() { return new NettyClient(); } + } diff --git a/spring-boot-example/spring-netty/netty-client/src/main/java/com/livk/netty/client/controller/MseController.java b/spring-boot-example/spring-netty/netty-client/src/main/java/com/livk/netty/client/controller/MseController.java index 262c83b85..0c021e94a 100644 --- a/spring-boot-example/spring-netty/netty-client/src/main/java/com/livk/netty/client/controller/MseController.java +++ b/spring-boot-example/spring-netty/netty-client/src/main/java/com/livk/netty/client/controller/MseController.java @@ -47,8 +47,10 @@ public HttpEntity send(@RequestBody JsonNode jsonNode) throws ExecutionExc NettyMessage.Message message = NettyMessage.Message.newBuilder() .setType(NettyMessage.Message.MessageType.NORMAL) .setContent(jsonNode.toString()) - .setRequestId(UUID.randomUUID().toString()).build(); + .setRequestId(UUID.randomUUID().toString()) + .build(); ChannelFuture future = nettyClient.sendMsg(message); return ResponseEntity.ok(future.get()); } + } diff --git a/spring-boot-example/spring-netty/netty-client/src/main/java/com/livk/netty/client/process/ClientHandlerInitializer.java b/spring-boot-example/spring-netty/netty-client/src/main/java/com/livk/netty/client/process/ClientHandlerInitializer.java index 99e287271..0c4783759 100644 --- a/spring-boot-example/spring-netty/netty-client/src/main/java/com/livk/netty/client/process/ClientHandlerInitializer.java +++ b/spring-boot-example/spring-netty/netty-client/src/main/java/com/livk/netty/client/process/ClientHandlerInitializer.java @@ -46,4 +46,5 @@ protected void initChannel(Channel ch) { .addLast(new HeartbeatHandler(nettyClient)) .addLast(new NettyClientHandler()); } + } diff --git a/spring-boot-example/spring-netty/netty-client/src/main/java/com/livk/netty/client/process/HeartbeatHandler.java b/spring-boot-example/spring-netty/netty-client/src/main/java/com/livk/netty/client/process/HeartbeatHandler.java index d3fb94cf8..46be661d6 100644 --- a/spring-boot-example/spring-netty/netty-client/src/main/java/com/livk/netty/client/process/HeartbeatHandler.java +++ b/spring-boot-example/spring-netty/netty-client/src/main/java/com/livk/netty/client/process/HeartbeatHandler.java @@ -36,6 +36,7 @@ @Slf4j @RequiredArgsConstructor public class HeartbeatHandler extends ChannelInboundHandlerAdapter { + private final NettyClient nettyClient; @Override @@ -45,10 +46,12 @@ public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exc NettyMessage.Message heartbeat = NettyMessage.Message.newBuilder() .setType(NettyMessage.Message.MessageType.HEARTBEAT_CLIENT) .setRequestId(UUID.randomUUID().toString()) - .setContent("heartbeat").build(); + .setContent("heartbeat") + .build(); ctx.writeAndFlush(heartbeat).addListener(ChannelFutureListener.CLOSE_ON_FAILURE); } - } else { + } + else { super.userEventTriggered(ctx, evt); } } @@ -65,4 +68,5 @@ public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { log.error("message:{}", cause.getMessage(), cause); ctx.channel().close(); } + } diff --git a/spring-boot-example/spring-netty/netty-client/src/main/java/com/livk/netty/client/process/NettyClient.java b/spring-boot-example/spring-netty/netty-client/src/main/java/com/livk/netty/client/process/NettyClient.java index a0fc68464..913074710 100644 --- a/spring-boot-example/spring-netty/netty-client/src/main/java/com/livk/netty/client/process/NettyClient.java +++ b/spring-boot-example/spring-netty/netty-client/src/main/java/com/livk/netty/client/process/NettyClient.java @@ -36,11 +36,15 @@ */ @Slf4j public class NettyClient implements AutoCloseable { + private final EventLoopGroup group = new NioEventLoopGroup(); + @Value("${spring.netty.port}") private int port; + @Value("${spring.netty.host}") private String host; + private SocketChannel socketChannel; public ChannelFuture sendMsg(NettyMessage.Message message) { @@ -59,7 +63,8 @@ public void start() { future.addListener((ChannelFutureListener) channelFuture -> { if (channelFuture.isSuccess()) { log.info("连接Netty服务端成功"); - } else { + } + else { log.info("连接失败,进行断线重连"); channelFuture.channel().eventLoop().schedule(this::start, 20, TimeUnit.SECONDS); } @@ -71,4 +76,5 @@ public void start() { public void close() throws InterruptedException { group.shutdownGracefully().sync(); } + } diff --git a/spring-boot-example/spring-netty/netty-client/src/main/java/com/livk/netty/client/process/NettyClientHandler.java b/spring-boot-example/spring-netty/netty-client/src/main/java/com/livk/netty/client/process/NettyClientHandler.java index 6c600062e..d96548211 100644 --- a/spring-boot-example/spring-netty/netty-client/src/main/java/com/livk/netty/client/process/NettyClientHandler.java +++ b/spring-boot-example/spring-netty/netty-client/src/main/java/com/livk/netty/client/process/NettyClientHandler.java @@ -38,4 +38,5 @@ public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws E log.info("error msg:{}", cause.getMessage(), cause); ctx.close(); } + } diff --git a/spring-boot-example/spring-netty/netty-client/src/test/java/com/livk/netty/client/controller/MseControllerTest.java b/spring-boot-example/spring-netty/netty-client/src/test/java/com/livk/netty/client/controller/MseControllerTest.java index 53e836412..09c472b2a 100644 --- a/spring-boot-example/spring-netty/netty-client/src/test/java/com/livk/netty/client/controller/MseControllerTest.java +++ b/spring-boot-example/spring-netty/netty-client/src/test/java/com/livk/netty/client/controller/MseControllerTest.java @@ -35,10 +35,10 @@ @SpringBootTest @AutoConfigureWebTestClient class MseControllerTest { + @Autowired WebTestClient client; - @Test void testSend() { Map body = Map.of("username", "root", "password", "root"); @@ -50,6 +50,8 @@ void testSend() { .expectStatus() .isOk(); } + } -//Generated with love by TestMe :) Please report issues and submit feature requests at: http://weirddev.com/forum#!/testme +// Generated with love by TestMe :) Please report issues and submit feature requests at: +// http://weirddev.com/forum#!/testme diff --git a/spring-boot-example/spring-netty/netty-commons/src/main/java/com/livk/netty/commons/MessageType.java b/spring-boot-example/spring-netty/netty-commons/src/main/java/com/livk/netty/commons/MessageType.java index 2297a8351..7831b554d 100644 --- a/spring-boot-example/spring-netty/netty-commons/src/main/java/com/livk/netty/commons/MessageType.java +++ b/spring-boot-example/spring-netty/netty-commons/src/main/java/com/livk/netty/commons/MessageType.java @@ -23,5 +23,7 @@ public interface MessageType { byte HEARTBEAT_CLIENT = 1; + byte HEARTBEAT_SERVER = 2; + } diff --git a/spring-boot-example/spring-netty/netty-commons/src/main/java/com/livk/netty/commons/codec/HeartbeatDecoder.java b/spring-boot-example/spring-netty/netty-commons/src/main/java/com/livk/netty/commons/codec/HeartbeatDecoder.java index 4121f08ab..97b6972b7 100644 --- a/spring-boot-example/spring-netty/netty-commons/src/main/java/com/livk/netty/commons/codec/HeartbeatDecoder.java +++ b/spring-boot-example/spring-netty/netty-commons/src/main/java/com/livk/netty/commons/codec/HeartbeatDecoder.java @@ -28,6 +28,7 @@ * @author livk */ public class HeartbeatDecoder extends ByteToMessageDecoder { + @Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List out) throws Exception { byte version = in.readByte(); @@ -36,4 +37,5 @@ protected void decode(ChannelHandlerContext ctx, ByteBuf in, List out) t clientPackage.setVersion(version); out.add(clientPackage); } + } diff --git a/spring-boot-example/spring-netty/netty-commons/src/main/java/com/livk/netty/commons/codec/HeartbeatEncoder.java b/spring-boot-example/spring-netty/netty-commons/src/main/java/com/livk/netty/commons/codec/HeartbeatEncoder.java index 173934b28..77f1047bd 100644 --- a/spring-boot-example/spring-netty/netty-commons/src/main/java/com/livk/netty/commons/codec/HeartbeatEncoder.java +++ b/spring-boot-example/spring-netty/netty-commons/src/main/java/com/livk/netty/commons/codec/HeartbeatEncoder.java @@ -26,9 +26,11 @@ * @author livk */ public class HeartbeatEncoder extends MessageToByteEncoder { + @Override protected void encode(ChannelHandlerContext ctx, ClientPackage msg, ByteBuf out) throws Exception { out.writeByte(msg.getVersion()); out.writeByte(msg.type()); } + } diff --git a/spring-boot-example/spring-netty/netty-commons/src/main/java/com/livk/netty/commons/io/AbstractPackage.java b/spring-boot-example/spring-netty/netty-commons/src/main/java/com/livk/netty/commons/io/AbstractPackage.java index 3cd20b869..527e28d36 100644 --- a/spring-boot-example/spring-netty/netty-commons/src/main/java/com/livk/netty/commons/io/AbstractPackage.java +++ b/spring-boot-example/spring-netty/netty-commons/src/main/java/com/livk/netty/commons/io/AbstractPackage.java @@ -28,4 +28,5 @@ public abstract class AbstractPackage { protected Byte version = 1; public abstract Byte type(); + } diff --git a/spring-boot-example/spring-netty/netty-commons/src/main/java/com/livk/netty/commons/io/ClientPackage.java b/spring-boot-example/spring-netty/netty-commons/src/main/java/com/livk/netty/commons/io/ClientPackage.java index 4116f637e..48afae39b 100644 --- a/spring-boot-example/spring-netty/netty-commons/src/main/java/com/livk/netty/commons/io/ClientPackage.java +++ b/spring-boot-example/spring-netty/netty-commons/src/main/java/com/livk/netty/commons/io/ClientPackage.java @@ -23,8 +23,10 @@ * @author livk */ public class ClientPackage extends AbstractPackage { + @Override public Byte type() { return MessageType.HEARTBEAT_CLIENT; } + } diff --git a/spring-boot-example/spring-netty/netty-commons/src/main/java/com/livk/netty/commons/io/ServerPackage.java b/spring-boot-example/spring-netty/netty-commons/src/main/java/com/livk/netty/commons/io/ServerPackage.java index 14923f60f..6efa63ea7 100644 --- a/spring-boot-example/spring-netty/netty-commons/src/main/java/com/livk/netty/commons/io/ServerPackage.java +++ b/spring-boot-example/spring-netty/netty-commons/src/main/java/com/livk/netty/commons/io/ServerPackage.java @@ -23,8 +23,10 @@ * @author livk */ public class ServerPackage extends AbstractPackage { + @Override public Byte type() { return MessageType.HEARTBEAT_SERVER; } + } diff --git a/spring-boot-example/spring-netty/netty-server/src/main/java/com/livk/netty/server/NettyServerApp.java b/spring-boot-example/spring-netty/netty-server/src/main/java/com/livk/netty/server/NettyServerApp.java index 0eb21bb95..4f90748a0 100644 --- a/spring-boot-example/spring-netty/netty-server/src/main/java/com/livk/netty/server/NettyServerApp.java +++ b/spring-boot-example/spring-netty/netty-server/src/main/java/com/livk/netty/server/NettyServerApp.java @@ -27,6 +27,7 @@ */ @SpringBootApplication public class NettyServerApp { + public static void main(String[] args) { SpringLauncher.run(args); } @@ -35,4 +36,5 @@ public static void main(String[] args) { public NettyServer nettyServer() { return new NettyServer(); } + } diff --git a/spring-boot-example/spring-netty/netty-server/src/main/java/com/livk/netty/server/process/NettyServer.java b/spring-boot-example/spring-netty/netty-server/src/main/java/com/livk/netty/server/process/NettyServer.java index cba1c8ba5..09edbd26e 100644 --- a/spring-boot-example/spring-netty/netty-server/src/main/java/com/livk/netty/server/process/NettyServer.java +++ b/spring-boot-example/spring-netty/netty-server/src/main/java/com/livk/netty/server/process/NettyServer.java @@ -37,6 +37,7 @@ public class NettyServer implements AutoCloseable { private final EventLoopGroup boss = new NioEventLoopGroup(); private final EventLoopGroup work = new NioEventLoopGroup(); + @Value("${spring.netty.server.port}") private Integer port; @@ -45,16 +46,16 @@ public void start() throws InterruptedException { bootstrap.group(boss, work) // 指定Channel .channel(NioServerSocketChannel.class) - //使用指定的端口设置套接字地址 + // 使用指定的端口设置套接字地址 .localAddress(new InetSocketAddress(port)) - //服务端可连接队列数,对应TCP/IP协议listen函数中backlog参数 + // 服务端可连接队列数,对应TCP/IP协议listen函数中backlog参数 .option(ChannelOption.SO_BACKLOG, 1024) - //设置TCP长连接,一般如果两个小时内没有数据的通信时,TCP会自动发送一个活动探测数据报文 + // 设置TCP长连接,一般如果两个小时内没有数据的通信时,TCP会自动发送一个活动探测数据报文 .childOption(ChannelOption.SO_KEEPALIVE, true) - //将小的数据包包装成更大的帧进行传送,提高网络的负载 + // 将小的数据包包装成更大的帧进行传送,提高网络的负载 .childOption(ChannelOption.TCP_NODELAY, true) .childHandler(new NettyServerHandlerInitializer()); @@ -69,4 +70,5 @@ public void close() throws InterruptedException { boss.shutdownGracefully().sync(); work.shutdownGracefully().sync(); } + } diff --git a/spring-boot-example/spring-netty/netty-server/src/main/java/com/livk/netty/server/process/NettyServerHandler.java b/spring-boot-example/spring-netty/netty-server/src/main/java/com/livk/netty/server/process/NettyServerHandler.java index 52e89aa40..b80d4e92a 100644 --- a/spring-boot-example/spring-netty/netty-server/src/main/java/com/livk/netty/server/process/NettyServerHandler.java +++ b/spring-boot-example/spring-netty/netty-server/src/main/java/com/livk/netty/server/process/NettyServerHandler.java @@ -35,10 +35,12 @@ public class NettyServerHandler extends SimpleChannelInboundHandler { @Override protected void initChannel(Channel ch) throws Exception { ch.pipeline() - //空闲检测 + // 空闲检测 .addLast(new ServerIdleStateHandler()) .addLast(new ProtobufVarint32FrameDecoder()) .addLast(new ProtobufDecoder(NettyMessage.Message.getDefaultInstance())) @@ -41,4 +41,5 @@ protected void initChannel(Channel ch) throws Exception { .addLast(new ProtobufEncoder()) .addLast(new NettyServerHandler()); } + } diff --git a/spring-boot-example/spring-netty/netty-server/src/main/java/com/livk/netty/server/process/ServerIdleStateHandler.java b/spring-boot-example/spring-netty/netty-server/src/main/java/com/livk/netty/server/process/ServerIdleStateHandler.java index d9123c7aa..60d94172e 100644 --- a/spring-boot-example/spring-netty/netty-server/src/main/java/com/livk/netty/server/process/ServerIdleStateHandler.java +++ b/spring-boot-example/spring-netty/netty-server/src/main/java/com/livk/netty/server/process/ServerIdleStateHandler.java @@ -29,6 +29,7 @@ */ @Slf4j public class ServerIdleStateHandler extends IdleStateHandler { + /** * 设置空闲检测时间为 30s */ @@ -43,4 +44,5 @@ protected void channelIdle(ChannelHandlerContext ctx, IdleStateEvent evt) throws log.info("{} 秒内没有读取到数据,关闭连接", READER_IDLE_TIME); ctx.channel().close(); } + } diff --git a/spring-boot-example/spring-protobuf-mq/protobuf-commons/src/main/java/com/livk/proto/BaseUserController.java b/spring-boot-example/spring-protobuf-mq/protobuf-commons/src/main/java/com/livk/proto/BaseUserController.java index f1121832c..9665f7da0 100644 --- a/spring-boot-example/spring-protobuf-mq/protobuf-commons/src/main/java/com/livk/proto/BaseUserController.java +++ b/spring-boot-example/spring-protobuf-mq/protobuf-commons/src/main/java/com/livk/proto/BaseUserController.java @@ -30,6 +30,7 @@ public abstract class BaseUserController { protected final ThreadLocalRandom current = ThreadLocalRandom.current(); + private final ProtobufSend protobufSend; @GetMapping("send") @@ -46,4 +47,5 @@ public void send() throws Exception { protected abstract String key(); protected abstract User create(int i); + } diff --git a/spring-boot-example/spring-protobuf-mq/protobuf-commons/src/main/java/com/livk/proto/ConsumerCheck.java b/spring-boot-example/spring-protobuf-mq/protobuf-commons/src/main/java/com/livk/proto/ConsumerCheck.java index e28acad31..439a5ce49 100644 --- a/spring-boot-example/spring-protobuf-mq/protobuf-commons/src/main/java/com/livk/proto/ConsumerCheck.java +++ b/spring-boot-example/spring-protobuf-mq/protobuf-commons/src/main/java/com/livk/proto/ConsumerCheck.java @@ -33,4 +33,5 @@ public static void success() { static boolean isSuccess() { return STATUS.get(); } + } diff --git a/spring-boot-example/spring-protobuf-mq/protobuf-commons/src/main/java/com/livk/proto/ProtobufSend.java b/spring-boot-example/spring-protobuf-mq/protobuf-commons/src/main/java/com/livk/proto/ProtobufSend.java index 860a2578d..8308f3c7d 100644 --- a/spring-boot-example/spring-protobuf-mq/protobuf-commons/src/main/java/com/livk/proto/ProtobufSend.java +++ b/spring-boot-example/spring-protobuf-mq/protobuf-commons/src/main/java/com/livk/proto/ProtobufSend.java @@ -25,4 +25,5 @@ public interface ProtobufSend { void send(String key, V data) throws IOException; + } diff --git a/spring-boot-example/spring-protobuf-mq/protobuf-commons/src/main/java/com/livk/proto/User.java b/spring-boot-example/spring-protobuf-mq/protobuf-commons/src/main/java/com/livk/proto/User.java index 9f48a59ac..7399c27b5 100644 --- a/spring-boot-example/spring-protobuf-mq/protobuf-commons/src/main/java/com/livk/proto/User.java +++ b/spring-boot-example/spring-protobuf-mq/protobuf-commons/src/main/java/com/livk/proto/User.java @@ -9,4 +9,5 @@ public record User(Long id, String name, String email, Integer sex) implements Serializable { @Serial private static final long serialVersionUID = 468062760765055608L; + } diff --git a/spring-boot-example/spring-protobuf-mq/protobuf-commons/src/main/java/com/livk/proto/UserConverter.java b/spring-boot-example/spring-protobuf-mq/protobuf-commons/src/main/java/com/livk/proto/UserConverter.java index b78a3e02f..25ad269e7 100644 --- a/spring-boot-example/spring-protobuf-mq/protobuf-commons/src/main/java/com/livk/proto/UserConverter.java +++ b/spring-boot-example/spring-protobuf-mq/protobuf-commons/src/main/java/com/livk/proto/UserConverter.java @@ -17,7 +17,8 @@ default User convert(byte[] bytes) { try { UserProto.User user = UserProto.User.parseFrom(bytes); return getSource(user); - } catch (InvalidProtocolBufferException e) { + } + catch (InvalidProtocolBufferException e) { throw new RuntimeException(e); } } diff --git a/spring-boot-example/spring-protobuf-mq/protobuf-commons/src/test/java/com/livk/proto/UserConverterTest.java b/spring-boot-example/spring-protobuf-mq/protobuf-commons/src/test/java/com/livk/proto/UserConverterTest.java index 3a4e9c46a..43248c21d 100644 --- a/spring-boot-example/spring-protobuf-mq/protobuf-commons/src/test/java/com/livk/proto/UserConverterTest.java +++ b/spring-boot-example/spring-protobuf-mq/protobuf-commons/src/test/java/com/livk/proto/UserConverterTest.java @@ -21,4 +21,5 @@ void convert() { assertFalse(ObjectUtils.isEmpty(bytes)); assertEquals(user, converter.convert(bytes)); } + } diff --git a/spring-boot-example/spring-protobuf-mq/spring-protobuf-amqp/src/main/java/com/livk/proto/amqp/AmqpConsumer.java b/spring-boot-example/spring-protobuf-mq/spring-protobuf-amqp/src/main/java/com/livk/proto/amqp/AmqpConsumer.java index 68217416b..11e2d7eca 100644 --- a/spring-boot-example/spring-protobuf-mq/spring-protobuf-amqp/src/main/java/com/livk/proto/amqp/AmqpConsumer.java +++ b/spring-boot-example/spring-protobuf-mq/spring-protobuf-amqp/src/main/java/com/livk/proto/amqp/AmqpConsumer.java @@ -21,4 +21,5 @@ public void consumer(@Payload User user) { log.info(" : {}", user); ConsumerCheck.success(); } + } diff --git a/spring-boot-example/spring-protobuf-mq/spring-protobuf-amqp/src/main/java/com/livk/proto/amqp/AmqpSend.java b/spring-boot-example/spring-protobuf-mq/spring-protobuf-amqp/src/main/java/com/livk/proto/amqp/AmqpSend.java index d7dbd8fa5..f994c0944 100644 --- a/spring-boot-example/spring-protobuf-mq/spring-protobuf-amqp/src/main/java/com/livk/proto/amqp/AmqpSend.java +++ b/spring-boot-example/spring-protobuf-mq/spring-protobuf-amqp/src/main/java/com/livk/proto/amqp/AmqpSend.java @@ -36,4 +36,5 @@ public class AmqpSend implements ProtobufSend { public void send(String key, User data) { rabbitTemplate.convertAndSend(key, data); } + } diff --git a/spring-boot-example/spring-protobuf-mq/spring-protobuf-amqp/src/main/java/com/livk/proto/amqp/controller/UserController.java b/spring-boot-example/spring-protobuf-mq/spring-protobuf-amqp/src/main/java/com/livk/proto/amqp/controller/UserController.java index 773dcf6ce..25989ead8 100644 --- a/spring-boot-example/spring-protobuf-mq/spring-protobuf-amqp/src/main/java/com/livk/proto/amqp/controller/UserController.java +++ b/spring-boot-example/spring-protobuf-mq/spring-protobuf-amqp/src/main/java/com/livk/proto/amqp/controller/UserController.java @@ -27,4 +27,5 @@ protected String key() { protected User create(int i) { return new User(100L + i, "amqp", "serializer@amqp.com", current.nextInt(0, 2)); } + } diff --git a/spring-boot-example/spring-protobuf-mq/spring-protobuf-amqp/src/main/java/com/livk/proto/amqp/converter/UserAmqpProtobufMessageConverter.java b/spring-boot-example/spring-protobuf-mq/spring-protobuf-amqp/src/main/java/com/livk/proto/amqp/converter/UserAmqpProtobufMessageConverter.java index 6301f18f0..e7dd54843 100644 --- a/spring-boot-example/spring-protobuf-mq/spring-protobuf-amqp/src/main/java/com/livk/proto/amqp/converter/UserAmqpProtobufMessageConverter.java +++ b/spring-boot-example/spring-protobuf-mq/spring-protobuf-amqp/src/main/java/com/livk/proto/amqp/converter/UserAmqpProtobufMessageConverter.java @@ -35,4 +35,5 @@ protected Message createMessage(@NonNull Object object, @NonNull MessageProperti public Object fromMessage(Message message) throws MessageConversionException { return userConverter.convert(message.getBody()); } + } diff --git a/spring-boot-example/spring-protobuf-mq/spring-protobuf-amqp/src/test/java/com/livk/proto/amqp/controller/UserControllerTest.java b/spring-boot-example/spring-protobuf-mq/spring-protobuf-amqp/src/test/java/com/livk/proto/amqp/controller/UserControllerTest.java index 4185c29ad..24c453ac6 100644 --- a/spring-boot-example/spring-protobuf-mq/spring-protobuf-amqp/src/test/java/com/livk/proto/amqp/controller/UserControllerTest.java +++ b/spring-boot-example/spring-protobuf-mq/spring-protobuf-amqp/src/test/java/com/livk/proto/amqp/controller/UserControllerTest.java @@ -21,7 +21,7 @@ class UserControllerTest { @Test void send() throws Exception { - mockMvc.perform(get("/user/send")) - .andExpect(status().isOk()); + mockMvc.perform(get("/user/send")).andExpect(status().isOk()); } + } diff --git a/spring-boot-example/spring-protobuf-mq/spring-protobuf-kafka/src/main/java/com/livk/proto/kafka/KafkaApplication.java b/spring-boot-example/spring-protobuf-mq/spring-protobuf-kafka/src/main/java/com/livk/proto/kafka/KafkaApplication.java index 35482e4d8..7161cb717 100644 --- a/spring-boot-example/spring-protobuf-mq/spring-protobuf-kafka/src/main/java/com/livk/proto/kafka/KafkaApplication.java +++ b/spring-boot-example/spring-protobuf-mq/spring-protobuf-kafka/src/main/java/com/livk/proto/kafka/KafkaApplication.java @@ -14,4 +14,5 @@ public class KafkaApplication { public static void main(String[] args) { SpringLauncher.run(args); } + } diff --git a/spring-boot-example/spring-protobuf-mq/spring-protobuf-kafka/src/main/java/com/livk/proto/kafka/KafkaConsumer.java b/spring-boot-example/spring-protobuf-mq/spring-protobuf-kafka/src/main/java/com/livk/proto/kafka/KafkaConsumer.java index f0fd76621..88449c2df 100644 --- a/spring-boot-example/spring-protobuf-mq/spring-protobuf-kafka/src/main/java/com/livk/proto/kafka/KafkaConsumer.java +++ b/spring-boot-example/spring-protobuf-mq/spring-protobuf-kafka/src/main/java/com/livk/proto/kafka/KafkaConsumer.java @@ -17,8 +17,9 @@ public class KafkaConsumer { @KafkaListener(id = "consumer", topics = KafkaConfig.TOPIC_NAME) public void consumer(ConsumerRecord record) { - log.info("topic[{}],offset[{}],partition[{}],key[{}],val[{}]", - record.topic(), record.offset(), record.partition(), record.key(), record.value()); + log.info("topic[{}],offset[{}],partition[{}],key[{}],val[{}]", record.topic(), record.offset(), + record.partition(), record.key(), record.value()); ConsumerCheck.success(); } + } diff --git a/spring-boot-example/spring-protobuf-mq/spring-protobuf-kafka/src/main/java/com/livk/proto/kafka/KafkaSend.java b/spring-boot-example/spring-protobuf-mq/spring-protobuf-kafka/src/main/java/com/livk/proto/kafka/KafkaSend.java index cee398c47..bb41fd1d7 100644 --- a/spring-boot-example/spring-protobuf-mq/spring-protobuf-kafka/src/main/java/com/livk/proto/kafka/KafkaSend.java +++ b/spring-boot-example/spring-protobuf-mq/spring-protobuf-kafka/src/main/java/com/livk/proto/kafka/KafkaSend.java @@ -36,4 +36,5 @@ public class KafkaSend implements ProtobufSend { public void send(String key, User data) { kafkaTemplate.send(key, data); } + } diff --git a/spring-boot-example/spring-protobuf-mq/spring-protobuf-kafka/src/main/java/com/livk/proto/kafka/controller/UserController.java b/spring-boot-example/spring-protobuf-mq/spring-protobuf-kafka/src/main/java/com/livk/proto/kafka/controller/UserController.java index f38a42af8..9833359a8 100644 --- a/spring-boot-example/spring-protobuf-mq/spring-protobuf-kafka/src/main/java/com/livk/proto/kafka/controller/UserController.java +++ b/spring-boot-example/spring-protobuf-mq/spring-protobuf-kafka/src/main/java/com/livk/proto/kafka/controller/UserController.java @@ -27,4 +27,5 @@ protected String key() { protected User create(int i) { return new User(100L + i, "kafka", "serializer@kafka.com", current.nextInt(0, 2)); } + } diff --git a/spring-boot-example/spring-protobuf-mq/spring-protobuf-kafka/src/main/java/com/livk/proto/kafka/converter/UserKafkaProtobufConverter.java b/spring-boot-example/spring-protobuf-mq/spring-protobuf-kafka/src/main/java/com/livk/proto/kafka/converter/UserKafkaProtobufConverter.java index 29c6e13f1..c6f77391c 100644 --- a/spring-boot-example/spring-protobuf-mq/spring-protobuf-kafka/src/main/java/com/livk/proto/kafka/converter/UserKafkaProtobufConverter.java +++ b/spring-boot-example/spring-protobuf-mq/spring-protobuf-kafka/src/main/java/com/livk/proto/kafka/converter/UserKafkaProtobufConverter.java @@ -33,4 +33,5 @@ public void configure(Map configs, boolean isKey) { public void close() { } + } diff --git a/spring-boot-example/spring-protobuf-mq/spring-protobuf-kafka/src/test/java/com/livk/proto/kafka/controller/UserControllerTest.java b/spring-boot-example/spring-protobuf-mq/spring-protobuf-kafka/src/test/java/com/livk/proto/kafka/controller/UserControllerTest.java index 40e4c8383..b047a455b 100644 --- a/spring-boot-example/spring-protobuf-mq/spring-protobuf-kafka/src/test/java/com/livk/proto/kafka/controller/UserControllerTest.java +++ b/spring-boot-example/spring-protobuf-mq/spring-protobuf-kafka/src/test/java/com/livk/proto/kafka/controller/UserControllerTest.java @@ -40,7 +40,7 @@ class UserControllerTest { @Test void send() throws Exception { - mockMvc.perform(get("/user/send")) - .andExpect(status().isOk()); + mockMvc.perform(get("/user/send")).andExpect(status().isOk()); } + } diff --git a/spring-boot-example/spring-protobuf-mq/spring-protobuf-pulsar/src/main/java/com/livk/proto/pulsar/PulsarApplication.java b/spring-boot-example/spring-protobuf-mq/spring-protobuf-pulsar/src/main/java/com/livk/proto/pulsar/PulsarApplication.java index 1b8962627..40d292517 100644 --- a/spring-boot-example/spring-protobuf-mq/spring-protobuf-pulsar/src/main/java/com/livk/proto/pulsar/PulsarApplication.java +++ b/spring-boot-example/spring-protobuf-mq/spring-protobuf-pulsar/src/main/java/com/livk/proto/pulsar/PulsarApplication.java @@ -12,4 +12,5 @@ public class PulsarApplication { public static void main(String[] args) { SpringLauncher.run(args); } + } diff --git a/spring-boot-example/spring-protobuf-mq/spring-protobuf-pulsar/src/main/java/com/livk/proto/pulsar/PulsarConsumer.java b/spring-boot-example/spring-protobuf-mq/spring-protobuf-pulsar/src/main/java/com/livk/proto/pulsar/PulsarConsumer.java index cfe50a1a1..aab479ab2 100644 --- a/spring-boot-example/spring-protobuf-mq/spring-protobuf-pulsar/src/main/java/com/livk/proto/pulsar/PulsarConsumer.java +++ b/spring-boot-example/spring-protobuf-mq/spring-protobuf-pulsar/src/main/java/com/livk/proto/pulsar/PulsarConsumer.java @@ -40,4 +40,5 @@ public void receive(Message message) { log.info("topic:{} key:{} data:{}", topic, key, data); ConsumerCheck.success(); } + } diff --git a/spring-boot-example/spring-protobuf-mq/spring-protobuf-pulsar/src/main/java/com/livk/proto/pulsar/PulsarSend.java b/spring-boot-example/spring-protobuf-mq/spring-protobuf-pulsar/src/main/java/com/livk/proto/pulsar/PulsarSend.java index d55744078..40972cb7d 100644 --- a/spring-boot-example/spring-protobuf-mq/spring-protobuf-pulsar/src/main/java/com/livk/proto/pulsar/PulsarSend.java +++ b/spring-boot-example/spring-protobuf-mq/spring-protobuf-pulsar/src/main/java/com/livk/proto/pulsar/PulsarSend.java @@ -44,4 +44,5 @@ public void send(String key, User data) throws PulsarClientException { .handle((messageId, throwable) -> throwable == null) .join(); } + } diff --git a/spring-boot-example/spring-protobuf-mq/spring-protobuf-pulsar/src/main/java/com/livk/proto/pulsar/config/PulsarConfig.java b/spring-boot-example/spring-protobuf-mq/spring-protobuf-pulsar/src/main/java/com/livk/proto/pulsar/config/PulsarConfig.java index 05b70d48b..07068dc8e 100644 --- a/spring-boot-example/spring-protobuf-mq/spring-protobuf-pulsar/src/main/java/com/livk/proto/pulsar/config/PulsarConfig.java +++ b/spring-boot-example/spring-protobuf-mq/spring-protobuf-pulsar/src/main/java/com/livk/proto/pulsar/config/PulsarConfig.java @@ -31,10 +31,13 @@ public class PulsarConfig { public static final String TOPIC_NAME = "pulsar-protobuf"; /** - * Spring Pulsar + * Spring + * Pulsar */ @Bean public SchemaResolver.SchemaResolverCustomizer schemaResolverCustomizer() { return schemaResolver -> schemaResolver.addCustomSchemaMapping(User.class, new UserProtobufSchema()); } + } diff --git a/spring-boot-example/spring-protobuf-mq/spring-protobuf-pulsar/src/main/java/com/livk/proto/pulsar/controller/UserController.java b/spring-boot-example/spring-protobuf-mq/spring-protobuf-pulsar/src/main/java/com/livk/proto/pulsar/controller/UserController.java index ea06b7a9b..c6ff2262e 100644 --- a/spring-boot-example/spring-protobuf-mq/spring-protobuf-pulsar/src/main/java/com/livk/proto/pulsar/controller/UserController.java +++ b/spring-boot-example/spring-protobuf-mq/spring-protobuf-pulsar/src/main/java/com/livk/proto/pulsar/controller/UserController.java @@ -13,6 +13,7 @@ @RestController @RequestMapping("user") public class UserController extends BaseUserController { + public UserController(PulsarSend pulsarSend) { super(pulsarSend); } @@ -26,4 +27,5 @@ protected String key() { protected User create(int i) { return new User(100L + i, "pulsar", "serializer@pulsar.com", current.nextInt(0, 2)); } + } diff --git a/spring-boot-example/spring-protobuf-mq/spring-protobuf-pulsar/src/main/java/com/livk/proto/pulsar/converter/UserProtobufSchema.java b/spring-boot-example/spring-protobuf-mq/spring-protobuf-pulsar/src/main/java/com/livk/proto/pulsar/converter/UserProtobufSchema.java index a1ffff70f..c6f6ac8f0 100644 --- a/spring-boot-example/spring-protobuf-mq/spring-protobuf-pulsar/src/main/java/com/livk/proto/pulsar/converter/UserProtobufSchema.java +++ b/spring-boot-example/spring-protobuf-mq/spring-protobuf-pulsar/src/main/java/com/livk/proto/pulsar/converter/UserProtobufSchema.java @@ -50,10 +50,7 @@ public byte[] encode(User message) { @Override public SchemaInfo getSchemaInfo() { - return SchemaInfo.builder() - .name("protobuf") - .type(SchemaType.BYTES) - .schema(new byte[0]) - .build(); + return SchemaInfo.builder().name("protobuf").type(SchemaType.BYTES).schema(new byte[0]).build(); } + } diff --git a/spring-boot-example/spring-protobuf-mq/spring-protobuf-pulsar/src/test/java/com/livk/proto/pulsar/controller/UserControllerTest.java b/spring-boot-example/spring-protobuf-mq/spring-protobuf-pulsar/src/test/java/com/livk/proto/pulsar/controller/UserControllerTest.java index 7400c7d92..ec4ac42f1 100644 --- a/spring-boot-example/spring-protobuf-mq/spring-protobuf-pulsar/src/test/java/com/livk/proto/pulsar/controller/UserControllerTest.java +++ b/spring-boot-example/spring-protobuf-mq/spring-protobuf-pulsar/src/test/java/com/livk/proto/pulsar/controller/UserControllerTest.java @@ -38,7 +38,7 @@ class UserControllerTest { @Test void send() throws Exception { - mockMvc.perform(get("/user/send")) - .andExpect(status().isOk()); + mockMvc.perform(get("/user/send")).andExpect(status().isOk()); } + } diff --git a/spring-boot-example/spring-protobuf-mq/spring-protobuf-rocketmq/src/main/java/com/livk/proto/rocketmq/RocketMQMessageConverterBeanPostProcessor.java b/spring-boot-example/spring-protobuf-mq/spring-protobuf-rocketmq/src/main/java/com/livk/proto/rocketmq/RocketMQMessageConverterBeanPostProcessor.java index bcb134114..48e3deb8a 100644 --- a/spring-boot-example/spring-protobuf-mq/spring-protobuf-rocketmq/src/main/java/com/livk/proto/rocketmq/RocketMQMessageConverterBeanPostProcessor.java +++ b/spring-boot-example/spring-protobuf-mq/spring-protobuf-rocketmq/src/main/java/com/livk/proto/rocketmq/RocketMQMessageConverterBeanPostProcessor.java @@ -18,7 +18,8 @@ public class RocketMQMessageConverterBeanPostProcessor implements BeanPostProcessor { @Override - public Object postProcessBeforeInitialization(@NonNull Object bean, @NonNull String beanName) throws BeansException { + public Object postProcessBeforeInitialization(@NonNull Object bean, @NonNull String beanName) + throws BeansException { if (bean instanceof RocketMQMessageConverter rocketMQMessageConverter) { MessageConverter messageConverter = rocketMQMessageConverter.getMessageConverter(); if (messageConverter instanceof CompositeMessageConverter compositeMessageConverter) { @@ -29,4 +30,5 @@ public Object postProcessBeforeInitialization(@NonNull Object bean, @NonNull Str } return bean; } + } diff --git a/spring-boot-example/spring-protobuf-mq/spring-protobuf-rocketmq/src/main/java/com/livk/proto/rocketmq/RocketMqApplication.java b/spring-boot-example/spring-protobuf-mq/spring-protobuf-rocketmq/src/main/java/com/livk/proto/rocketmq/RocketMqApplication.java index 1a570e886..ae1696f0a 100644 --- a/spring-boot-example/spring-protobuf-mq/spring-protobuf-rocketmq/src/main/java/com/livk/proto/rocketmq/RocketMqApplication.java +++ b/spring-boot-example/spring-protobuf-mq/spring-protobuf-rocketmq/src/main/java/com/livk/proto/rocketmq/RocketMqApplication.java @@ -12,4 +12,5 @@ public class RocketMqApplication { public static void main(String[] args) { SpringLauncher.run(args); } + } diff --git a/spring-boot-example/spring-protobuf-mq/spring-protobuf-rocketmq/src/main/java/com/livk/proto/rocketmq/RocketMqConsumer.java b/spring-boot-example/spring-protobuf-mq/spring-protobuf-rocketmq/src/main/java/com/livk/proto/rocketmq/RocketMqConsumer.java index cd8b82c62..a258b4d73 100644 --- a/spring-boot-example/spring-protobuf-mq/spring-protobuf-rocketmq/src/main/java/com/livk/proto/rocketmq/RocketMqConsumer.java +++ b/spring-boot-example/spring-protobuf-mq/spring-protobuf-rocketmq/src/main/java/com/livk/proto/rocketmq/RocketMqConsumer.java @@ -38,4 +38,5 @@ public void onMessage(User message) { log.info("data:{}", message); ConsumerCheck.success(); } + } diff --git a/spring-boot-example/spring-protobuf-mq/spring-protobuf-rocketmq/src/main/java/com/livk/proto/rocketmq/RocketMqSend.java b/spring-boot-example/spring-protobuf-mq/spring-protobuf-rocketmq/src/main/java/com/livk/proto/rocketmq/RocketMqSend.java index 65ed15daa..fb6793790 100644 --- a/spring-boot-example/spring-protobuf-mq/spring-protobuf-rocketmq/src/main/java/com/livk/proto/rocketmq/RocketMqSend.java +++ b/spring-boot-example/spring-protobuf-mq/spring-protobuf-rocketmq/src/main/java/com/livk/proto/rocketmq/RocketMqSend.java @@ -36,4 +36,5 @@ public class RocketMqSend implements ProtobufSend { public void send(String key, User data) { rocketMQTemplate.convertAndSend(key, data); } + } diff --git a/spring-boot-example/spring-protobuf-mq/spring-protobuf-rocketmq/src/main/java/com/livk/proto/rocketmq/config/RocketMqConfig.java b/spring-boot-example/spring-protobuf-mq/spring-protobuf-rocketmq/src/main/java/com/livk/proto/rocketmq/config/RocketMqConfig.java index f7b3a65a0..be5d20045 100644 --- a/spring-boot-example/spring-protobuf-mq/spring-protobuf-rocketmq/src/main/java/com/livk/proto/rocketmq/config/RocketMqConfig.java +++ b/spring-boot-example/spring-protobuf-mq/spring-protobuf-rocketmq/src/main/java/com/livk/proto/rocketmq/config/RocketMqConfig.java @@ -26,4 +26,5 @@ public class RocketMqConfig { public static final String TOPIC_NAME = "rocketmq-protobuf"; + } diff --git a/spring-boot-example/spring-protobuf-mq/spring-protobuf-rocketmq/src/main/java/com/livk/proto/rocketmq/controller/UserController.java b/spring-boot-example/spring-protobuf-mq/spring-protobuf-rocketmq/src/main/java/com/livk/proto/rocketmq/controller/UserController.java index 959d2be7e..36db4d08d 100644 --- a/spring-boot-example/spring-protobuf-mq/spring-protobuf-rocketmq/src/main/java/com/livk/proto/rocketmq/controller/UserController.java +++ b/spring-boot-example/spring-protobuf-mq/spring-protobuf-rocketmq/src/main/java/com/livk/proto/rocketmq/controller/UserController.java @@ -27,4 +27,5 @@ protected String key() { protected User create(int i) { return new User(100L + i, "rocketmq", "serializer@rocketmq.com", current.nextInt(0, 2)); } + } diff --git a/spring-boot-example/spring-protobuf-mq/spring-protobuf-rocketmq/src/main/java/com/livk/proto/rocketmq/converter/UserProtobufMessageConverter.java b/spring-boot-example/spring-protobuf-mq/spring-protobuf-rocketmq/src/main/java/com/livk/proto/rocketmq/converter/UserProtobufMessageConverter.java index 562955ba6..1ac7b60f8 100644 --- a/spring-boot-example/spring-protobuf-mq/spring-protobuf-rocketmq/src/main/java/com/livk/proto/rocketmq/converter/UserProtobufMessageConverter.java +++ b/spring-boot-example/spring-protobuf-mq/spring-protobuf-rocketmq/src/main/java/com/livk/proto/rocketmq/converter/UserProtobufMessageConverter.java @@ -48,4 +48,5 @@ public Message toMessage(@NonNull Object payload, MessageHeaders headers) { } return null; } + } diff --git a/spring-boot-example/spring-protobuf-mq/spring-protobuf-rocketmq/src/test/java/com/livk/proto/rocketmq/controller/UserControllerTest.java b/spring-boot-example/spring-protobuf-mq/spring-protobuf-rocketmq/src/test/java/com/livk/proto/rocketmq/controller/UserControllerTest.java index 5ee70f99b..fe5823cfa 100644 --- a/spring-boot-example/spring-protobuf-mq/spring-protobuf-rocketmq/src/test/java/com/livk/proto/rocketmq/controller/UserControllerTest.java +++ b/spring-boot-example/spring-protobuf-mq/spring-protobuf-rocketmq/src/test/java/com/livk/proto/rocketmq/controller/UserControllerTest.java @@ -40,7 +40,7 @@ class UserControllerTest { @Test void send() throws Exception { - mockMvc.perform(get("/user/send")) - .andExpect(status().isOk()); + mockMvc.perform(get("/user/send")).andExpect(status().isOk()); } + } diff --git a/spring-boot-example/spring-pulsar/pulsar-commons/src/main/java/com/livk/pulsar/common/entity/PulsarMessage.java b/spring-boot-example/spring-pulsar/pulsar-commons/src/main/java/com/livk/pulsar/common/entity/PulsarMessage.java index fb1cc99b4..aa8680b5e 100644 --- a/spring-boot-example/spring-pulsar/pulsar-commons/src/main/java/com/livk/pulsar/common/entity/PulsarMessage.java +++ b/spring-boot-example/spring-pulsar/pulsar-commons/src/main/java/com/livk/pulsar/common/entity/PulsarMessage.java @@ -42,4 +42,5 @@ public class PulsarMessage implements Serializable { public String toJson() { return JsonMapperUtils.writeValueAsString(this); } + } diff --git a/spring-boot-example/spring-pulsar/pulsar-consumer/src/main/java/com/livk/pulsar/consumer/MessageConsumer.java b/spring-boot-example/spring-pulsar/pulsar-consumer/src/main/java/com/livk/pulsar/consumer/MessageConsumer.java index 93d27a91d..3270efb83 100644 --- a/spring-boot-example/spring-pulsar/pulsar-consumer/src/main/java/com/livk/pulsar/consumer/MessageConsumer.java +++ b/spring-boot-example/spring-pulsar/pulsar-consumer/src/main/java/com/livk/pulsar/consumer/MessageConsumer.java @@ -40,4 +40,5 @@ public void receive(Message message) { String topic = message.getTopicName(); log.info("topic:{} key:{} data:{}", topic, key, data); } + } diff --git a/spring-boot-example/spring-pulsar/pulsar-producer/src/main/java/com/livk/pulsar/producer/ProducerTask.java b/spring-boot-example/spring-pulsar/pulsar-producer/src/main/java/com/livk/pulsar/producer/ProducerTask.java index c5fdcb444..f00f021b3 100644 --- a/spring-boot-example/spring-pulsar/pulsar-producer/src/main/java/com/livk/pulsar/producer/ProducerTask.java +++ b/spring-boot-example/spring-pulsar/pulsar-producer/src/main/java/com/livk/pulsar/producer/ProducerTask.java @@ -41,6 +41,7 @@ public class ProducerTask { private static final Snowflake SNOWFLAKE = new Snowflake(); + private final PulsarTemplate pulsarTemplate; @Scheduled(cron = "0/5 * * * * ?") diff --git a/spring-boot-example/spring-pulsar/pulsar-producer/src/main/java/com/livk/pulsar/producer/controller/MessageController.java b/spring-boot-example/spring-pulsar/pulsar-producer/src/main/java/com/livk/pulsar/producer/controller/MessageController.java index d1b9b5a90..59909ebaf 100644 --- a/spring-boot-example/spring-pulsar/pulsar-producer/src/main/java/com/livk/pulsar/producer/controller/MessageController.java +++ b/spring-boot-example/spring-pulsar/pulsar-producer/src/main/java/com/livk/pulsar/producer/controller/MessageController.java @@ -58,4 +58,5 @@ public HttpEntity send(@RequestBody JsonNode jsonNode) throws Exception MessageId messageId = pulsarTemplate.sendAsync(message.toJson(), Schema.STRING).get(); return ResponseEntity.ok(JsonMapperUtils.writeValueAsString(messageId)); } + } diff --git a/spring-boot-example/spring-pulsar/pulsar-producer/src/test/java/com/livk/pulsar/producer/controller/MessageConsumerTest.java b/spring-boot-example/spring-pulsar/pulsar-producer/src/test/java/com/livk/pulsar/producer/controller/MessageConsumerTest.java index 298fedaec..c23ccea53 100644 --- a/spring-boot-example/spring-pulsar/pulsar-producer/src/test/java/com/livk/pulsar/producer/controller/MessageConsumerTest.java +++ b/spring-boot-example/spring-pulsar/pulsar-producer/src/test/java/com/livk/pulsar/producer/controller/MessageConsumerTest.java @@ -40,4 +40,5 @@ public void receive(Message message) { String topic = message.getTopicName(); log.info("topic:{} key:{} data:{}", topic, key, data); } + } diff --git a/spring-boot-example/spring-pulsar/pulsar-producer/src/test/java/com/livk/pulsar/producer/controller/MessageControllerTest.java b/spring-boot-example/spring-pulsar/pulsar-producer/src/test/java/com/livk/pulsar/producer/controller/MessageControllerTest.java index 7c128246f..d21525060 100644 --- a/spring-boot-example/spring-pulsar/pulsar-producer/src/test/java/com/livk/pulsar/producer/controller/MessageControllerTest.java +++ b/spring-boot-example/spring-pulsar/pulsar-producer/src/test/java/com/livk/pulsar/producer/controller/MessageControllerTest.java @@ -38,25 +38,22 @@ * * @author livk */ -@SpringBootTest({ - "spring.pulsar.client.service-url=pulsar://livk.com:6650", - "spring.pulsar.consumer.topics=livk-topic", - "spring.pulsar.consumer.subscription-name=consumer" -}) +@SpringBootTest({ "spring.pulsar.client.service-url=pulsar://livk.com:6650", "spring.pulsar.consumer.topics=livk-topic", + "spring.pulsar.consumer.subscription-name=consumer" }) @AutoConfigureMockMvc class MessageControllerTest { + @Autowired MockMvc mockMvc; - @Test void testSend() throws Exception { Map map = Map.of("username", "livk", "password", "123456"); - mockMvc.perform(post("/producer") - .contentType(MediaType.APPLICATION_JSON) + mockMvc + .perform(post("/producer").contentType(MediaType.APPLICATION_JSON) .content(JsonMapperUtils.writeValueAsString(map))) .andExpect(status().isOk()) .andDo(print()); } -} +} diff --git a/spring-boot-example/spring-quartz/src/main/java/com/livk/quartz/config/QuartzScheduler.java b/spring-boot-example/spring-quartz/src/main/java/com/livk/quartz/config/QuartzScheduler.java index 8d2810860..b2382a6dc 100644 --- a/spring-boot-example/spring-quartz/src/main/java/com/livk/quartz/config/QuartzScheduler.java +++ b/spring-boot-example/spring-quartz/src/main/java/com/livk/quartz/config/QuartzScheduler.java @@ -50,7 +50,9 @@ public boolean modifyJob(String name, String group, String time) throws Schedule String oldTime = cronTrigger.getCronExpression(); if (!oldTime.equalsIgnoreCase(time)) { CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(time); - CronTrigger build = TriggerBuilder.newTrigger().withIdentity(name, group).withSchedule(cronScheduleBuilder) + CronTrigger build = TriggerBuilder.newTrigger() + .withIdentity(name, group) + .withSchedule(cronScheduleBuilder) .build(); date = scheduler.rescheduleJob(triggerKey, build); } diff --git a/spring-boot-example/spring-quartz/src/main/java/com/livk/quartz/controller/QuartzController.java b/spring-boot-example/spring-quartz/src/main/java/com/livk/quartz/controller/QuartzController.java index ca30e0188..5cd6280d9 100644 --- a/spring-boot-example/spring-quartz/src/main/java/com/livk/quartz/controller/QuartzController.java +++ b/spring-boot-example/spring-quartz/src/main/java/com/livk/quartz/controller/QuartzController.java @@ -39,10 +39,14 @@ public class QuartzController { @PostMapping("livkTask") public Mono livkTask() throws SchedulerException { - JobDetail jobDetail = JobBuilder.newJob(com.livk.quartz.scheduler.QuartzScheduler.class).withIdentity("job2", "group2").build(); + JobDetail jobDetail = JobBuilder.newJob(com.livk.quartz.scheduler.QuartzScheduler.class) + .withIdentity("job2", "group2") + .build(); jobDetail.getJobDataMap().put("user", "tom2"); CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule("0/10 * * * * ?"); - CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity("job2", "group2").withSchedule(cronScheduleBuilder) + CronTrigger cronTrigger = TriggerBuilder.newTrigger() + .withIdentity("job2", "group2") + .withSchedule(cronScheduleBuilder) .build(); quartzScheduler.scheduleJob(jobDetail, cronTrigger); return Mono.empty(); diff --git a/spring-boot-example/spring-r2dbc/src/main/java/com/livk/r2dbc/controller/UserController.java b/spring-boot-example/spring-r2dbc/src/main/java/com/livk/r2dbc/controller/UserController.java index 6cdf23482..e83668747 100644 --- a/spring-boot-example/spring-r2dbc/src/main/java/com/livk/r2dbc/controller/UserController.java +++ b/spring-boot-example/spring-r2dbc/src/main/java/com/livk/r2dbc/controller/UserController.java @@ -52,7 +52,8 @@ public HttpEntity> users() { @Bean public RouterFunction userList() { return RouterFunctions.route() - .GET("/stream/user", request -> ServerResponse.ok().body(userService.list(), User.class)).build(); + .GET("/stream/user", request -> ServerResponse.ok().body(userService.list(), User.class)) + .build(); } @GetMapping("/{id}") diff --git a/spring-boot-example/spring-r2dbc/src/main/java/com/livk/r2dbc/service/impl/UserServiceImpl.java b/spring-boot-example/spring-r2dbc/src/main/java/com/livk/r2dbc/service/impl/UserServiceImpl.java index 10a581ae6..c1b0b606b 100644 --- a/spring-boot-example/spring-r2dbc/src/main/java/com/livk/r2dbc/service/impl/UserServiceImpl.java +++ b/spring-boot-example/spring-r2dbc/src/main/java/com/livk/r2dbc/service/impl/UserServiceImpl.java @@ -52,13 +52,15 @@ public Mono getById(Mono id) { @Override public Mono save(Mono userMono) { - return userMono.flatMap(user -> userRepository.save(user).flatMap( - u1 -> Objects.nonNull(u1.id()) ? Mono.empty() : Mono.defer(() -> Mono.error(new RuntimeException())))); + return userMono.flatMap(user -> userRepository.save(user) + .flatMap(u1 -> Objects.nonNull(u1.id()) ? Mono.empty() + : Mono.defer(() -> Mono.error(new RuntimeException())))); } @Override public Mono updateById(Mono id, Mono userMono) { - return userMono.flatMap(monoUser -> userRepository.findById(id) + return userMono + .flatMap(monoUser -> userRepository.findById(id) .switchIfEmpty(Mono.error(new RuntimeException("Id Not Found!"))) .flatMap(user -> userRepository.save(new User(user.id(), monoUser.username(), monoUser.password())))) .flatMap(mono -> Mono.empty()); diff --git a/spring-boot-example/spring-rabbit/rabbit-commons/src/main/java/com/livk/amqp/config/TopicConfig.java b/spring-boot-example/spring-rabbit/rabbit-commons/src/main/java/com/livk/amqp/config/TopicConfig.java index 3cf726727..6fd501fb5 100644 --- a/spring-boot-example/spring-rabbit/rabbit-commons/src/main/java/com/livk/amqp/config/TopicConfig.java +++ b/spring-boot-example/spring-rabbit/rabbit-commons/src/main/java/com/livk/amqp/config/TopicConfig.java @@ -102,4 +102,5 @@ public Binding bindTopicC() { public MessageConverter messageConverter(ObjectMapper objectMapper) { return new Jackson2JsonMessageConverter(objectMapper, "com.livk.amqp.entity"); } + } diff --git a/spring-boot-example/spring-rabbit/rabbit-provider/src/main/java/com/livk/provider/send/RabbitSend.java b/spring-boot-example/spring-rabbit/rabbit-provider/src/main/java/com/livk/provider/send/RabbitSend.java index c8dd29307..5fcb70c88 100644 --- a/spring-boot-example/spring-rabbit/rabbit-provider/src/main/java/com/livk/provider/send/RabbitSend.java +++ b/spring-boot-example/spring-rabbit/rabbit-provider/src/main/java/com/livk/provider/send/RabbitSend.java @@ -71,7 +71,7 @@ public void sendMsgHeaders(Message message, Map map) { messageProperties.setContentType("UTF-8"); messageProperties.getHeaders().putAll(map); org.springframework.amqp.core.Message msg = new org.springframework.amqp.core.Message( - message.toString().getBytes(), messageProperties); + message.toString().getBytes(), messageProperties); rabbitTemplate.convertAndSend(HeadersConfig.HEADERS_EXCHANGE_NAME, null, msg); } diff --git a/spring-boot-example/spring-rabbit/rabbit-provider/src/test/java/com/livk/provider/ConsumerTest.java b/spring-boot-example/spring-rabbit/rabbit-provider/src/test/java/com/livk/provider/ConsumerTest.java index 577708367..3a2634210 100644 --- a/spring-boot-example/spring-rabbit/rabbit-provider/src/test/java/com/livk/provider/ConsumerTest.java +++ b/spring-boot-example/spring-rabbit/rabbit-provider/src/test/java/com/livk/provider/ConsumerTest.java @@ -35,6 +35,7 @@ @Slf4j @Component public class ConsumerTest { + @RabbitListener(queuesToDeclare = @Queue(DirectConfig.RABBIT_DIRECT_TOPIC)) public void consumerDirect(@Payload Message message) { log.info("direct anno consumer msg:{}", message); @@ -78,4 +79,5 @@ public void consumerHeadersB(org.springframework.amqp.core.Message message) thro String contentType = messageProperties.getContentType(); log.info("headers B anno consumer msg:{}", new String(message.getBody(), contentType)); } + } diff --git a/spring-boot-example/spring-rabbit/rabbit-provider/src/test/java/com/livk/provider/controller/RabbitControllerTest.java b/spring-boot-example/spring-rabbit/rabbit-provider/src/test/java/com/livk/provider/controller/RabbitControllerTest.java index 28d09c5c6..19cf0f586 100644 --- a/spring-boot-example/spring-rabbit/rabbit-provider/src/test/java/com/livk/provider/controller/RabbitControllerTest.java +++ b/spring-boot-example/spring-rabbit/rabbit-provider/src/test/java/com/livk/provider/controller/RabbitControllerTest.java @@ -38,60 +38,55 @@ @AutoConfigureMockMvc class RabbitControllerTest { - static String body = JsonMapperUtils.writeValueAsString(Map.of( - "msg", "hello", - "data", "By Livk" - )); + static String body = JsonMapperUtils.writeValueAsString(Map.of("msg", "hello", "data", "By Livk")); + @Autowired MockMvc mockMvc; @Test void sendMsgDirect() throws Exception { - mockMvc.perform(post("/provider/sendMsgDirect") - .contentType(MediaType.APPLICATION_JSON) - .content(body)) + mockMvc.perform(post("/provider/sendMsgDirect").contentType(MediaType.APPLICATION_JSON).content(body)) .andDo(print()) .andExpect(status().isOk()); } @Test void sendMsgFanout() throws Exception { - mockMvc.perform(post("/provider/sendMsgFanout") - .contentType(MediaType.APPLICATION_JSON) - .content(body)) + mockMvc.perform(post("/provider/sendMsgFanout").contentType(MediaType.APPLICATION_JSON).content(body)) .andDo(print()) .andExpect(status().isOk()); } @Test void sendMsgTopic() throws Exception { - mockMvc.perform(post("/provider/sendMsgTopic/{key}", "rabbit.a.b") - .contentType(MediaType.APPLICATION_JSON) + mockMvc + .perform(post("/provider/sendMsgTopic/{key}", "rabbit.a.b").contentType(MediaType.APPLICATION_JSON) .content(body)) .andDo(print()) .andExpect(status().isOk()); - mockMvc.perform(post("/provider/sendMsgTopic/{key}", "a.b") - .contentType(MediaType.APPLICATION_JSON) - .content(body)) + mockMvc + .perform(post("/provider/sendMsgTopic/{key}", "a.b").contentType(MediaType.APPLICATION_JSON).content(body)) .andDo(print()) .andExpect(status().isOk()); } @Test void sendMsgHeaders() throws Exception { - mockMvc.perform(post("/provider/sendMsgHeaders") - .queryParam("json", "{\"auth\":\"livk\"}") + mockMvc + .perform(post("/provider/sendMsgHeaders").queryParam("json", "{\"auth\":\"livk\"}") .contentType(MediaType.APPLICATION_JSON) .content(body)) .andDo(print()) .andExpect(status().isOk()); - mockMvc.perform(post("/provider/sendMsgHeaders") - .queryParam("json", "{\"username\":\"livk\",\"password\":\"livk\"}") - .contentType(MediaType.APPLICATION_JSON) - .content(body)) + mockMvc + .perform( + post("/provider/sendMsgHeaders").queryParam("json", "{\"username\":\"livk\",\"password\":\"livk\"}") + .contentType(MediaType.APPLICATION_JSON) + .content(body)) .andDo(print()) .andExpect(status().isOk()); } + } diff --git a/spring-boot-example/spring-rabbit/rabbitmq-mqtt/src/main/java/com/livk/mqtt/config/MqttReceiverConfig.java b/spring-boot-example/spring-rabbit/rabbitmq-mqtt/src/main/java/com/livk/mqtt/config/MqttReceiverConfig.java index 4ac13a84f..a20332023 100644 --- a/spring-boot-example/spring-rabbit/rabbitmq-mqtt/src/main/java/com/livk/mqtt/config/MqttReceiverConfig.java +++ b/spring-boot-example/spring-rabbit/rabbitmq-mqtt/src/main/java/com/livk/mqtt/config/MqttReceiverConfig.java @@ -58,8 +58,8 @@ public MessageChannel mqttInboundChannel() { @Bean public MessageProducer inbound(MqttPahoClientFactory factory, MqttProperties mqttProperties) { // 可以同时消费(订阅)多个Topic - MqttPahoMessageDrivenChannelAdapter adapter = new MqttPahoMessageDrivenChannelAdapter(mqttProperties.getReceiver().getClientId(), factory, - mqttProperties.getReceiver().getDefaultTopic()); + MqttPahoMessageDrivenChannelAdapter adapter = new MqttPahoMessageDrivenChannelAdapter( + mqttProperties.getReceiver().getClientId(), factory, mqttProperties.getReceiver().getDefaultTopic()); adapter.setCompletionTimeout(5000); adapter.setConverter(new DefaultPahoMessageConverter()); adapter.setQos(1); diff --git a/spring-boot-example/spring-rabbit/rabbitmq-mqtt/src/main/java/com/livk/mqtt/config/MqttSenderConfig.java b/spring-boot-example/spring-rabbit/rabbitmq-mqtt/src/main/java/com/livk/mqtt/config/MqttSenderConfig.java index f5af14751..a221eb9cf 100644 --- a/spring-boot-example/spring-rabbit/rabbitmq-mqtt/src/main/java/com/livk/mqtt/config/MqttSenderConfig.java +++ b/spring-boot-example/spring-rabbit/rabbitmq-mqtt/src/main/java/com/livk/mqtt/config/MqttSenderConfig.java @@ -53,7 +53,7 @@ public MessageChannel mqttOutboundChannel() { @ServiceActivator(inputChannel = CHANNEL_NAME_OUT) public MessageHandler mqttOutbound(MqttPahoClientFactory mqttPahoClientFactory, MqttProperties mqttProperties) { MqttPahoMessageHandler messageHandler = new MqttPahoMessageHandler(mqttProperties.getSender().getClientId(), - mqttPahoClientFactory); + mqttPahoClientFactory); messageHandler.setAsync(true); messageHandler.setDefaultTopic(mqttProperties.getSender().getDefaultTopic()); return messageHandler; diff --git a/spring-boot-example/spring-rabbit/rabbitmq-mqtt/src/main/java/com/livk/mqtt/handler/MqttSender.java b/spring-boot-example/spring-rabbit/rabbitmq-mqtt/src/main/java/com/livk/mqtt/handler/MqttSender.java index 066fa9b7b..ce99c627c 100644 --- a/spring-boot-example/spring-rabbit/rabbitmq-mqtt/src/main/java/com/livk/mqtt/handler/MqttSender.java +++ b/spring-boot-example/spring-rabbit/rabbitmq-mqtt/src/main/java/com/livk/mqtt/handler/MqttSender.java @@ -34,25 +34,22 @@ public interface MqttSender { /** * 发送信息到MQTT服务器 - * * @param data 发送的文本 */ void sendToMqtt(String data); /** * 发送信息到MQTT服务器 - * - * @param topic 主题 + * @param topic 主题 * @param payload 消息主体 */ void sendToMqtt(@Header(MqttHeaders.TOPIC) String topic, String payload); /** * 发送信息到MQTT服务器 - * - * @param topic 主题 - * @param qos 对消息处理的几种机制。 0 表示的是订阅者没收到消息不会再次发送,消息会丢失。 1 - * 表示的是会尝试重试,一直到接收到消息,但这种情况可能导致订阅者收到多次重复消息。 2 多了一次去重的动作,确保订阅者收到的消息有一次。 + * @param topic 主题 + * @param qos 对消息处理的几种机制。 0 表示的是订阅者没收到消息不会再次发送,消息会丢失。 1 + * 表示的是会尝试重试,一直到接收到消息,但这种情况可能导致订阅者收到多次重复消息。 2 多了一次去重的动作,确保订阅者收到的消息有一次。 * @param payload 消息主体 */ void sendToMqtt(@Header(MqttHeaders.TOPIC) String topic, @Header(MqttHeaders.QOS) int qos, String payload); diff --git a/spring-boot-example/spring-rabbit/rabbitmq-order-expired/src/main/java/com/livk/order/OrderApp.java b/spring-boot-example/spring-rabbit/rabbitmq-order-expired/src/main/java/com/livk/order/OrderApp.java index 3a13572e9..34eb237ab 100644 --- a/spring-boot-example/spring-rabbit/rabbitmq-order-expired/src/main/java/com/livk/order/OrderApp.java +++ b/spring-boot-example/spring-rabbit/rabbitmq-order-expired/src/main/java/com/livk/order/OrderApp.java @@ -29,7 +29,9 @@ */ @SpringBootApplication public class OrderApp { + public static void main(String[] args) { SpringLauncher.run(args); } + } diff --git a/spring-boot-example/spring-rabbit/rabbitmq-order-expired/src/main/java/com/livk/order/config/OrderListener.java b/spring-boot-example/spring-rabbit/rabbitmq-order-expired/src/main/java/com/livk/order/config/OrderListener.java index 209cdbb8c..61d961846 100644 --- a/spring-boot-example/spring-rabbit/rabbitmq-order-expired/src/main/java/com/livk/order/config/OrderListener.java +++ b/spring-boot-example/spring-rabbit/rabbitmq-order-expired/src/main/java/com/livk/order/config/OrderListener.java @@ -48,14 +48,16 @@ public void processFail(String order, Message message, Channel channel) throws I public void processSuc(String order, Message message, Channel channel) throws IOException, InterruptedException { log.info("【订单号】 - [{}]", order); TimeUnit.SECONDS.sleep(1); - //是否支付 + // 是否支付 int i = ThreadLocalRandom.current().nextInt(1, 100); if (i == 6) { channel.basicAck(message.getMessageProperties().getDeliveryTag(), false); log.info("支付成功!"); - } else { + } + else { channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true); log.warn("缺少支付!"); } } + } diff --git a/spring-boot-example/spring-rabbit/rabbitmq-order-expired/src/main/java/com/livk/order/config/RabbitConfig.java b/spring-boot-example/spring-rabbit/rabbitmq-order-expired/src/main/java/com/livk/order/config/RabbitConfig.java index e491ed109..b8d439962 100644 --- a/spring-boot-example/spring-rabbit/rabbitmq-order-expired/src/main/java/com/livk/order/config/RabbitConfig.java +++ b/spring-boot-example/spring-rabbit/rabbitmq-order-expired/src/main/java/com/livk/order/config/RabbitConfig.java @@ -41,27 +41,27 @@ public class RabbitConfig { public final static String orderQueue = "order_queue"; - //交换机名称 + // 交换机名称 public final static String orderExchange = "order_exchange"; // routingKey public final static String routingKeyOrder = "routing_key_order"; - //死信消息队列名称 + // 死信消息队列名称 public final static String dealQueueOrder = "deal_queue_order"; - //死信交换机名称 + // 死信交换机名称 public final static String dealExchangeOrder = "deal_exchange_order"; - //死信 routingKey + // 死信 routingKey public final static String deadRoutingKeyOrder = "dead_routing_key_order"; public final static String MESSAGE_TTL = "x-message-ttl"; - //死信队列 交换机标识符 + // 死信队列 交换机标识符 public static final String DEAD_LETTER_QUEUE_KEY = "x-dead-letter-exchange"; - //死信队列交换机绑定键标识符 + // 死信队列交换机绑定键标识符 public static final String DEAD_LETTER_ROUTING_KEY = "x-dead-letter-routing-key"; @Bean @@ -97,4 +97,5 @@ public DirectExchange deadExchangeOrder() { public Binding bindingDeadExchange() { return BindingBuilder.bind(deadQueueOrder()).to(deadExchangeOrder()).with(deadRoutingKeyOrder); } + } diff --git a/spring-boot-example/spring-rabbit/rabbitmq-order-expired/src/main/java/com/livk/order/controller/OrderController.java b/spring-boot-example/spring-rabbit/rabbitmq-order-expired/src/main/java/com/livk/order/controller/OrderController.java index 0b8bd3cdb..512a552ac 100644 --- a/spring-boot-example/spring-rabbit/rabbitmq-order-expired/src/main/java/com/livk/order/controller/OrderController.java +++ b/spring-boot-example/spring-rabbit/rabbitmq-order-expired/src/main/java/com/livk/order/controller/OrderController.java @@ -47,7 +47,6 @@ public class OrderController { /** * 模拟提交订单 - * * @return java.lang.Object * @author nxq */ diff --git a/spring-boot-example/spring-redis/redis-caffeine/src/main/java/com/livk/caffeine/aspect/CacheInterceptor.java b/spring-boot-example/spring-redis/redis-caffeine/src/main/java/com/livk/caffeine/aspect/CacheInterceptor.java index 646c1152c..a131ef4df 100644 --- a/spring-boot-example/spring-redis/redis-caffeine/src/main/java/com/livk/caffeine/aspect/CacheInterceptor.java +++ b/spring-boot-example/spring-redis/redis-caffeine/src/main/java/com/livk/caffeine/aspect/CacheInterceptor.java @@ -72,4 +72,5 @@ protected Object invoke(MethodInvocation invocation, DoubleCache doubleCache) th private Callable call(Object obj) { return () -> obj; } + } diff --git a/spring-boot-example/spring-redis/redis-caffeine/src/main/java/com/livk/caffeine/config/CaffeineConfig.java b/spring-boot-example/spring-redis/redis-caffeine/src/main/java/com/livk/caffeine/config/CaffeineConfig.java index 3a05c271c..25b8e5cb9 100644 --- a/spring-boot-example/spring-redis/redis-caffeine/src/main/java/com/livk/caffeine/config/CaffeineConfig.java +++ b/spring-boot-example/spring-redis/redis-caffeine/src/main/java/com/livk/caffeine/config/CaffeineConfig.java @@ -49,4 +49,5 @@ public Cache caffeineCache() { public CacheManager cacheManager(CacheHandler cacheHandler) { return new RedisCaffeineManager(cacheHandler); } + } diff --git a/spring-boot-example/spring-redis/redis-caffeine/src/main/java/com/livk/caffeine/config/RedisCaffeineCache.java b/spring-boot-example/spring-redis/redis-caffeine/src/main/java/com/livk/caffeine/config/RedisCaffeineCache.java index 8124dafec..281cf048d 100644 --- a/spring-boot-example/spring-redis/redis-caffeine/src/main/java/com/livk/caffeine/config/RedisCaffeineCache.java +++ b/spring-boot-example/spring-redis/redis-caffeine/src/main/java/com/livk/caffeine/config/RedisCaffeineCache.java @@ -56,8 +56,7 @@ public CacheHandler getNativeCache() { @SuppressWarnings("unchecked") @Override public T get(Object key, Callable valueLoader) { - return (T) fromStoreValue(this.cacheHandler.readAndPut(key.toString(), - supplier(valueLoader).get())); + return (T) fromStoreValue(this.cacheHandler.readAndPut(key.toString(), supplier(valueLoader).get())); } @Override @@ -79,9 +78,11 @@ private Supplier supplier(Callable callable) { return () -> { try { return callable.call(); - } catch (Exception e) { + } + catch (Exception e) { throw new RuntimeException(e); } }; } + } diff --git a/spring-boot-example/spring-redis/redis-caffeine/src/main/java/com/livk/caffeine/config/RedisCaffeineManager.java b/spring-boot-example/spring-redis/redis-caffeine/src/main/java/com/livk/caffeine/config/RedisCaffeineManager.java index 3129cf89e..f1139bc84 100644 --- a/spring-boot-example/spring-redis/redis-caffeine/src/main/java/com/livk/caffeine/config/RedisCaffeineManager.java +++ b/spring-boot-example/spring-redis/redis-caffeine/src/main/java/com/livk/caffeine/config/RedisCaffeineManager.java @@ -51,4 +51,5 @@ private Cache createCache(String name) { public Collection getCacheNames() { return Collections.unmodifiableSet(this.cacheMap.keySet()); } + } diff --git a/spring-boot-example/spring-redis/redis-caffeine/src/main/java/com/livk/caffeine/controller/CacheController.java b/spring-boot-example/spring-redis/redis-caffeine/src/main/java/com/livk/caffeine/controller/CacheController.java index f58bfb0f1..532daa7f1 100644 --- a/spring-boot-example/spring-redis/redis-caffeine/src/main/java/com/livk/caffeine/controller/CacheController.java +++ b/spring-boot-example/spring-redis/redis-caffeine/src/main/java/com/livk/caffeine/controller/CacheController.java @@ -51,4 +51,5 @@ public String put() { public String delete() { return "over"; } + } diff --git a/spring-boot-example/spring-redis/redis-caffeine/src/main/java/com/livk/caffeine/handler/CacheHandlerAdapter.java b/spring-boot-example/spring-redis/redis-caffeine/src/main/java/com/livk/caffeine/handler/CacheHandlerAdapter.java index d9c0f21fd..20d2e5532 100644 --- a/spring-boot-example/spring-redis/redis-caffeine/src/main/java/com/livk/caffeine/handler/CacheHandlerAdapter.java +++ b/spring-boot-example/spring-redis/redis-caffeine/src/main/java/com/livk/caffeine/handler/CacheHandlerAdapter.java @@ -62,4 +62,5 @@ public void clear() { cache.invalidateAll(); redisOps.delete(keys); } + } diff --git a/spring-boot-example/spring-redis/redis-caffeine/src/main/java/com/livk/caffeine/handler/CacheWriteHandler.java b/spring-boot-example/spring-redis/redis-caffeine/src/main/java/com/livk/caffeine/handler/CacheWriteHandler.java index 135bb506b..78dfcef5c 100644 --- a/spring-boot-example/spring-redis/redis-caffeine/src/main/java/com/livk/caffeine/handler/CacheWriteHandler.java +++ b/spring-boot-example/spring-redis/redis-caffeine/src/main/java/com/livk/caffeine/handler/CacheWriteHandler.java @@ -31,4 +31,5 @@ public interface CacheWriteHandler { void delete(String key); void clear(); + } diff --git a/spring-boot-example/spring-redis/redis-caffeine/src/test/java/com/livk/caffeine/controller/CacheControllerTest.java b/spring-boot-example/spring-redis/redis-caffeine/src/test/java/com/livk/caffeine/controller/CacheControllerTest.java index 141324967..5bccd5748 100644 --- a/spring-boot-example/spring-redis/redis-caffeine/src/test/java/com/livk/caffeine/controller/CacheControllerTest.java +++ b/spring-boot-example/spring-redis/redis-caffeine/src/test/java/com/livk/caffeine/controller/CacheControllerTest.java @@ -48,27 +48,31 @@ @SpringBootTest @AutoConfigureMockMvc class CacheControllerTest { + @Autowired MockMvc mockMvc; @Autowired RedisOps redisOps; - @Test void testGet() throws Exception { Set result = new HashSet<>(); String uuid = mockMvc.perform(get("/cache")) .andExpect(status().isOk()) .andDo(print()) - .andReturn().getResponse().getContentAsString(); + .andReturn() + .getResponse() + .getContentAsString(); result.add(uuid); for (int i = 0; i < 3; i++) { String newUUID = mockMvc.perform(get("/cache")) .andExpect(status().isOk()) .andDo(print()) .andExpect(content().string(uuid)) - .andReturn().getResponse().getContentAsString(); + .andReturn() + .getResponse() + .getContentAsString(); result.add(newUUID); } assertEquals(result.size(), 1); @@ -81,13 +85,17 @@ void testPut() throws Exception { String uuid = mockMvc.perform(post("/cache")) .andExpect(status().isOk()) .andDo(print()) - .andReturn().getResponse().getContentAsString(); + .andReturn() + .getResponse() + .getContentAsString(); result.add(uuid); String newUUID = mockMvc.perform(get("/cache")) .andExpect(status().isOk()) .andDo(print()) .andExpect(content().string(uuid)) - .andReturn().getResponse().getContentAsString(); + .andReturn() + .getResponse() + .getContentAsString(); result.add(newUUID); } assertEquals(result.size(), 3); @@ -95,10 +103,7 @@ void testPut() throws Exception { @Test void testDelete() throws Exception { - mockMvc.perform(delete("/cache")) - .andExpect(status().isOk()) - .andDo(print()) - .andExpect(content().string("over")); + mockMvc.perform(delete("/cache")).andExpect(status().isOk()).andDo(print()).andExpect(content().string("over")); } @Test @@ -116,6 +121,8 @@ public void test() { assertEquals(1, keys.size()); } } + } -//Generated with love by TestMe :) Please report issues and submit feature requests at: http://weirddev.com/forum#!/testme +// Generated with love by TestMe :) Please report issues and submit feature requests at: +// http://weirddev.com/forum#!/testme diff --git a/spring-boot-example/spring-redis/redis-consumer/src/main/java/com/livk/redis/config/RedisConfig.java b/spring-boot-example/spring-redis/redis-consumer/src/main/java/com/livk/redis/config/RedisConfig.java index d3fc63bef..734c58890 100644 --- a/spring-boot-example/spring-redis/redis-consumer/src/main/java/com/livk/redis/config/RedisConfig.java +++ b/spring-boot-example/spring-redis/redis-consumer/src/main/java/com/livk/redis/config/RedisConfig.java @@ -51,14 +51,15 @@ public class RedisConfig { @Bean @SuppressWarnings("rawtypes") public ReactiveRedisMessageListenerContainer reactiveRedisMessageListenerContainer( - ReactiveRedisConnectionFactory connectionFactory) { + ReactiveRedisConnectionFactory connectionFactory) { ReactiveRedisMessageListenerContainer container = new ReactiveRedisMessageListenerContainer(connectionFactory); RedisSerializer serializer = JacksonSerializerUtils.json(LivkMessage.class); container .receive(List.of(PatternTopic.of(LivkMessage.CHANNEL)), - RedisSerializationContext.SerializationPair.fromSerializer(RedisSerializer.string()), - RedisSerializationContext.SerializationPair.fromSerializer(serializer)) - .map(ReactiveSubscription.Message::getMessage).subscribe(obj -> log.info("message:{}", obj)); + RedisSerializationContext.SerializationPair.fromSerializer(RedisSerializer.string()), + RedisSerializationContext.SerializationPair.fromSerializer(serializer)) + .map(ReactiveSubscription.Message::getMessage) + .subscribe(obj -> log.info("message:{}", obj)); return container; } diff --git a/spring-boot-example/spring-redis/redis-consumer/src/main/java/com/livk/redis/listener/LivkStreamListener.java b/spring-boot-example/spring-redis/redis-consumer/src/main/java/com/livk/redis/listener/LivkStreamListener.java index c84159ae8..d4fdf6992 100644 --- a/spring-boot-example/spring-redis/redis-consumer/src/main/java/com/livk/redis/listener/LivkStreamListener.java +++ b/spring-boot-example/spring-redis/redis-consumer/src/main/java/com/livk/redis/listener/LivkStreamListener.java @@ -45,7 +45,7 @@ @Component @RequiredArgsConstructor public class LivkStreamListener - implements StreamListener>, InitializingBean, DisposableBean { + implements StreamListener>, InitializingBean, DisposableBean { private final RedisOps redisOps; @@ -65,20 +65,25 @@ public void afterPropertiesSet() { if (groups.isEmpty()) { redisOps.opsForStream().createGroup("livk-streamKey", "livk-group"); } - } else { + } + else { redisOps.opsForStream().createGroup("livk-streamKey", "livk-group"); } - StreamMessageListenerContainer.StreamMessageListenerContainerOptions> options - = StreamMessageListenerContainer.StreamMessageListenerContainerOptions.builder().batchSize(10) + StreamMessageListenerContainer.StreamMessageListenerContainerOptions> options = StreamMessageListenerContainer.StreamMessageListenerContainerOptions + .builder() + .batchSize(10) .executor(new ThreadPoolExecutor(4, 10, 0, TimeUnit.SECONDS, new ArrayBlockingQueue<>(10))) - .errorHandler(t -> log.error("ERROR:{}", t.getMessage())).pollTimeout(Duration.ZERO) - .serializer(RedisSerializer.string()).targetType(String.class).build(); + .errorHandler(t -> log.error("ERROR:{}", t.getMessage())) + .pollTimeout(Duration.ZERO) + .serializer(RedisSerializer.string()) + .targetType(String.class) + .build(); this.listenerContainer = StreamMessageListenerContainer .create(Objects.requireNonNull(redisOps.getConnectionFactory()), options); this.listenerContainer.receive(Consumer.from("livk-group", "livk"), - StreamOffset.create("livk-streamKey", ReadOffset.lastConsumed()), this); + StreamOffset.create("livk-streamKey", ReadOffset.lastConsumed()), this); this.listenerContainer.start(); } diff --git a/spring-boot-example/spring-redis/redis-lua/src/main/java/com/livk/redis/support/LuaStock.java b/spring-boot-example/spring-redis/redis-lua/src/main/java/com/livk/redis/support/LuaStock.java index b88785a62..b61de6d82 100644 --- a/spring-boot-example/spring-redis/redis-lua/src/main/java/com/livk/redis/support/LuaStock.java +++ b/spring-boot-example/spring-redis/redis-lua/src/main/java/com/livk/redis/support/LuaStock.java @@ -45,7 +45,8 @@ public String buy(Integer num) { Assert.notNull(result, "RedisScript Result is Null!"); if (0 == result) { return "没了"; - } else if (2 == result) { + } + else if (2 == result) { return "抢到了"; } return ""; diff --git a/spring-boot-example/spring-redis/redis-provider/src/main/java/com/livk/redis/RedisBloom.java b/spring-boot-example/spring-redis/redis-provider/src/main/java/com/livk/redis/RedisBloom.java index 4434df18d..292779235 100644 --- a/spring-boot-example/spring-redis/redis-provider/src/main/java/com/livk/redis/RedisBloom.java +++ b/spring-boot-example/spring-redis/redis-provider/src/main/java/com/livk/redis/RedisBloom.java @@ -41,7 +41,7 @@ public class RedisBloom { /** * 准备自定义哈希算法需要用到的质数,因为一条数据需要hash计算5次 且5次的结果要不一样 */ - private static final int[] primeNums = new int[]{17, 19, 29, 31, 37}; + private static final int[] primeNums = new int[] { 17, 19, 29, 31, 37 }; private final ValueOperations forValue; diff --git a/spring-boot-example/spring-redis/redis-provider/src/main/java/com/livk/redis/controller/MessageController.java b/spring-boot-example/spring-redis/redis-provider/src/main/java/com/livk/redis/controller/MessageController.java index 720b34fe4..f45972c6c 100644 --- a/spring-boot-example/spring-redis/redis-provider/src/main/java/com/livk/redis/controller/MessageController.java +++ b/spring-boot-example/spring-redis/redis-provider/src/main/java/com/livk/redis/controller/MessageController.java @@ -45,7 +45,7 @@ public class MessageController { @PostMapping("/redis/{id}") public Mono send(@PathVariable("id") Long id, @RequestParam("msg") String msg, - @RequestBody Map data) { + @RequestBody Map data) { return reactiveRedisOps .convertAndSend(LivkMessage.CHANNEL, LivkMessage.of().setId(id).setMsg(msg).setData(data)) .flatMap(n -> Mono.empty()); @@ -54,27 +54,23 @@ public Mono send(@PathVariable("id") Long id, @RequestParam("msg") String @PostMapping("/redis/stream") public Mono stream() { return reactiveRedisOps.opsForStream() - .add(StreamRecords.newRecord() - .ofObject("livk-object") - .withStreamKey("livk-streamKey")) + .add(StreamRecords.newRecord().ofObject("livk-object").withStreamKey("livk-streamKey")) .flatMap(n -> Mono.empty()); } @PostMapping("/redis/hyper-log-log") public Mono add(@RequestParam Object data) { - return reactiveRedisOps.opsForHyperLogLog() - .add("log", data) - .flatMap(n -> Mono.empty()); + return reactiveRedisOps.opsForHyperLogLog().add("log", data).flatMap(n -> Mono.empty()); } @GetMapping("/redis/hyper-log-log") public Mono get() { - return reactiveRedisOps.opsForHyperLogLog() - .size("log"); + return reactiveRedisOps.opsForHyperLogLog().size("log"); } @PostMapping("person") public Mono add(@RequestBody Mono personMono) { return personMono.doOnNext(personRepository::save).then(); } + } diff --git a/spring-boot-example/spring-redis/redis-provider/src/main/java/com/livk/redis/entity/Person.java b/spring-boot-example/spring-redis/redis-provider/src/main/java/com/livk/redis/entity/Person.java index c577e3e8d..140c8b213 100644 --- a/spring-boot-example/spring-redis/redis-provider/src/main/java/com/livk/redis/entity/Person.java +++ b/spring-boot-example/spring-redis/redis-provider/src/main/java/com/livk/redis/entity/Person.java @@ -31,8 +31,12 @@ @Data @RedisHash("people") public class Person { + @Id private String id; + private String username; + private String address; + } diff --git a/spring-boot-example/spring-redis/redis-provider/src/main/java/com/livk/redis/repository/PersonRepository.java b/spring-boot-example/spring-redis/redis-provider/src/main/java/com/livk/redis/repository/PersonRepository.java index 7258563c8..159502484 100644 --- a/spring-boot-example/spring-redis/redis-provider/src/main/java/com/livk/redis/repository/PersonRepository.java +++ b/spring-boot-example/spring-redis/redis-provider/src/main/java/com/livk/redis/repository/PersonRepository.java @@ -30,4 +30,5 @@ */ @Repository public interface PersonRepository extends CrudRepository { + } diff --git a/spring-boot-example/spring-redis/redis-repeated-submit/src/main/java/com/livk/redis/submit/AutoRepeatedSubmitInterceptor.java b/spring-boot-example/spring-redis/redis-repeated-submit/src/main/java/com/livk/redis/submit/AutoRepeatedSubmitInterceptor.java index 3cfad8014..22498b7c4 100644 --- a/spring-boot-example/spring-redis/redis-repeated-submit/src/main/java/com/livk/redis/submit/AutoRepeatedSubmitInterceptor.java +++ b/spring-boot-example/spring-redis/redis-repeated-submit/src/main/java/com/livk/redis/submit/AutoRepeatedSubmitInterceptor.java @@ -38,9 +38,8 @@ public class AutoRepeatedSubmitInterceptor implements HandlerInterceptor { @Override - public boolean preHandle(@NonNull HttpServletRequest request, - @NonNull HttpServletResponse response, - @NonNull Object handler) { + public boolean preHandle(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, + @NonNull Object handler) { if (handler instanceof HandlerMethod handlerMethod) { AutoRepeatedSubmit methodAnnotation = handlerMethod.getMethodAnnotation(AutoRepeatedSubmit.class); if (methodAnnotation != null) { @@ -51,15 +50,18 @@ public boolean preHandle(@NonNull HttpServletRequest request, if (RedisSupport.exists(token)) { WebUtils.outJson(response, "重复提交3s后重试"); return false; - } else { + } + else { RedisSupport.setEx(token, true, 3L); return true; } - } else { + } + else { WebUtils.outJson(response, "重复提交3s后重试"); return false; } - } finally { + } + finally { LockSupport.unlock(); } } @@ -67,7 +69,8 @@ public boolean preHandle(@NonNull HttpServletRequest request, return false; } } - //必须返回true,否则会被拦截一切请求 + // 必须返回true,否则会被拦截一切请求 return true; } + } diff --git a/spring-boot-example/spring-redis/redis-repeated-submit/src/main/java/com/livk/redis/submit/RepeatedSubmit.java b/spring-boot-example/spring-redis/redis-repeated-submit/src/main/java/com/livk/redis/submit/RepeatedSubmit.java index af1cccb07..50499f627 100644 --- a/spring-boot-example/spring-redis/redis-repeated-submit/src/main/java/com/livk/redis/submit/RepeatedSubmit.java +++ b/spring-boot-example/spring-redis/redis-repeated-submit/src/main/java/com/livk/redis/submit/RepeatedSubmit.java @@ -25,7 +25,9 @@ */ @SpringBootApplication public class RepeatedSubmit { + public static void main(String[] args) { SpringLauncher.run(args); } + } diff --git a/spring-boot-example/spring-redis/redis-repeated-submit/src/main/java/com/livk/redis/submit/WebmvcConfig.java b/spring-boot-example/spring-redis/redis-repeated-submit/src/main/java/com/livk/redis/submit/WebmvcConfig.java index 36884ebce..0fb306b03 100644 --- a/spring-boot-example/spring-redis/redis-repeated-submit/src/main/java/com/livk/redis/submit/WebmvcConfig.java +++ b/spring-boot-example/spring-redis/redis-repeated-submit/src/main/java/com/livk/redis/submit/WebmvcConfig.java @@ -33,4 +33,5 @@ public class WebmvcConfig implements WebMvcConfigurer { public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new AutoRepeatedSubmitInterceptor()); } + } diff --git a/spring-boot-example/spring-redis/redis-repeated-submit/src/main/java/com/livk/redis/submit/annotation/AutoRepeatedSubmit.java b/spring-boot-example/spring-redis/redis-repeated-submit/src/main/java/com/livk/redis/submit/annotation/AutoRepeatedSubmit.java index 8cf409e9e..78327a18c 100644 --- a/spring-boot-example/spring-redis/redis-repeated-submit/src/main/java/com/livk/redis/submit/annotation/AutoRepeatedSubmit.java +++ b/spring-boot-example/spring-redis/redis-repeated-submit/src/main/java/com/livk/redis/submit/annotation/AutoRepeatedSubmit.java @@ -26,7 +26,7 @@ * @author livk */ -@Target({ElementType.METHOD}) +@Target({ ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) public @interface AutoRepeatedSubmit { diff --git a/spring-boot-example/spring-redis/redis-repeated-submit/src/main/java/com/livk/redis/submit/controller/JsonController.java b/spring-boot-example/spring-redis/redis-repeated-submit/src/main/java/com/livk/redis/submit/controller/JsonController.java index 54a07e14f..f93aab228 100644 --- a/spring-boot-example/spring-redis/redis-repeated-submit/src/main/java/com/livk/redis/submit/controller/JsonController.java +++ b/spring-boot-example/spring-redis/redis-repeated-submit/src/main/java/com/livk/redis/submit/controller/JsonController.java @@ -36,4 +36,5 @@ public class JsonController { public HttpEntity get() { return ResponseEntity.ok("json"); } + } diff --git a/spring-boot-example/spring-redis/redis-repeated-submit/src/main/java/com/livk/redis/submit/support/LockSupport.java b/spring-boot-example/spring-redis/redis-repeated-submit/src/main/java/com/livk/redis/submit/support/LockSupport.java index 065fac008..040af0625 100644 --- a/spring-boot-example/spring-redis/redis-repeated-submit/src/main/java/com/livk/redis/submit/support/LockSupport.java +++ b/spring-boot-example/spring-redis/redis-repeated-submit/src/main/java/com/livk/redis/submit/support/LockSupport.java @@ -42,4 +42,5 @@ public boolean tryLock(LockType type, String key, long leaseTime, long waitTime, public void unlock() { LOCK.unlock(); } + } diff --git a/spring-boot-example/spring-redis/redis-repeated-submit/src/main/java/com/livk/redis/submit/support/RedisSupport.java b/spring-boot-example/spring-redis/redis-repeated-submit/src/main/java/com/livk/redis/submit/support/RedisSupport.java index 110ecb5d3..8ca4a80c0 100644 --- a/spring-boot-example/spring-redis/redis-repeated-submit/src/main/java/com/livk/redis/submit/support/RedisSupport.java +++ b/spring-boot-example/spring-redis/redis-repeated-submit/src/main/java/com/livk/redis/submit/support/RedisSupport.java @@ -41,26 +41,23 @@ public class RedisSupport { OPERATIONS = REDIS_OPS.opsForValue(); } - /** * 写入缓存设置时效时间 - * - * @param key the key - * @param value the value + * @param key the key + * @param value the value * @param expireTime the expire time */ public void setEx(String key, Object value, Long expireTime) { OPERATIONS.set(key, value, expireTime, TimeUnit.SECONDS); } - /** * 判断缓存中是否有对应的value - * * @param key the key * @return boolean boolean */ public boolean exists(String key) { return Boolean.TRUE.equals(REDIS_OPS.hasKey(key)); } + } diff --git a/spring-boot-example/spring-redis/redisson-order-expired/src/main/java/com/livk/redisson/order/OrderExpiredExample.java b/spring-boot-example/spring-redis/redisson-order-expired/src/main/java/com/livk/redisson/order/OrderExpiredExample.java index a59250487..b3a8a3625 100644 --- a/spring-boot-example/spring-redis/redisson-order-expired/src/main/java/com/livk/redisson/order/OrderExpiredExample.java +++ b/spring-boot-example/spring-redis/redisson-order-expired/src/main/java/com/livk/redisson/order/OrderExpiredExample.java @@ -29,7 +29,9 @@ */ @SpringBootApplication public class OrderExpiredExample { + public static void main(String[] args) { SpringLauncher.run(args); } + } diff --git a/spring-boot-example/spring-redis/redisson-order-expired/src/main/java/com/livk/redisson/order/OrderQueueConsumer.java b/spring-boot-example/spring-redis/redisson-order-expired/src/main/java/com/livk/redisson/order/OrderQueueConsumer.java index 0d0a08e1c..4dcd39846 100644 --- a/spring-boot-example/spring-redis/redisson-order-expired/src/main/java/com/livk/redisson/order/OrderQueueConsumer.java +++ b/spring-boot-example/spring-redis/redisson-order-expired/src/main/java/com/livk/redisson/order/OrderQueueConsumer.java @@ -52,8 +52,10 @@ public void run() { while (true) { try { Employer employer = orderQueue.take(); - log.info("订单取消时间:{} ==订单生成时间:{}", DateUtils.format(LocalDateTime.now(), DateUtils.HMS), employer.getPutTime()); - } catch (InterruptedException e) { + log.info("订单取消时间:{} ==订单生成时间:{}", DateUtils.format(LocalDateTime.now(), DateUtils.HMS), + employer.getPutTime()); + } + catch (InterruptedException e) { throw new RuntimeException(e); } } diff --git a/spring-boot-example/spring-redis/redisson-order-expired/src/main/java/com/livk/redisson/order/controller/OrderController.java b/spring-boot-example/spring-redis/redisson-order-expired/src/main/java/com/livk/redisson/order/controller/OrderController.java index dc9f37922..b0a1e6481 100644 --- a/spring-boot-example/spring-redis/redisson-order-expired/src/main/java/com/livk/redisson/order/controller/OrderController.java +++ b/spring-boot-example/spring-redis/redisson-order-expired/src/main/java/com/livk/redisson/order/controller/OrderController.java @@ -57,9 +57,9 @@ public void create() throws InterruptedException { } } - @Override public void destroy() { delayedQueue.destroy(); } + } diff --git a/spring-boot-example/spring-redis/redisson-order-expired/src/main/java/com/livk/redisson/order/entity/Employer.java b/spring-boot-example/spring-redis/redisson-order-expired/src/main/java/com/livk/redisson/order/entity/Employer.java index da0d256b9..212c14c2f 100644 --- a/spring-boot-example/spring-redis/redisson-order-expired/src/main/java/com/livk/redisson/order/entity/Employer.java +++ b/spring-boot-example/spring-redis/redisson-order-expired/src/main/java/com/livk/redisson/order/entity/Employer.java @@ -35,13 +35,19 @@ @NoArgsConstructor @AllArgsConstructor public class Employer { + private String name; + private int age; + private String wife; + private Double salary; + private String putTime; public void setPutTime() { this.putTime = DateUtils.format(LocalDateTime.now(), DateUtils.HMS); } + } diff --git a/spring-boot-example/spring-rest-doc/src/main/java/com/livk/doc/DocController.java b/spring-boot-example/spring-rest-doc/src/main/java/com/livk/doc/DocController.java index a9fcbae0f..3c26753fd 100644 --- a/spring-boot-example/spring-rest-doc/src/main/java/com/livk/doc/DocController.java +++ b/spring-boot-example/spring-rest-doc/src/main/java/com/livk/doc/DocController.java @@ -50,4 +50,5 @@ public HttpEntity get(@RequestParam String name) { public HttpEntity post(@RequestBody Map data) throws JsonProcessingException { return ResponseEntity.ok(objectMapper.readTree(objectMapper.writeValueAsString(data))); } + } diff --git a/spring-boot-example/spring-rest-doc/src/main/java/com/livk/doc/RestDocApp.java b/spring-boot-example/spring-rest-doc/src/main/java/com/livk/doc/RestDocApp.java index 4084c1589..80b55de1d 100644 --- a/spring-boot-example/spring-rest-doc/src/main/java/com/livk/doc/RestDocApp.java +++ b/spring-boot-example/spring-rest-doc/src/main/java/com/livk/doc/RestDocApp.java @@ -29,7 +29,9 @@ */ @SpringBootApplication public class RestDocApp { + public static void main(String[] args) { SpringLauncher.run(args); } + } diff --git a/spring-boot-example/spring-rest-doc/src/test/java/com/livk/doc/DocControllerTest.java b/spring-boot-example/spring-rest-doc/src/test/java/com/livk/doc/DocControllerTest.java index beb527775..512880fce 100644 --- a/spring-boot-example/spring-rest-doc/src/test/java/com/livk/doc/DocControllerTest.java +++ b/spring-boot-example/spring-rest-doc/src/test/java/com/livk/doc/DocControllerTest.java @@ -47,7 +47,7 @@ * @author livk */ @WebMvcTest -@ExtendWith({SpringExtension.class, RestDocumentationExtension.class}) +@ExtendWith({ SpringExtension.class, RestDocumentationExtension.class }) class DocControllerTest { MockMvc mockMvc; @@ -56,8 +56,7 @@ class DocControllerTest { ObjectMapper mapper; @BeforeEach - public void setMockMvc(WebApplicationContext webApplicationContext, - RestDocumentationContextProvider provider) { + public void setMockMvc(WebApplicationContext webApplicationContext, RestDocumentationContextProvider provider) { this.mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext) .apply(MockMvcRestDocumentation.documentationConfiguration(provider)) .build(); @@ -65,8 +64,7 @@ public void setMockMvc(WebApplicationContext webApplicationContext, @Test void testGet() throws Exception { - mockMvc.perform(get("/doc") - .param("name", "world")) + mockMvc.perform(get("/doc").param("name", "world")) .andExpect(status().isOk()) .andExpect(content().string("hello world")) .andDo(document("get")); @@ -75,12 +73,11 @@ void testGet() throws Exception { @Test void testPost() throws Exception { Map map = Map.of("username", "livk", "password", "123456"); - mockMvc.perform(post("/doc") - .contentType(MediaType.APPLICATION_JSON) - .content(mapper.writeValueAsString(map))) + mockMvc.perform(post("/doc").contentType(MediaType.APPLICATION_JSON).content(mapper.writeValueAsString(map))) .andExpect(status().isOk()) .andExpect(jsonPath("$.username").value("livk")) .andExpect(jsonPath("$.password").value("123456")) .andDo(document("post")); } + } diff --git a/spring-boot-example/spring-retry/src/test/java/com/livk/retry/controller/RetryControllerTest.java b/spring-boot-example/spring-retry/src/test/java/com/livk/retry/controller/RetryControllerTest.java index 50cbf72c0..296440ea5 100644 --- a/spring-boot-example/spring-retry/src/test/java/com/livk/retry/controller/RetryControllerTest.java +++ b/spring-boot-example/spring-retry/src/test/java/com/livk/retry/controller/RetryControllerTest.java @@ -49,4 +49,5 @@ void retryTest() throws Exception { .andDo(print()) .andExpect(content().string("recover SUC")); } + } diff --git a/spring-boot-example/spring-rocket/rocket-commons/src/main/java/com/livk/rocket/constant/RocketConstant.java b/spring-boot-example/spring-rocket/rocket-commons/src/main/java/com/livk/rocket/constant/RocketConstant.java index 304d31acd..1f4af86fd 100644 --- a/spring-boot-example/spring-rocket/rocket-commons/src/main/java/com/livk/rocket/constant/RocketConstant.java +++ b/spring-boot-example/spring-rocket/rocket-commons/src/main/java/com/livk/rocket/constant/RocketConstant.java @@ -23,11 +23,13 @@ public interface RocketConstant { String LIVK_MESSAGE_TOPIC = "livk-message-topic"; + String LIVK_EXT_MESSAGE_TOPIC = "livk-ext-message-topic"; String LIVK_MESSAGE_QUEUE_SELECTOR_KEY = "livk-message_queue_selector_key"; String LIVK_MESSAGE_ORDERLY_TOPIC = "livk-message-orderly-topic"; + String LIVK_EXT_MESSAGE_ORDERLY_TOPIC = "livk-ext-message-orderly-topic"; } diff --git a/spring-boot-example/spring-rocket/rocket-consumer/src/main/java/com/livk/rocket/consumer/RocketConsumerApp.java b/spring-boot-example/spring-rocket/rocket-consumer/src/main/java/com/livk/rocket/consumer/RocketConsumerApp.java index cda02c882..ebff33676 100644 --- a/spring-boot-example/spring-rocket/rocket-consumer/src/main/java/com/livk/rocket/consumer/RocketConsumerApp.java +++ b/spring-boot-example/spring-rocket/rocket-consumer/src/main/java/com/livk/rocket/consumer/RocketConsumerApp.java @@ -25,7 +25,9 @@ */ @SpringBootApplication public class RocketConsumerApp { + public static void main(String[] args) { SpringLauncher.run(args); } + } diff --git a/spring-boot-example/spring-rocket/rocket-consumer/src/main/java/com/livk/rocket/consumer/listener/TestExtMessageListener.java b/spring-boot-example/spring-rocket/rocket-consumer/src/main/java/com/livk/rocket/consumer/listener/TestExtMessageListener.java index 55304b60e..95706710b 100644 --- a/spring-boot-example/spring-rocket/rocket-consumer/src/main/java/com/livk/rocket/consumer/listener/TestExtMessageListener.java +++ b/spring-boot-example/spring-rocket/rocket-consumer/src/main/java/com/livk/rocket/consumer/listener/TestExtMessageListener.java @@ -42,4 +42,5 @@ public void onMessage(RocketDTO dto) { } log.info("ext rocketMQ receive message:{}", JsonMapperUtils.writeValueAsString(dto)); } + } diff --git a/spring-boot-example/spring-rocket/rocket-consumer/src/main/java/com/livk/rocket/consumer/listener/TestExtMessageOrderlyListener.java b/spring-boot-example/spring-rocket/rocket-consumer/src/main/java/com/livk/rocket/consumer/listener/TestExtMessageOrderlyListener.java index 58a6f48dd..b1af90094 100644 --- a/spring-boot-example/spring-rocket/rocket-consumer/src/main/java/com/livk/rocket/consumer/listener/TestExtMessageOrderlyListener.java +++ b/spring-boot-example/spring-rocket/rocket-consumer/src/main/java/com/livk/rocket/consumer/listener/TestExtMessageOrderlyListener.java @@ -31,11 +31,13 @@ */ @Slf4j @Component -@RocketMQMessageListener(consumerGroup = "livk-consumer-group-4", topic = RocketConstant.LIVK_EXT_MESSAGE_ORDERLY_TOPIC, consumeMode = ConsumeMode.ORDERLY) +@RocketMQMessageListener(consumerGroup = "livk-consumer-group-4", topic = RocketConstant.LIVK_EXT_MESSAGE_ORDERLY_TOPIC, + consumeMode = ConsumeMode.ORDERLY) public class TestExtMessageOrderlyListener implements RocketMQListener { @Override public void onMessage(RocketDTO dto) { log.info("orderly ext rocketMQ receive message:{}", JsonMapperUtils.writeValueAsString(dto)); } + } diff --git a/spring-boot-example/spring-rocket/rocket-consumer/src/main/java/com/livk/rocket/consumer/listener/TestMessageListener.java b/spring-boot-example/spring-rocket/rocket-consumer/src/main/java/com/livk/rocket/consumer/listener/TestMessageListener.java index 6e1fa2b6b..37679c03c 100644 --- a/spring-boot-example/spring-rocket/rocket-consumer/src/main/java/com/livk/rocket/consumer/listener/TestMessageListener.java +++ b/spring-boot-example/spring-rocket/rocket-consumer/src/main/java/com/livk/rocket/consumer/listener/TestMessageListener.java @@ -42,4 +42,5 @@ public void onMessage(RocketDTO dto) { } log.info("rocketMQ receive message:{}", JsonMapperUtils.writeValueAsString(dto)); } + } diff --git a/spring-boot-example/spring-rocket/rocket-consumer/src/main/java/com/livk/rocket/consumer/listener/TestMessageOrderlyListener.java b/spring-boot-example/spring-rocket/rocket-consumer/src/main/java/com/livk/rocket/consumer/listener/TestMessageOrderlyListener.java index e01f342d0..279e41773 100644 --- a/spring-boot-example/spring-rocket/rocket-consumer/src/main/java/com/livk/rocket/consumer/listener/TestMessageOrderlyListener.java +++ b/spring-boot-example/spring-rocket/rocket-consumer/src/main/java/com/livk/rocket/consumer/listener/TestMessageOrderlyListener.java @@ -31,11 +31,13 @@ */ @Slf4j @Component -@RocketMQMessageListener(consumerGroup = "livk-consumer-group-3", topic = RocketConstant.LIVK_MESSAGE_ORDERLY_TOPIC, consumeMode = ConsumeMode.ORDERLY) +@RocketMQMessageListener(consumerGroup = "livk-consumer-group-3", topic = RocketConstant.LIVK_MESSAGE_ORDERLY_TOPIC, + consumeMode = ConsumeMode.ORDERLY) public class TestMessageOrderlyListener implements RocketMQListener { @Override public void onMessage(RocketDTO dto) { log.info("orderly rocketMQ receive message:{}", JsonMapperUtils.writeValueAsString(dto)); } + } diff --git a/spring-boot-example/spring-rocket/rocket-producer/src/main/java/com/livk/rocket/producer/config/ExtRocketMQTemplate.java b/spring-boot-example/spring-rocket/rocket-producer/src/main/java/com/livk/rocket/producer/config/ExtRocketMQTemplate.java index e9d65a874..339a2c459 100644 --- a/spring-boot-example/spring-rocket/rocket-producer/src/main/java/com/livk/rocket/producer/config/ExtRocketMQTemplate.java +++ b/spring-boot-example/spring-rocket/rocket-producer/src/main/java/com/livk/rocket/producer/config/ExtRocketMQTemplate.java @@ -25,11 +25,9 @@ * * @author laokou */ -@ExtRocketMQTemplateConfiguration( - group = "${rocketmq.ext.producer.group:livk-ext-producer-group}", - nameServer = "${rocketmq.ext.name-server:laokou.org:9876}", - retryTimesWhenSendFailed = 2, - retryTimesWhenSendAsyncFailed = 2 -) +@ExtRocketMQTemplateConfiguration(group = "${rocketmq.ext.producer.group:livk-ext-producer-group}", + nameServer = "${rocketmq.ext.name-server:laokou.org:9876}", retryTimesWhenSendFailed = 2, + retryTimesWhenSendAsyncFailed = 2) public class ExtRocketMQTemplate extends RocketMQTemplate { + } diff --git a/spring-boot-example/spring-rocket/rocket-producer/src/main/java/com/livk/rocket/producer/controller/ExtRocketProducer.java b/spring-boot-example/spring-rocket/rocket-producer/src/main/java/com/livk/rocket/producer/controller/ExtRocketProducer.java index d9ff3a617..37b04a014 100644 --- a/spring-boot-example/spring-rocket/rocket-producer/src/main/java/com/livk/rocket/producer/controller/ExtRocketProducer.java +++ b/spring-boot-example/spring-rocket/rocket-producer/src/main/java/com/livk/rocket/producer/controller/ExtRocketProducer.java @@ -40,14 +40,12 @@ @RequiredArgsConstructor public class ExtRocketProducer { - private final RocketMQTemplate extRocketMQTemplate; /** * rocketmq消息>同步发送 - * * @param topic topic - * @param dto dto + * @param dto dto */ @PostMapping("/send/{topic}") public void sendMessage(@PathVariable("topic") String topic, @RequestBody RocketDTO dto) { @@ -56,9 +54,8 @@ public void sendMessage(@PathVariable("topic") String topic, @RequestBody Rocket /** * rocketmq消息>异步发送 - * * @param topic topic - * @param dto dto + * @param dto dto */ @PostMapping("/sendAsync/{topic}") public void sendAsyncMessage(@PathVariable("topic") String topic, @RequestBody RocketDTO dto) { @@ -77,34 +74,33 @@ public void onException(Throwable throwable) { /** * rocketmq消息>单向发送 - * * @param topic topic - * @param dto dto + * @param dto dto */ @PostMapping("/sendOne/{topic}") public void sendOneMessage(@PathVariable("topic") String topic, @RequestBody RocketDTO dto) { - //单向发送,只负责发送消息,不会触发回调函数,即发送消息请求不等待 - //适用于耗时短,但对可靠性不高的场景,如日志收集 + // 单向发送,只负责发送消息,不会触发回调函数,即发送消息请求不等待 + // 适用于耗时短,但对可靠性不高的场景,如日志收集 extRocketMQTemplate.sendOneWay(topic, dto); } /** * 事务消息 - * * @param topic the topic - * @param dto the dto + * @param dto the dto */ @PostMapping("/sendTransaction/{topic}") public void sendTransactionMessage(@PathVariable("topic") String topic, @RequestBody RocketDTO dto) { - Message message = MessageBuilder.withPayload(dto).setHeader(RocketMQHeaders.TRANSACTION_ID, "3").build(); + Message message = MessageBuilder.withPayload(dto) + .setHeader(RocketMQHeaders.TRANSACTION_ID, "3") + .build(); extRocketMQTemplate.sendMessageInTransaction(topic, message, dto); } /** * 延迟消息 - * * @param topic the topic - * @param dto the dto + * @param dto the dto */ @PostMapping("/sendDelay/{topic}") public void sendDelay(@PathVariable("topic") String topic, @RequestBody RocketDTO dto) { @@ -113,9 +109,8 @@ public void sendDelay(@PathVariable("topic") String topic, @RequestBody RocketDT /** * rocketmq消息>同步发送顺序消息 - * * @param topic topic - * @param dto dto + * @param dto dto */ @PostMapping("/sendOrderly/{topic}") public void sendMessageOrderly(@PathVariable("topic") String topic, @RequestBody RocketDTO dto) { @@ -124,35 +119,34 @@ public void sendMessageOrderly(@PathVariable("topic") String topic, @RequestBody /** * rocketmq消息>异步发送顺序消息 - * * @param topic topic - * @param dto dto + * @param dto dto */ @PostMapping("/sendAsyncOrderly/{topic}") public void sendAsyncMessageOrderly(@PathVariable("topic") String topic, @RequestBody RocketDTO dto) { - extRocketMQTemplate.asyncSendOrderly(topic, dto, RocketConstant.LIVK_MESSAGE_QUEUE_SELECTOR_KEY, new SendCallback() { - @Override - public void onSuccess(SendResult sendResult) { - log.info("发送成功"); - } - - @Override - public void onException(Throwable throwable) { - log.error("报错信息:{}", throwable.getMessage()); - } - }); + extRocketMQTemplate.asyncSendOrderly(topic, dto, RocketConstant.LIVK_MESSAGE_QUEUE_SELECTOR_KEY, + new SendCallback() { + @Override + public void onSuccess(SendResult sendResult) { + log.info("发送成功"); + } + + @Override + public void onException(Throwable throwable) { + log.error("报错信息:{}", throwable.getMessage()); + } + }); } /** * rocketmq消息>单向发送顺序消息 - * * @param topic topic - * @param dto dto + * @param dto dto */ @PostMapping("/sendOneOrderly/{topic}") public void sendOneMessageOrderly(@PathVariable("topic") String topic, @RequestBody RocketDTO dto) { - //单向发送,只负责发送消息,不会触发回调函数,即发送消息请求不等待 - //适用于耗时短,但对可靠性不高的场景,如日志收集 + // 单向发送,只负责发送消息,不会触发回调函数,即发送消息请求不等待 + // 适用于耗时短,但对可靠性不高的场景,如日志收集 extRocketMQTemplate.sendOneWayOrderly(topic, dto, RocketConstant.LIVK_MESSAGE_QUEUE_SELECTOR_KEY); } diff --git a/spring-boot-example/spring-rocket/rocket-producer/src/main/java/com/livk/rocket/producer/controller/RocketProducer.java b/spring-boot-example/spring-rocket/rocket-producer/src/main/java/com/livk/rocket/producer/controller/RocketProducer.java index a03b48e31..3fb972ce3 100644 --- a/spring-boot-example/spring-rocket/rocket-producer/src/main/java/com/livk/rocket/producer/controller/RocketProducer.java +++ b/spring-boot-example/spring-rocket/rocket-producer/src/main/java/com/livk/rocket/producer/controller/RocketProducer.java @@ -44,9 +44,8 @@ public class RocketProducer { /** * rocketmq消息>同步发送 - * * @param topic topic - * @param dto dto + * @param dto dto */ @PostMapping("/send/{topic}") public void sendMessage(@PathVariable("topic") String topic, @RequestBody RocketDTO dto) { @@ -55,9 +54,8 @@ public void sendMessage(@PathVariable("topic") String topic, @RequestBody Rocket /** * rocketmq消息>异步发送 - * * @param topic topic - * @param dto dto + * @param dto dto */ @PostMapping("/sendAsync/{topic}") public void sendAsyncMessage(@PathVariable("topic") String topic, @RequestBody RocketDTO dto) { @@ -76,34 +74,33 @@ public void onException(Throwable throwable) { /** * rocketmq消息>单向发送 - * * @param topic topic - * @param dto dto + * @param dto dto */ @PostMapping("/sendOne/{topic}") public void sendOneMessage(@PathVariable("topic") String topic, @RequestBody RocketDTO dto) { - //单向发送,只负责发送消息,不会触发回调函数,即发送消息请求不等待 - //适用于耗时短,但对可靠性不高的场景,如日志收集 + // 单向发送,只负责发送消息,不会触发回调函数,即发送消息请求不等待 + // 适用于耗时短,但对可靠性不高的场景,如日志收集 rocketMQTemplate.sendOneWay(topic, dto); } /** * 事务消息 - * * @param topic the topic - * @param dto the dto + * @param dto the dto */ @PostMapping("/sendTransaction/{topic}") public void sendTransactionMessage(@PathVariable("topic") String topic, @RequestBody RocketDTO dto) { - Message message = MessageBuilder.withPayload(dto).setHeader(RocketMQHeaders.TRANSACTION_ID, "3").build(); + Message message = MessageBuilder.withPayload(dto) + .setHeader(RocketMQHeaders.TRANSACTION_ID, "3") + .build(); rocketMQTemplate.sendMessageInTransaction(topic, message, dto); } /** * 延迟消息 - * * @param topic the topic - * @param dto the dto + * @param dto the dto */ @PostMapping("/sendDelay/{topic}") public void sendDelay(@PathVariable("topic") String topic, @RequestBody RocketDTO dto) { @@ -113,9 +110,8 @@ public void sendDelay(@PathVariable("topic") String topic, @RequestBody RocketDT /** * rocketmq消息>同步发送顺序消息 - * * @param topic topic - * @param dto dto + * @param dto dto */ @PostMapping("/sendOrderly/{topic}") public void sendMessageOrderly(@PathVariable("topic") String topic, @RequestBody RocketDTO dto) { @@ -124,35 +120,34 @@ public void sendMessageOrderly(@PathVariable("topic") String topic, @RequestBody /** * rocketmq消息>异步发送顺序消息 - * * @param topic topic - * @param dto dto + * @param dto dto */ @PostMapping("/sendAsyncOrderly/{topic}") public void sendAsyncMessageOrderly(@PathVariable("topic") String topic, @RequestBody RocketDTO dto) { - rocketMQTemplate.asyncSendOrderly(topic, dto, RocketConstant.LIVK_MESSAGE_QUEUE_SELECTOR_KEY, new SendCallback() { - @Override - public void onSuccess(SendResult sendResult) { - log.info("发送成功"); - } + rocketMQTemplate.asyncSendOrderly(topic, dto, RocketConstant.LIVK_MESSAGE_QUEUE_SELECTOR_KEY, + new SendCallback() { + @Override + public void onSuccess(SendResult sendResult) { + log.info("发送成功"); + } - @Override - public void onException(Throwable throwable) { - log.error("报错信息:{}", throwable.getMessage()); - } - }); + @Override + public void onException(Throwable throwable) { + log.error("报错信息:{}", throwable.getMessage()); + } + }); } /** * rocketmq消息>单向发送顺序消息 - * * @param topic topic - * @param dto dto + * @param dto dto */ @PostMapping("/sendOneOrderly/{topic}") public void sendOneMessageOrderly(@PathVariable("topic") String topic, @RequestBody RocketDTO dto) { - //单向发送,只负责发送消息,不会触发回调函数,即发送消息请求不等待 - //适用于耗时短,但对可靠性不高的场景,如日志收集 + // 单向发送,只负责发送消息,不会触发回调函数,即发送消息请求不等待 + // 适用于耗时短,但对可靠性不高的场景,如日志收集 rocketMQTemplate.sendOneWayOrderly(topic, dto, RocketConstant.LIVK_MESSAGE_QUEUE_SELECTOR_KEY); } diff --git a/spring-boot-example/spring-rocket/rocket-producer/src/main/java/com/livk/rocket/producer/listener/TestExtTxListener.java b/spring-boot-example/spring-rocket/rocket-producer/src/main/java/com/livk/rocket/producer/listener/TestExtTxListener.java index 658ca381c..4c4b0c90b 100644 --- a/spring-boot-example/spring-rocket/rocket-producer/src/main/java/com/livk/rocket/producer/listener/TestExtTxListener.java +++ b/spring-boot-example/spring-rocket/rocket-producer/src/main/java/com/livk/rocket/producer/listener/TestExtTxListener.java @@ -36,7 +36,6 @@ public class TestExtTxListener implements RocketMQLocalTransactionListener { /** * 监听发送half消息,执行本地事务 - * * @param msg * @param arg * @return @@ -63,7 +62,6 @@ public RocketMQLocalTransactionState executeLocalTransaction(Message msg, Object /** * 本地事务检查,检查本地事务是否成功 - * * @param msg * @return */ diff --git a/spring-boot-example/spring-rocket/rocket-producer/src/main/java/com/livk/rocket/producer/listener/TestTxListener.java b/spring-boot-example/spring-rocket/rocket-producer/src/main/java/com/livk/rocket/producer/listener/TestTxListener.java index 77b3e2301..f0a84ed66 100644 --- a/spring-boot-example/spring-rocket/rocket-producer/src/main/java/com/livk/rocket/producer/listener/TestTxListener.java +++ b/spring-boot-example/spring-rocket/rocket-producer/src/main/java/com/livk/rocket/producer/listener/TestTxListener.java @@ -36,7 +36,6 @@ public class TestTxListener implements RocketMQLocalTransactionListener { /** * 监听发送half消息,执行本地事务 - * * @param msg * @param arg * @return @@ -63,7 +62,6 @@ public RocketMQLocalTransactionState executeLocalTransaction(Message msg, Object /** * 本地事务检查,检查本地事务是否成功 - * * @param msg * @return */ diff --git a/spring-boot-example/spring-rocket/rocket-producer/src/test/java/com/livk/rocket/producer/controller/ExtRocketProducerTest.java b/spring-boot-example/spring-rocket/rocket-producer/src/test/java/com/livk/rocket/producer/controller/ExtRocketProducerTest.java index bb1c016f3..480276c58 100644 --- a/spring-boot-example/spring-rocket/rocket-producer/src/test/java/com/livk/rocket/producer/controller/ExtRocketProducerTest.java +++ b/spring-boot-example/spring-rocket/rocket-producer/src/test/java/com/livk/rocket/producer/controller/ExtRocketProducerTest.java @@ -54,10 +54,10 @@ public void init() { dto.setBody(msg); } - @Test void sendMessage() throws Exception { - mockMvc.perform(post("/api/ext/send/{topic}", RocketConstant.LIVK_EXT_MESSAGE_TOPIC) + mockMvc + .perform(post("/api/ext/send/{topic}", RocketConstant.LIVK_EXT_MESSAGE_TOPIC) .contentType(MediaType.APPLICATION_JSON) .content(JsonMapperUtils.writeValueAsString(dto))) .andExpect(status().isOk()) @@ -66,7 +66,8 @@ void sendMessage() throws Exception { @Test void sendAsyncMessage() throws Exception { - mockMvc.perform(post("/api/ext/sendAsync/{topic}", RocketConstant.LIVK_EXT_MESSAGE_TOPIC) + mockMvc + .perform(post("/api/ext/sendAsync/{topic}", RocketConstant.LIVK_EXT_MESSAGE_TOPIC) .contentType(MediaType.APPLICATION_JSON) .content(JsonMapperUtils.writeValueAsString(dto))) .andExpect(status().isOk()) @@ -75,7 +76,8 @@ void sendAsyncMessage() throws Exception { @Test void sendOneMessage() throws Exception { - mockMvc.perform(post("/api/ext/sendOne/{topic}", RocketConstant.LIVK_EXT_MESSAGE_TOPIC) + mockMvc + .perform(post("/api/ext/sendOne/{topic}", RocketConstant.LIVK_EXT_MESSAGE_TOPIC) .contentType(MediaType.APPLICATION_JSON) .content(JsonMapperUtils.writeValueAsString(dto))) .andExpect(status().isOk()) @@ -84,7 +86,8 @@ void sendOneMessage() throws Exception { @Test void sendTransactionMessage() throws Exception { - mockMvc.perform(post("/api/ext/sendTransaction/{topic}", RocketConstant.LIVK_EXT_MESSAGE_TOPIC) + mockMvc + .perform(post("/api/ext/sendTransaction/{topic}", RocketConstant.LIVK_EXT_MESSAGE_TOPIC) .contentType(MediaType.APPLICATION_JSON) .content(JsonMapperUtils.writeValueAsString(dto))) .andExpect(status().isOk()) @@ -93,7 +96,8 @@ void sendTransactionMessage() throws Exception { @Test void sendDelay() throws Exception { - mockMvc.perform(post("/api/ext/sendDelay/{topic}", RocketConstant.LIVK_EXT_MESSAGE_TOPIC) + mockMvc + .perform(post("/api/ext/sendDelay/{topic}", RocketConstant.LIVK_EXT_MESSAGE_TOPIC) .contentType(MediaType.APPLICATION_JSON) .content(JsonMapperUtils.writeValueAsString(dto))) .andExpect(status().isOk()) @@ -105,7 +109,8 @@ void sendMessageOrderly() throws Exception { for (int i = 1; i <= 6; i++) { RocketDTO rocketDTO = new RocketDTO(); rocketDTO.setBody("同步顺序消息" + i); - mockMvc.perform(post("/api/ext/sendOrderly/{topic}", RocketConstant.LIVK_EXT_MESSAGE_ORDERLY_TOPIC) + mockMvc + .perform(post("/api/ext/sendOrderly/{topic}", RocketConstant.LIVK_EXT_MESSAGE_ORDERLY_TOPIC) .contentType(MediaType.APPLICATION_JSON) .content(JsonMapperUtils.writeValueAsString(rocketDTO))) .andExpect(status().isOk()) @@ -118,7 +123,8 @@ void sendAsyncMessageOrderly() throws Exception { for (int i = 1; i <= 6; i++) { RocketDTO rocketDTO = new RocketDTO(); rocketDTO.setBody("异步顺序消息" + i); - mockMvc.perform(post("/api/ext/sendAsyncOrderly/{topic}", RocketConstant.LIVK_EXT_MESSAGE_ORDERLY_TOPIC) + mockMvc + .perform(post("/api/ext/sendAsyncOrderly/{topic}", RocketConstant.LIVK_EXT_MESSAGE_ORDERLY_TOPIC) .contentType(MediaType.APPLICATION_JSON) .content(JsonMapperUtils.writeValueAsString(rocketDTO))) .andExpect(status().isOk()) @@ -131,7 +137,8 @@ void sendOneMessageOrderly() throws Exception { for (int i = 1; i <= 6; i++) { RocketDTO rocketDTO = new RocketDTO(); rocketDTO.setBody("单向顺序消息" + i); - mockMvc.perform(post("/api/ext/sendOneOrderly/{topic}", RocketConstant.LIVK_EXT_MESSAGE_ORDERLY_TOPIC) + mockMvc + .perform(post("/api/ext/sendOneOrderly/{topic}", RocketConstant.LIVK_EXT_MESSAGE_ORDERLY_TOPIC) .contentType(MediaType.APPLICATION_JSON) .content(JsonMapperUtils.writeValueAsString(rocketDTO))) .andExpect(status().isOk()) diff --git a/spring-boot-example/spring-rocket/rocket-producer/src/test/java/com/livk/rocket/producer/controller/RocketProducerTest.java b/spring-boot-example/spring-rocket/rocket-producer/src/test/java/com/livk/rocket/producer/controller/RocketProducerTest.java index 47bc1ce72..c048a97b2 100644 --- a/spring-boot-example/spring-rocket/rocket-producer/src/test/java/com/livk/rocket/producer/controller/RocketProducerTest.java +++ b/spring-boot-example/spring-rocket/rocket-producer/src/test/java/com/livk/rocket/producer/controller/RocketProducerTest.java @@ -53,19 +53,20 @@ public void init() { dto.setBody(msg); } - @Test void sendMessage() throws Exception { - mockMvc.perform(post("/api/send/{topic}", RocketConstant.LIVK_MESSAGE_TOPIC) - .contentType(MediaType.APPLICATION_JSON) - .content(JsonMapperUtils.writeValueAsString(dto))) + mockMvc + .perform( + post("/api/send/{topic}", RocketConstant.LIVK_MESSAGE_TOPIC).contentType(MediaType.APPLICATION_JSON) + .content(JsonMapperUtils.writeValueAsString(dto))) .andExpect(status().isOk()) .andDo(print()); } @Test void sendAsyncMessage() throws Exception { - mockMvc.perform(post("/api/sendAsync/{topic}", RocketConstant.LIVK_MESSAGE_TOPIC) + mockMvc + .perform(post("/api/sendAsync/{topic}", RocketConstant.LIVK_MESSAGE_TOPIC) .contentType(MediaType.APPLICATION_JSON) .content(JsonMapperUtils.writeValueAsString(dto))) .andExpect(status().isOk()) @@ -74,7 +75,8 @@ void sendAsyncMessage() throws Exception { @Test void sendOneMessage() throws Exception { - mockMvc.perform(post("/api/sendOne/{topic}", RocketConstant.LIVK_MESSAGE_TOPIC) + mockMvc + .perform(post("/api/sendOne/{topic}", RocketConstant.LIVK_MESSAGE_TOPIC) .contentType(MediaType.APPLICATION_JSON) .content(JsonMapperUtils.writeValueAsString(dto))) .andExpect(status().isOk()) @@ -83,7 +85,8 @@ void sendOneMessage() throws Exception { @Test void sendTransactionMessage() throws Exception { - mockMvc.perform(post("/api/sendTransaction/{topic}", RocketConstant.LIVK_MESSAGE_TOPIC) + mockMvc + .perform(post("/api/sendTransaction/{topic}", RocketConstant.LIVK_MESSAGE_TOPIC) .contentType(MediaType.APPLICATION_JSON) .content(JsonMapperUtils.writeValueAsString(dto))) .andExpect(status().isOk()) @@ -92,7 +95,8 @@ void sendTransactionMessage() throws Exception { @Test void sendDelay() throws Exception { - mockMvc.perform(post("/api/sendDelay/{topic}", RocketConstant.LIVK_MESSAGE_TOPIC) + mockMvc + .perform(post("/api/sendDelay/{topic}", RocketConstant.LIVK_MESSAGE_TOPIC) .contentType(MediaType.APPLICATION_JSON) .content(JsonMapperUtils.writeValueAsString(dto))) .andExpect(status().isOk()) @@ -104,7 +108,8 @@ void sendMessageOrderly() throws Exception { for (int i = 1; i <= 6; i++) { RocketDTO rocketDTO = new RocketDTO(); rocketDTO.setBody("同步顺序消息" + i); - mockMvc.perform(post("/api/sendOrderly/{topic}", RocketConstant.LIVK_MESSAGE_ORDERLY_TOPIC) + mockMvc + .perform(post("/api/sendOrderly/{topic}", RocketConstant.LIVK_MESSAGE_ORDERLY_TOPIC) .contentType(MediaType.APPLICATION_JSON) .content(JsonMapperUtils.writeValueAsString(rocketDTO))) .andExpect(status().isOk()) @@ -117,7 +122,8 @@ void sendAsyncMessageOrderly() throws Exception { for (int i = 1; i <= 6; i++) { RocketDTO rocketDTO = new RocketDTO(); rocketDTO.setBody("异步顺序消息" + i); - mockMvc.perform(post("/api/sendAsyncOrderly/{topic}", RocketConstant.LIVK_MESSAGE_ORDERLY_TOPIC) + mockMvc + .perform(post("/api/sendAsyncOrderly/{topic}", RocketConstant.LIVK_MESSAGE_ORDERLY_TOPIC) .contentType(MediaType.APPLICATION_JSON) .content(JsonMapperUtils.writeValueAsString(rocketDTO))) .andExpect(status().isOk()) @@ -130,7 +136,8 @@ void sendOneMessageOrderly() throws Exception { for (int i = 1; i <= 6; i++) { RocketDTO rocketDTO = new RocketDTO(); rocketDTO.setBody("单向顺序消息" + i); - mockMvc.perform(post("/api/sendOneOrderly/{topic}", RocketConstant.LIVK_MESSAGE_ORDERLY_TOPIC) + mockMvc + .perform(post("/api/sendOneOrderly/{topic}", RocketConstant.LIVK_MESSAGE_ORDERLY_TOPIC) .contentType(MediaType.APPLICATION_JSON) .content(JsonMapperUtils.writeValueAsString(rocketDTO))) .andExpect(status().isOk()) diff --git a/spring-boot-example/spring-rsocket/rsocket-client/src/main/java/com/livk/rsocket/MessageController.java b/spring-boot-example/spring-rsocket/rsocket-client/src/main/java/com/livk/rsocket/MessageController.java index 8e2642f42..c9bce9cb1 100644 --- a/spring-boot-example/spring-rsocket/rsocket-client/src/main/java/com/livk/rsocket/MessageController.java +++ b/spring-boot-example/spring-rsocket/rsocket-client/src/main/java/com/livk/rsocket/MessageController.java @@ -53,7 +53,6 @@ public MessageController(RSocketRequester.Builder rsocketRequesterBuilder, RSock .createClient(MessageService.class); } - @GetMapping("request-response") public Mono requestResponse() { return messageService.requestResponse(new Message("客户端", "服务器")); @@ -61,8 +60,7 @@ public Mono requestResponse() { @GetMapping("fire-and-forget") public Mono fireAndForget() { - return messageService.fireAndForget(new Message("客户端", "服务器")) - .flatMap(unused -> Mono.just("fire and forget")); + return messageService.fireAndForget(new Message("客户端", "服务器")).flatMap(unused -> Mono.just("fire and forget")); } @GetMapping("stream") @@ -84,4 +82,5 @@ public Mono channel() { .map(messages -> messages.stream().map(Message::toString).collect(Collectors.toList())) .map(list -> String.join(",", list)); } + } diff --git a/spring-boot-example/spring-rsocket/rsocket-client/src/main/java/com/livk/rsocket/MessageService.java b/spring-boot-example/spring-rsocket/rsocket-client/src/main/java/com/livk/rsocket/MessageService.java index 2966e8555..add4460a9 100644 --- a/spring-boot-example/spring-rsocket/rsocket-client/src/main/java/com/livk/rsocket/MessageService.java +++ b/spring-boot-example/spring-rsocket/rsocket-client/src/main/java/com/livk/rsocket/MessageService.java @@ -44,4 +44,5 @@ public interface MessageService { @RSocketExchange("channel") Flux channel(Flux settings); + } diff --git a/spring-boot-example/spring-rsocket/rsocket-client/src/main/java/com/livk/rsocket/RSocketClient.java b/spring-boot-example/spring-rsocket/rsocket-client/src/main/java/com/livk/rsocket/RSocketClient.java index 75ae35cc6..be748a3d9 100644 --- a/spring-boot-example/spring-rsocket/rsocket-client/src/main/java/com/livk/rsocket/RSocketClient.java +++ b/spring-boot-example/spring-rsocket/rsocket-client/src/main/java/com/livk/rsocket/RSocketClient.java @@ -65,8 +65,7 @@ public Mono requestResponse() { @GetMapping("fire-and-forget") public Mono fireAndForget() { - return this.rsocketRequester - .route("fire-and-forget") + return this.rsocketRequester.route("fire-and-forget") .data(new Message("客户端", "服务器")) .send() .flatMap(unused -> Mono.just("fire and forget")); @@ -84,8 +83,7 @@ public Mono channel() { Mono setting3 = Mono.just(Duration.ofSeconds(5)).delayElement(Duration.ofSeconds(15)); Flux settings = Flux.concat(setting1, setting2, setting3) .doOnNext(d -> log.info("客户端channel发送消息 {}", d.getSeconds())); - return settings.collectList() - .flatMap(durations -> Mono.just("channel")); + return settings.collectList().flatMap(durations -> Mono.just("channel")); } } diff --git a/spring-boot-example/spring-rsocket/rsocket-server/src/main/java/com/livk/rsocket/RSocketController.java b/spring-boot-example/spring-rsocket/rsocket-server/src/main/java/com/livk/rsocket/RSocketController.java index 158c1c1e4..7a5c909c3 100644 --- a/spring-boot-example/spring-rsocket/rsocket-server/src/main/java/com/livk/rsocket/RSocketController.java +++ b/spring-boot-example/spring-rsocket/rsocket-server/src/main/java/com/livk/rsocket/RSocketController.java @@ -56,7 +56,8 @@ Flux stream(Message request) { @MessageMapping("channel") Flux channel(final Flux settings) { return settings.doOnNext(setting -> log.info("发射间隔为 {} 秒.", setting.getSeconds())) - .switchMap(setting -> Flux.interval(setting).map(index -> new Message("服务端", "客户端", index))).log(); + .switchMap(setting -> Flux.interval(setting).map(index -> new Message("服务端", "客户端", index))) + .log(); } } diff --git a/spring-boot-example/spring-security/security-sso/sso-auth/src/main/java/com/livk/sso/auth/SSOAuthApp.java b/spring-boot-example/spring-security/security-sso/sso-auth/src/main/java/com/livk/sso/auth/SSOAuthApp.java index 1e0b118ef..58d29ee4b 100644 --- a/spring-boot-example/spring-security/security-sso/sso-auth/src/main/java/com/livk/sso/auth/SSOAuthApp.java +++ b/spring-boot-example/spring-security/security-sso/sso-auth/src/main/java/com/livk/sso/auth/SSOAuthApp.java @@ -39,13 +39,13 @@ public static void main(String[] args) { } @Bean - public ApplicationRunner applicationRunner(UserMapper userMapper, - JdbcTemplate jdbcTemplate) { + public ApplicationRunner applicationRunner(UserMapper userMapper, JdbcTemplate jdbcTemplate) { return args -> { if (userMapper.getByUserName("livk") == null) { - jdbcTemplate.execute("INSERT INTO users (id, username, password)\n" + - "VALUES (1, 'livk', '$2a$10$LepUx6I/1y0Pc614ZqSK6eXvoMbNDjdjAKqV/GQ4C97b0pw/kiuBC')"); + jdbcTemplate.execute("INSERT INTO users (id, username, password)\n" + + "VALUES (1, 'livk', '$2a$10$LepUx6I/1y0Pc614ZqSK6eXvoMbNDjdjAKqV/GQ4C97b0pw/kiuBC')"); } }; } + } diff --git a/spring-boot-example/spring-security/security-sso/sso-auth/src/main/java/com/livk/sso/auth/config/TokenLoginFilter.java b/spring-boot-example/spring-security/security-sso/sso-auth/src/main/java/com/livk/sso/auth/config/TokenLoginFilter.java index 19db0067d..6730ee91e 100644 --- a/spring-boot-example/spring-security/security-sso/sso-auth/src/main/java/com/livk/sso/auth/config/TokenLoginFilter.java +++ b/spring-boot-example/spring-security/security-sso/sso-auth/src/main/java/com/livk/sso/auth/config/TokenLoginFilter.java @@ -43,7 +43,7 @@ public class TokenLoginFilter extends AbstractAuthenticationProcessingFilter { private static final AntPathRequestMatcher DEFAULT_ANT_PATH_REQUEST_MATCHER = new AntPathRequestMatcher("/login", - "POST"); + "POST"); private final AuthenticationManager authenticationManager; @@ -54,16 +54,18 @@ public TokenLoginFilter(AuthenticationManager authenticationManager) { @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) - throws AuthenticationException { + throws AuthenticationException { try { User user = JsonMapperUtils.readValue(request.getInputStream(), User.class); - UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword(), - user.getAuthorities()); + UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken( + user.getUsername(), user.getPassword(), user.getAuthorities()); return authenticationManager.authenticate(authenticationToken); - } catch (IOException e) { + } + catch (IOException e) { Map map = Map.of("code", HttpServletResponse.SC_UNAUTHORIZED, "msg", "用户名或者密码错误!"); WebUtils.outJson(response, map); throw new UsernameNotFoundException("用户名或者密码错误"); } } + } diff --git a/spring-boot-example/spring-security/security-sso/sso-auth/src/main/java/com/livk/sso/auth/handler/CustomAccessDeniedHandler.java b/spring-boot-example/spring-security/security-sso/sso-auth/src/main/java/com/livk/sso/auth/handler/CustomAccessDeniedHandler.java index 3c4debfe6..a38fd2e6e 100644 --- a/spring-boot-example/spring-security/security-sso/sso-auth/src/main/java/com/livk/sso/auth/handler/CustomAccessDeniedHandler.java +++ b/spring-boot-example/spring-security/security-sso/sso-auth/src/main/java/com/livk/sso/auth/handler/CustomAccessDeniedHandler.java @@ -31,9 +31,13 @@ */ @Slf4j public class CustomAccessDeniedHandler implements AccessDeniedHandler { + @Override - public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) { + public void handle(HttpServletRequest request, HttpServletResponse response, + AccessDeniedException accessDeniedException) { log.error("exception:{}", accessDeniedException.getMessage(), accessDeniedException); - WebUtils.outJson(response, Map.of("code", HttpServletResponse.SC_FORBIDDEN, "msg", accessDeniedException.getMessage())); + WebUtils.outJson(response, + Map.of("code", HttpServletResponse.SC_FORBIDDEN, "msg", accessDeniedException.getMessage())); } + } diff --git a/spring-boot-example/spring-security/security-sso/sso-auth/src/main/java/com/livk/sso/auth/handler/CustomAuthenticationFailureHandler.java b/spring-boot-example/spring-security/security-sso/sso-auth/src/main/java/com/livk/sso/auth/handler/CustomAuthenticationFailureHandler.java index 705e0c18f..a6f54476f 100644 --- a/spring-boot-example/spring-security/security-sso/sso-auth/src/main/java/com/livk/sso/auth/handler/CustomAuthenticationFailureHandler.java +++ b/spring-boot-example/spring-security/security-sso/sso-auth/src/main/java/com/livk/sso/auth/handler/CustomAuthenticationFailureHandler.java @@ -31,10 +31,13 @@ */ @Slf4j public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler { + @Override - public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) { + public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, + AuthenticationException exception) { log.error("异常:{}", exception.getMessage(), exception); WebUtils.outJson(response, Map.of("code", HttpServletResponse.SC_BAD_REQUEST, "msg", - "login failed, username or password is incorrect")); + "login failed, username or password is incorrect")); } + } diff --git a/spring-boot-example/spring-security/security-sso/sso-auth/src/main/java/com/livk/sso/auth/handler/CustomAuthenticationSuccessHandler.java b/spring-boot-example/spring-security/security-sso/sso-auth/src/main/java/com/livk/sso/auth/handler/CustomAuthenticationSuccessHandler.java index e256565a6..162ec1099 100644 --- a/spring-boot-example/spring-security/security-sso/sso-auth/src/main/java/com/livk/sso/auth/handler/CustomAuthenticationSuccessHandler.java +++ b/spring-boot-example/spring-security/security-sso/sso-auth/src/main/java/com/livk/sso/auth/handler/CustomAuthenticationSuccessHandler.java @@ -33,12 +33,15 @@ */ @Slf4j public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler { + @Override - public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) { + public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, + Authentication authentication) { User user = (User) authentication.getPrincipal(); String token = JwtUtils.generateToken(user); log.info("登录成功user:{} token:{}", user, token); Map map = Map.of("code", HttpServletResponse.SC_OK, "data", token); WebUtils.outJson(response, map); } + } diff --git a/spring-boot-example/spring-security/security-sso/sso-auth/src/main/java/com/livk/sso/auth/handler/CustomLogoutSuccessHandler.java b/spring-boot-example/spring-security/security-sso/sso-auth/src/main/java/com/livk/sso/auth/handler/CustomLogoutSuccessHandler.java index 4e5429db8..554936eb7 100644 --- a/spring-boot-example/spring-security/security-sso/sso-auth/src/main/java/com/livk/sso/auth/handler/CustomLogoutSuccessHandler.java +++ b/spring-boot-example/spring-security/security-sso/sso-auth/src/main/java/com/livk/sso/auth/handler/CustomLogoutSuccessHandler.java @@ -32,10 +32,13 @@ */ @Slf4j public class CustomLogoutSuccessHandler implements LogoutSuccessHandler { + @Override - public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) { + public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, + Authentication authentication) { log.info("退出"); SecurityContextHolder.getContextHolderStrategy().clearContext(); WebUtils.outJson(response, Map.of("code", HttpServletResponse.SC_OK, "msg", "exit successfully")); } + } diff --git a/spring-boot-example/spring-security/security-sso/sso-auth/src/main/java/com/livk/sso/auth/support/CustomAuthenticationEntryPoint.java b/spring-boot-example/spring-security/security-sso/sso-auth/src/main/java/com/livk/sso/auth/support/CustomAuthenticationEntryPoint.java index ca6ef275a..536046787 100644 --- a/spring-boot-example/spring-security/security-sso/sso-auth/src/main/java/com/livk/sso/auth/support/CustomAuthenticationEntryPoint.java +++ b/spring-boot-example/spring-security/security-sso/sso-auth/src/main/java/com/livk/sso/auth/support/CustomAuthenticationEntryPoint.java @@ -31,9 +31,12 @@ */ @Slf4j public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint { + @Override - public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) { + public void commence(HttpServletRequest request, HttpServletResponse response, + AuthenticationException authException) { log.error("异常:{}", authException.getMessage(), authException); WebUtils.outJson(response, Map.of("code", HttpServletResponse.SC_FORBIDDEN, "msg", authException.getMessage())); } + } diff --git a/spring-boot-example/spring-security/security-sso/sso-auth/src/test/java/com/livk/sso/auth/controller/UserControllerTest.java b/spring-boot-example/spring-security/security-sso/sso-auth/src/test/java/com/livk/sso/auth/controller/UserControllerTest.java index c7ec13edc..cf6a8cfdc 100644 --- a/spring-boot-example/spring-security/security-sso/sso-auth/src/test/java/com/livk/sso/auth/controller/UserControllerTest.java +++ b/spring-boot-example/spring-security/security-sso/sso-auth/src/test/java/com/livk/sso/auth/controller/UserControllerTest.java @@ -42,14 +42,11 @@ * * @author livk */ -@SpringBootTest({ - "spring.datasource.driver-class-name=org.h2.Driver", - "spring.datasource.url=jdbc:h2:mem:test", - "spring.sql.init.platform=h2", - "spring.sql.init.mode=embedded" -}) +@SpringBootTest({ "spring.datasource.driver-class-name=org.h2.Driver", "spring.datasource.url=jdbc:h2:mem:test", + "spring.sql.init.platform=h2", "spring.sql.init.mode=embedded" }) @AutoConfigureMockMvc class UserControllerTest { + @Autowired MockMvc mockMvc; @@ -60,21 +57,21 @@ public void init() throws Exception { Map body = new HashMap<>(); body.put("username", "livk"); body.put("password", "123456"); - MockHttpServletResponse response = mockMvc.perform(post("/login") - .contentType(MediaType.APPLICATION_JSON) + MockHttpServletResponse response = mockMvc + .perform(post("/login").contentType(MediaType.APPLICATION_JSON) .content(JsonMapperUtils.writeValueAsString(body))) .andExpect(status().isOk()) .andDo(print()) .andExpect(jsonPath("code", "200").exists()) - .andReturn().getResponse(); - token = "Bearer " + JsonMapperUtils.readValueMap(response.getContentAsString(), String.class, String.class).get("data"); + .andReturn() + .getResponse(); + token = "Bearer " + + JsonMapperUtils.readValueMap(response.getContentAsString(), String.class, String.class).get("data"); } - @Test void testList() throws Exception { - mockMvc.perform(get("/user/list") - .header(HttpHeaders.AUTHORIZATION, token)) + mockMvc.perform(get("/user/list").header(HttpHeaders.AUTHORIZATION, token)) .andExpect(status().isOk()) .andDo(print()) .andExpect(content().string("list")); @@ -82,12 +79,13 @@ void testList() throws Exception { @Test void testUpdate() throws Exception { - mockMvc.perform(put("/user/update") - .header(HttpHeaders.AUTHORIZATION, token)) + mockMvc.perform(put("/user/update").header(HttpHeaders.AUTHORIZATION, token)) .andExpect(status().isOk()) .andDo(print()) .andExpect(content().string("update")); } + } -//Generated with love by TestMe :) Please report issues and submit feature requests at: http://weirddev.com/forum#!/testme +// Generated with love by TestMe :) Please report issues and submit feature requests at: +// http://weirddev.com/forum#!/testme diff --git a/spring-boot-example/spring-security/security-sso/sso-commons/src/main/java/com/livk/sso/commons/RsaKeyProperties.java b/spring-boot-example/spring-security/security-sso/sso-commons/src/main/java/com/livk/sso/commons/RsaKeyProperties.java index b09e80266..922e0a421 100644 --- a/spring-boot-example/spring-security/security-sso/sso-commons/src/main/java/com/livk/sso/commons/RsaKeyProperties.java +++ b/spring-boot-example/spring-security/security-sso/sso-commons/src/main/java/com/livk/sso/commons/RsaKeyProperties.java @@ -44,9 +44,8 @@ public class RsaKeyProperties { private final RSAKey rsaKey; - public RsaKeyProperties(@Name("location") String location, - @Name("password") String password, - @Name("alias") String alias) { + public RsaKeyProperties(@Name("location") String location, @Name("password") String password, + @Name("alias") String alias) { if (ObjectUtils.isEmpty(location)) { location = DEFAULT_LOCATION; } @@ -57,7 +56,8 @@ public RsaKeyProperties(@Name("location") String location, if (resources != null) { jksResource = resources[0]; } - } catch (IOException e) { + } + catch (IOException e) { throw new RuntimeException(e); } } @@ -67,4 +67,5 @@ public RsaKeyProperties(@Name("location") String location, public RSAKey rsaKey() { return rsaKey; } + } diff --git a/spring-boot-example/spring-security/security-sso/sso-commons/src/main/java/com/livk/sso/commons/SSOAutoConfiguration.java b/spring-boot-example/spring-security/security-sso/sso-commons/src/main/java/com/livk/sso/commons/SSOAutoConfiguration.java index 5a2899853..ecceb27ad 100644 --- a/spring-boot-example/spring-security/security-sso/sso-commons/src/main/java/com/livk/sso/commons/SSOAutoConfiguration.java +++ b/spring-boot-example/spring-security/security-sso/sso-commons/src/main/java/com/livk/sso/commons/SSOAutoConfiguration.java @@ -32,4 +32,5 @@ @AutoConfiguration @EnableConfigurationProperties(RsaKeyProperties.class) public class SSOAutoConfiguration { + } diff --git a/spring-boot-example/spring-security/security-sso/sso-commons/src/main/java/com/livk/sso/commons/entity/User.java b/spring-boot-example/spring-security/security-sso/sso-commons/src/main/java/com/livk/sso/commons/entity/User.java index b0b6e8d68..0ed9f11f6 100644 --- a/spring-boot-example/spring-security/security-sso/sso-commons/src/main/java/com/livk/sso/commons/entity/User.java +++ b/spring-boot-example/spring-security/security-sso/sso-commons/src/main/java/com/livk/sso/commons/entity/User.java @@ -53,16 +53,10 @@ public class User implements UserDetails { private List roles; @JsonCreator - public static User create(@JsonProperty("id") Long id, - @JsonProperty("username") String username, - @JsonProperty("password") String password, - @JsonProperty("status") Integer status, - @JsonProperty("roles") List roles) { - return new User().setId(id) - .setUsername(username) - .setPassword(password) - .setStatus(status) - .setRoles(roles); + public static User create(@JsonProperty("id") Long id, @JsonProperty("username") String username, + @JsonProperty("password") String password, @JsonProperty("status") Integer status, + @JsonProperty("roles") List roles) { + return new User().setId(id).setUsername(username).setPassword(password).setStatus(status).setRoles(roles); } @JsonIgnore diff --git a/spring-boot-example/spring-security/security-sso/sso-commons/src/main/java/com/livk/sso/commons/filter/TokenVerifyFilter.java b/spring-boot-example/spring-security/security-sso/sso-commons/src/main/java/com/livk/sso/commons/filter/TokenVerifyFilter.java index 4443f7482..742d8c389 100644 --- a/spring-boot-example/spring-security/security-sso/sso-commons/src/main/java/com/livk/sso/commons/filter/TokenVerifyFilter.java +++ b/spring-boot-example/spring-security/security-sso/sso-commons/src/main/java/com/livk/sso/commons/filter/TokenVerifyFilter.java @@ -45,22 +45,24 @@ public TokenVerifyFilter(AuthenticationManager authenticationManager) { @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) - throws IOException, ServletException { + throws IOException, ServletException { String authorization = request.getHeader(HttpHeaders.AUTHORIZATION); if (authorization != null && authorization.startsWith("Bearer ")) { String token = authorization.replaceFirst("Bearer ", ""); Payload payload = JwtUtils.parse(token); User user = payload.getUserInfo(); if (user != null) { - UsernamePasswordAuthenticationToken authenticated = UsernamePasswordAuthenticationToken.authenticated(user, - "", user.getAuthorities()); + UsernamePasswordAuthenticationToken authenticated = UsernamePasswordAuthenticationToken + .authenticated(user, "", user.getAuthorities()); SecurityContextHolder.getContext().setAuthentication(authenticated); chain.doFilter(request, response); - } else { + } + else { Map map = Map.of("code", HttpServletResponse.SC_FORBIDDEN, "msg", "缺少用户信息"); WebUtils.outJson(response, map); } - } else { + } + else { Map map = Map.of("code", HttpServletResponse.SC_FORBIDDEN, "msg", "请登录!"); WebUtils.outJson(response, map); } diff --git a/spring-boot-example/spring-security/security-sso/sso-commons/src/main/java/com/livk/sso/commons/util/JwtUtils.java b/spring-boot-example/spring-security/security-sso/sso-commons/src/main/java/com/livk/sso/commons/util/JwtUtils.java index 036a10215..0091e66fb 100644 --- a/spring-boot-example/spring-security/security-sso/sso-commons/src/main/java/com/livk/sso/commons/util/JwtUtils.java +++ b/spring-boot-example/spring-security/security-sso/sso-commons/src/main/java/com/livk/sso/commons/util/JwtUtils.java @@ -54,13 +54,13 @@ public class JwtUtils { public String generateToken(User userInfo) { JWSHeader jwsHeader = new JWSHeader.Builder(JWSAlgorithm.RS256).type(JOSEObjectType.JWT).build(); Payload payload = new Payload(UUID.randomUUID().toString(), userInfo); - JWSObject jwsObject = new JWSObject(jwsHeader, new com.nimbusds.jose.Payload(JsonMapperUtils.writeValueAsString(payload))); + JWSObject jwsObject = new JWSObject(jwsHeader, + new com.nimbusds.jose.Payload(JsonMapperUtils.writeValueAsString(payload))); RSASSASigner signer = new RSASSASigner(RSA_KEY); jwsObject.sign(signer); return jwsObject.serialize(); } - @SneakyThrows public Payload parse(String token) { JWSObject jwsObject = JWSObject.parse(token); @@ -71,4 +71,5 @@ public Payload parse(String token) { } throw new RuntimeException("500"); } + } diff --git a/spring-boot-example/spring-security/security-sso/sso-commons/src/main/java/com/livk/sso/commons/util/KeyStoreKeyFactory.java b/spring-boot-example/spring-security/security-sso/sso-commons/src/main/java/com/livk/sso/commons/util/KeyStoreKeyFactory.java index 2f2ac5acb..53f4caf52 100644 --- a/spring-boot-example/spring-security/security-sso/sso-commons/src/main/java/com/livk/sso/commons/util/KeyStoreKeyFactory.java +++ b/spring-boot-example/spring-security/security-sso/sso-commons/src/main/java/com/livk/sso/commons/util/KeyStoreKeyFactory.java @@ -39,9 +39,13 @@ public class KeyStoreKeyFactory { private final Resource resource; + private final char[] password; + private final Object lock = new Object(); + private final String type; + private KeyStore store; public KeyStoreKeyFactory(Resource resource, char[] password) { @@ -80,15 +84,15 @@ public KeyPair getKeyPair(String alias, char[] password) { PublicKey publicKey = null; if (certificate != null) { publicKey = certificate.getPublicKey(); - } else if (key != null) { - RSAPublicKeySpec spec = new RSAPublicKeySpec(key.getModulus(), - key.getPublicExponent()); + } + else if (key != null) { + RSAPublicKeySpec spec = new RSAPublicKeySpec(key.getModulus(), key.getPublicExponent()); publicKey = KeyFactory.getInstance("RSA").generatePublic(spec); } return new KeyPair(publicKey, key); - } catch (Exception e) { - throw new IllegalStateException("Cannot load keys from store: " + resource, - e); + } + catch (Exception e) { + throw new IllegalStateException("Cannot load keys from store: " + resource, e); } } diff --git a/spring-boot-example/spring-security/security-sso/sso-commons/src/main/java/com/livk/sso/commons/util/RSAUtils.java b/spring-boot-example/spring-security/security-sso/sso-commons/src/main/java/com/livk/sso/commons/util/RSAUtils.java index 52f070a63..062367714 100644 --- a/spring-boot-example/spring-security/security-sso/sso-commons/src/main/java/com/livk/sso/commons/util/RSAUtils.java +++ b/spring-boot-example/spring-security/security-sso/sso-commons/src/main/java/com/livk/sso/commons/util/RSAUtils.java @@ -41,4 +41,5 @@ public RSAKey rsaKey(Resource resource, String password, String alise) { RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); return new RSAKey.Builder(publicKey).privateKey(privateKey).build(); } + } diff --git a/spring-boot-example/spring-security/security-sso/sso-commons/src/main/java/com/livk/sso/commons/util/SecurityContextUtils.java b/spring-boot-example/spring-security/security-sso/sso-commons/src/main/java/com/livk/sso/commons/util/SecurityContextUtils.java index 5602b91b2..ee0177693 100644 --- a/spring-boot-example/spring-security/security-sso/sso-commons/src/main/java/com/livk/sso/commons/util/SecurityContextUtils.java +++ b/spring-boot-example/spring-security/security-sso/sso-commons/src/main/java/com/livk/sso/commons/util/SecurityContextUtils.java @@ -36,4 +36,5 @@ public User getUser() { Object principal = getAuthentication().getPrincipal(); return principal instanceof User user ? user : null; } + } diff --git a/spring-boot-example/spring-security/security-sso/sso-resources/src/main/java/com/livk/sso/resource/service/UserService.java b/spring-boot-example/spring-security/security-sso/sso-resources/src/main/java/com/livk/sso/resource/service/UserService.java index 4395c39b4..68a9ec4e0 100644 --- a/spring-boot-example/spring-security/security-sso/sso-resources/src/main/java/com/livk/sso/resource/service/UserService.java +++ b/spring-boot-example/spring-security/security-sso/sso-resources/src/main/java/com/livk/sso/resource/service/UserService.java @@ -36,4 +36,5 @@ public class UserService implements UserDetailsService { public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { throw new UnsupportedOperationException(); } + } diff --git a/spring-boot-example/spring-security/security-sso/sso-resources/src/test/java/com/livk/sso/resource/controller/UserControllerTest.java b/spring-boot-example/spring-security/security-sso/sso-resources/src/test/java/com/livk/sso/resource/controller/UserControllerTest.java index 3b950fda8..1979d8a87 100644 --- a/spring-boot-example/spring-security/security-sso/sso-resources/src/test/java/com/livk/sso/resource/controller/UserControllerTest.java +++ b/spring-boot-example/spring-security/security-sso/sso-resources/src/test/java/com/livk/sso/resource/controller/UserControllerTest.java @@ -66,8 +66,10 @@ public void init() { Map body = new HashMap<>(); body.put("username", "livk"); body.put("password", "123456"); - ResponseEntity responseEntity = template.postForEntity("http://localhost:9987/login", JsonMapperUtils.writeValueAsString(body), String.class); - token = "Bearer " + JsonMapperUtils.readValueMap(responseEntity.getBody(), String.class, String.class).get("data"); + ResponseEntity responseEntity = template.postForEntity("http://localhost:9987/login", + JsonMapperUtils.writeValueAsString(body), String.class); + token = "Bearer " + + JsonMapperUtils.readValueMap(responseEntity.getBody(), String.class, String.class).get("data"); } @Test @@ -77,8 +79,7 @@ public void test() { @Test void testList() throws Exception { - mockMvc.perform(get("/user/list") - .header(HttpHeaders.AUTHORIZATION, token)) + mockMvc.perform(get("/user/list").header(HttpHeaders.AUTHORIZATION, token)) .andExpect(status().isOk()) .andDo(print()) .andExpect(content().string("list")); @@ -86,10 +87,10 @@ void testList() throws Exception { @Test void testUpdate() throws Exception { - mockMvc.perform(put("/user/update") - .header(HttpHeaders.AUTHORIZATION, token)) + mockMvc.perform(put("/user/update").header(HttpHeaders.AUTHORIZATION, token)) .andExpect(status().isOk()) .andDo(print()) .andExpect(content().string("update")); } + } diff --git a/spring-boot-example/spring-server-sent-events/src/main/java/com/livk/event/SentServer.java b/spring-boot-example/spring-server-sent-events/src/main/java/com/livk/event/SentServer.java index b8c5100a7..8c4d1a0b2 100644 --- a/spring-boot-example/spring-server-sent-events/src/main/java/com/livk/event/SentServer.java +++ b/spring-boot-example/spring-server-sent-events/src/main/java/com/livk/event/SentServer.java @@ -31,7 +31,9 @@ @EnableScheduling @SpringBootApplication public class SentServer { + public static void main(String[] args) { SpringLauncher.run(args); } + } diff --git a/spring-boot-example/spring-server-sent-events/src/main/java/com/livk/event/SentTask.java b/spring-boot-example/spring-server-sent-events/src/main/java/com/livk/event/SentTask.java index 7f8da1e33..7010852a3 100644 --- a/spring-boot-example/spring-server-sent-events/src/main/java/com/livk/event/SentTask.java +++ b/spring-boot-example/spring-server-sent-events/src/main/java/com/livk/event/SentTask.java @@ -50,11 +50,13 @@ public void push() { sseEmitter.send(SseEmitter.event() .data(DateUtils.format(LocalDateTime.now(), DateUtils.YMD_HMS)) .id(sseEmitterEntry.getKey())); - } catch (Exception e) { + } + catch (Exception e) { log.error("推送异常:{}", e.getMessage()); sseEmitter.complete(); sseEmitterRepository.remove(sseEmitterEntry.getKey()); } } } + } diff --git a/spring-boot-example/spring-server-sent-events/src/main/java/com/livk/event/context/InMemorySseEmitterRepository.java b/spring-boot-example/spring-server-sent-events/src/main/java/com/livk/event/context/InMemorySseEmitterRepository.java index 855a1335a..c52da4942 100644 --- a/spring-boot-example/spring-server-sent-events/src/main/java/com/livk/event/context/InMemorySseEmitterRepository.java +++ b/spring-boot-example/spring-server-sent-events/src/main/java/com/livk/event/context/InMemorySseEmitterRepository.java @@ -54,4 +54,5 @@ public SseEmitter put(String id, SseEmitter sseEmitter) { public SseEmitter remove(String id) { return sseEmitters.remove(id); } + } diff --git a/spring-boot-example/spring-server-sent-events/src/main/java/com/livk/event/context/SseEmitterLocator.java b/spring-boot-example/spring-server-sent-events/src/main/java/com/livk/event/context/SseEmitterLocator.java index 546478e93..42e4e6966 100644 --- a/spring-boot-example/spring-server-sent-events/src/main/java/com/livk/event/context/SseEmitterLocator.java +++ b/spring-boot-example/spring-server-sent-events/src/main/java/com/livk/event/context/SseEmitterLocator.java @@ -33,4 +33,5 @@ public interface SseEmitterLocator { Map all(); SseEmitter get(K id); + } diff --git a/spring-boot-example/spring-server-sent-events/src/main/java/com/livk/event/context/SseEmitterRepository.java b/spring-boot-example/spring-server-sent-events/src/main/java/com/livk/event/context/SseEmitterRepository.java index f0c4b5937..cfa755590 100644 --- a/spring-boot-example/spring-server-sent-events/src/main/java/com/livk/event/context/SseEmitterRepository.java +++ b/spring-boot-example/spring-server-sent-events/src/main/java/com/livk/event/context/SseEmitterRepository.java @@ -25,4 +25,5 @@ * @author livk */ public interface SseEmitterRepository extends SseEmitterLocator, SseEmitterWriter { + } diff --git a/spring-boot-example/spring-server-sent-events/src/main/java/com/livk/event/context/SseEmitterWriter.java b/spring-boot-example/spring-server-sent-events/src/main/java/com/livk/event/context/SseEmitterWriter.java index 3e83d224e..d5055e5c7 100644 --- a/spring-boot-example/spring-server-sent-events/src/main/java/com/livk/event/context/SseEmitterWriter.java +++ b/spring-boot-example/spring-server-sent-events/src/main/java/com/livk/event/context/SseEmitterWriter.java @@ -31,4 +31,5 @@ public interface SseEmitterWriter { SseEmitter put(K id, SseEmitter sseEmitter); SseEmitter remove(K id); + } diff --git a/spring-boot-example/spring-server-sent-events/src/main/java/com/livk/event/controller/SentController.java b/spring-boot-example/spring-server-sent-events/src/main/java/com/livk/event/controller/SentController.java index a57ac524d..f10c561f2 100644 --- a/spring-boot-example/spring-server-sent-events/src/main/java/com/livk/event/controller/SentController.java +++ b/spring-boot-example/spring-server-sent-events/src/main/java/com/livk/event/controller/SentController.java @@ -56,16 +56,13 @@ public HttpEntity subscribe(@PathVariable String id) { } @PostMapping("/push/{id}") - public HttpEntity push(@PathVariable String id, - @RequestBody JsonNode content) throws IOException { + public HttpEntity push(@PathVariable String id, @RequestBody JsonNode content) throws IOException { log.info("{}", content); SseEmitter sseEmitter = sseEmitterRepository.get(id); if (sseEmitter == null) { return ResponseEntity.ok(false); } - sseEmitter.send(SseEmitter.event() - .data(content) - .id(id)); + sseEmitter.send(SseEmitter.event().data(content).id(id)); return ResponseEntity.ok(true); } @@ -76,9 +73,7 @@ public HttpEntity pushData(@PathVariable String id) throws IOException return ResponseEntity.ok(false); } for (int i = 0; i < 10; i++) { - sseEmitter.send(SseEmitter.event() - .data(i + ":::::" + UUID.randomUUID()) - .id(id)); + sseEmitter.send(SseEmitter.event().data(i + ":::::" + UUID.randomUUID()).id(id)); } sseEmitter.complete(); sseEmitterRepository.remove(id); @@ -95,4 +90,5 @@ public HttpEntity over(@PathVariable String id) { sseEmitterRepository.remove(id); return ResponseEntity.ok(true); } + } diff --git a/spring-boot-example/spring-video/src/main/java/com/livk/video/VideoApp.java b/spring-boot-example/spring-video/src/main/java/com/livk/video/VideoApp.java index f46fcc799..62fa36f32 100644 --- a/spring-boot-example/spring-video/src/main/java/com/livk/video/VideoApp.java +++ b/spring-boot-example/spring-video/src/main/java/com/livk/video/VideoApp.java @@ -25,7 +25,9 @@ */ @SpringBootApplication public class VideoApp { + public static void main(String[] args) { SpringLauncher.run(args); } + } diff --git a/spring-boot-example/spring-video/src/main/java/com/livk/video/controller/VideoController.java b/spring-boot-example/spring-video/src/main/java/com/livk/video/controller/VideoController.java index 2fda703b7..92896fe79 100644 --- a/spring-boot-example/spring-video/src/main/java/com/livk/video/controller/VideoController.java +++ b/spring-boot-example/spring-video/src/main/java/com/livk/video/controller/VideoController.java @@ -44,21 +44,23 @@ public class VideoController { private static final String VIDEO_SUFFIX = ".mp4"; + private final VideoResourceHttpRequestHandler requestHandler; @GetMapping - public void video(HttpServletRequest request, - HttpServletResponse response, - @RequestParam(defaultValue = "test") String videoName) throws Exception { - //查询视频是否存在 + public void video(HttpServletRequest request, HttpServletResponse response, + @RequestParam(defaultValue = "test") String videoName) throws Exception { + // 查询视频是否存在 if ("test".equals(videoName)) { request.setAttribute(VideoResourceHttpRequestHandler.ATTR, "classpath:" + videoName + VIDEO_SUFFIX); requestHandler.handleRequest(request, response); - } else { + } + else { Map map = Map.of("msg", "视频资源不存在", "status", HttpServletResponse.SC_NOT_FOUND); response.setStatus(HttpServletResponse.SC_NOT_FOUND); response.setCharacterEncoding(StandardCharsets.UTF_8.toString()); WebUtils.outJson(response, map); } } + } diff --git a/spring-boot-example/spring-video/src/main/java/com/livk/video/support/VideoResourceHttpRequestHandler.java b/spring-boot-example/spring-video/src/main/java/com/livk/video/support/VideoResourceHttpRequestHandler.java index 81e508773..c232f2be7 100644 --- a/spring-boot-example/spring-video/src/main/java/com/livk/video/support/VideoResourceHttpRequestHandler.java +++ b/spring-boot-example/spring-video/src/main/java/com/livk/video/support/VideoResourceHttpRequestHandler.java @@ -40,4 +40,5 @@ protected Resource getResource(HttpServletRequest request) { String location = (String) request.getAttribute(ATTR); return ResourceUtils.getResource(location); } + } diff --git a/spring-boot-example/spring-video/src/test/java/com/livk/video/controller/VideoControllerTest.java b/spring-boot-example/spring-video/src/test/java/com/livk/video/controller/VideoControllerTest.java index 8f2e7feab..16e83740f 100644 --- a/spring-boot-example/spring-video/src/test/java/com/livk/video/controller/VideoControllerTest.java +++ b/spring-boot-example/spring-video/src/test/java/com/livk/video/controller/VideoControllerTest.java @@ -47,14 +47,13 @@ class VideoControllerTest { @Test void testVideo() throws Exception { - mockMvc.perform(get("/video")) - .andExpect(status().isOk()) - .andDo(result -> { - ByteArrayInputStream in = new ByteArrayInputStream(result.getResponse().getContentAsByteArray()); - FileUtils.download(in, "./test.mp4"); - }); + mockMvc.perform(get("/video")).andExpect(status().isOk()).andDo(result -> { + ByteArrayInputStream in = new ByteArrayInputStream(result.getResponse().getContentAsByteArray()); + FileUtils.download(in, "./test.mp4"); + }); File video = new File("./test.mp4"); assertTrue(video.exists()); assertTrue(video.delete()); } + } diff --git a/spring-boot-example/spring-websocket/spring-websocket-chat/src/main/java/com/livk/socket/chat/WebSocketChatApp.java b/spring-boot-example/spring-websocket/spring-websocket-chat/src/main/java/com/livk/socket/chat/WebSocketChatApp.java index 06562eb3e..f68e87499 100644 --- a/spring-boot-example/spring-websocket/spring-websocket-chat/src/main/java/com/livk/socket/chat/WebSocketChatApp.java +++ b/spring-boot-example/spring-websocket/spring-websocket-chat/src/main/java/com/livk/socket/chat/WebSocketChatApp.java @@ -25,7 +25,9 @@ */ @SpringBootApplication public class WebSocketChatApp { + public static void main(String[] args) { SpringLauncher.run(args); } + } diff --git a/spring-boot-example/spring-websocket/spring-websocket-chat/src/main/java/com/livk/socket/chat/config/WebSocketConfig.java b/spring-boot-example/spring-websocket/spring-websocket-chat/src/main/java/com/livk/socket/chat/config/WebSocketConfig.java index a8de54f3a..bc8041b43 100644 --- a/spring-boot-example/spring-websocket/spring-websocket-chat/src/main/java/com/livk/socket/chat/config/WebSocketConfig.java +++ b/spring-boot-example/spring-websocket/spring-websocket-chat/src/main/java/com/livk/socket/chat/config/WebSocketConfig.java @@ -46,4 +46,5 @@ public void configureMessageBroker(MessageBrokerRegistry registry) { .setSystemLogin("admin") .setSystemPasscode("admin"); } + } diff --git a/spring-boot-example/spring-websocket/spring-websocket-chat/src/main/java/com/livk/socket/chat/config/WebSocketEventListener.java b/spring-boot-example/spring-websocket/spring-websocket-chat/src/main/java/com/livk/socket/chat/config/WebSocketEventListener.java index 4493746e3..efa947ae2 100644 --- a/spring-boot-example/spring-websocket/spring-websocket-chat/src/main/java/com/livk/socket/chat/config/WebSocketEventListener.java +++ b/spring-boot-example/spring-websocket/spring-websocket-chat/src/main/java/com/livk/socket/chat/config/WebSocketEventListener.java @@ -55,4 +55,5 @@ public void handleWebSocketDisconnectListener(SessionDisconnectEvent event) { messagingTemplate.convertAndSend("/topic/public", chatMessage); } } + } diff --git a/spring-boot-example/spring-websocket/spring-websocket-chat/src/main/java/com/livk/socket/chat/controller/ChatController.java b/spring-boot-example/spring-websocket/spring-websocket-chat/src/main/java/com/livk/socket/chat/controller/ChatController.java index 4ab4c3ab4..248428c3d 100644 --- a/spring-boot-example/spring-websocket/spring-websocket-chat/src/main/java/com/livk/socket/chat/controller/ChatController.java +++ b/spring-boot-example/spring-websocket/spring-websocket-chat/src/main/java/com/livk/socket/chat/controller/ChatController.java @@ -38,9 +38,9 @@ public ChatMessage sendMessage(@Payload ChatMessage chatMessage) { @MessageMapping("/chat/add-user") @SendTo("/topic/public") - public ChatMessage addUser(@Payload ChatMessage chatMessage, - SimpMessageHeaderAccessor headerAccessor) { + public ChatMessage addUser(@Payload ChatMessage chatMessage, SimpMessageHeaderAccessor headerAccessor) { headerAccessor.getSessionAttributes().put("username", chatMessage.getSender()); return chatMessage; } + } diff --git a/spring-boot-example/spring-websocket/spring-websocket-chat/src/main/java/com/livk/socket/chat/entity/ChatMessage.java b/spring-boot-example/spring-websocket/spring-websocket-chat/src/main/java/com/livk/socket/chat/entity/ChatMessage.java index cb2badf46..e319c4ac9 100644 --- a/spring-boot-example/spring-websocket/spring-websocket-chat/src/main/java/com/livk/socket/chat/entity/ChatMessage.java +++ b/spring-boot-example/spring-websocket/spring-websocket-chat/src/main/java/com/livk/socket/chat/entity/ChatMessage.java @@ -24,13 +24,17 @@ */ @Data public class ChatMessage { + private MessageType type; + private String content; + private String sender; public enum MessageType { - CHAT, - JOIN, - LEAVE + + CHAT, JOIN, LEAVE + } + } diff --git a/spring-boot-example/spring-websocket/spring-websocket-session/src/main/java/com/livk/socket/session/WebSocketClientTest.java b/spring-boot-example/spring-websocket/spring-websocket-session/src/main/java/com/livk/socket/session/WebSocketClientTest.java index 04f771744..8a909a972 100644 --- a/spring-boot-example/spring-websocket/spring-websocket-session/src/main/java/com/livk/socket/session/WebSocketClientTest.java +++ b/spring-boot-example/spring-websocket/spring-websocket-session/src/main/java/com/livk/socket/session/WebSocketClientTest.java @@ -75,7 +75,8 @@ public void run() { try { getClient(uri); countDownLatch.await(); - } catch (Exception e) { + } + catch (Exception e) { throw new RuntimeException(e); } } @@ -85,7 +86,8 @@ private void getClient(String uri) throws URISyntaxException { while (webSocketClient.getReadyState().ordinal() == 0) { try { Thread.sleep(200); - } catch (InterruptedException e) { + } + catch (InterruptedException e) { log.warn("延迟操作出现问题,但并不影响功能"); } log.info("连接中......."); @@ -97,4 +99,5 @@ private void getClient(String uri) throws URISyntaxException { log.info(uri + "连接失败......."); } } + } diff --git a/spring-boot-example/spring-websocket/spring-websocket-session/src/main/java/com/livk/socket/session/config/ServerConfigurator.java b/spring-boot-example/spring-websocket/spring-websocket-session/src/main/java/com/livk/socket/session/config/ServerConfigurator.java index dfd33ea82..6e9c8d703 100644 --- a/spring-boot-example/spring-websocket/spring-websocket-session/src/main/java/com/livk/socket/session/config/ServerConfigurator.java +++ b/spring-boot-example/spring-websocket/spring-websocket-session/src/main/java/com/livk/socket/session/config/ServerConfigurator.java @@ -37,13 +37,15 @@ public class ServerConfigurator extends ServerEndpointConfig.Configurator { @Override public boolean checkOrigin(String originHeaderValue) { - ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); + ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder + .getRequestAttributes(); Assert.notNull(servletRequestAttributes, "servletRequestAttributes not be null!"); HttpServletRequest request = servletRequestAttributes.getRequest(); String token = request.getHeader(HttpHeaders.AUTHORIZATION); if ("livk123".equals(token)) { return super.checkOrigin(originHeaderValue); - } else { + } + else { log.info("缺少参数!"); return false; } diff --git a/spring-boot-example/spring-websocket/spring-websocket-session/src/main/java/com/livk/socket/session/provider/WebSocketServer.java b/spring-boot-example/spring-websocket/spring-websocket-session/src/main/java/com/livk/socket/session/provider/WebSocketServer.java index 615bae431..84a25179f 100644 --- a/spring-boot-example/spring-websocket/spring-websocket-session/src/main/java/com/livk/socket/session/provider/WebSocketServer.java +++ b/spring-boot-example/spring-websocket/spring-websocket-session/src/main/java/com/livk/socket/session/provider/WebSocketServer.java @@ -50,14 +50,14 @@ public class WebSocketServer { /** * 异步推送消息 - * * @param message */ public static void sendWholeAsyncMessage(String message) { for (WebSocketServer item : websocketSet) { try { item.session.getAsyncRemote().sendText(message); - } catch (Exception e) { + } + catch (Exception e) { log.error("websocket异步发送消息异常{0}", e); } } @@ -73,10 +73,12 @@ public static void sendInfo(@PathParam("sid") String sid, String message) { // 这里可以设定只推送给这个sid的,为null则全部推送 if (sid == null) { item.sendMessage(message); - } else if (item.sid.equals(sid)) { + } + else if (item.sid.equals(sid)) { item.sendMessage(message); } - } catch (IOException e) { + } + catch (IOException e) { log.error("websocket 发送异常", e); } } @@ -105,7 +107,6 @@ public void onClose() { /** * 收到客户端消息后调用的方法 - * * @param message 客户端发送过来的消息 */ @OnMessage diff --git a/spring-boot-example/spring-websocket/spring-websocket-session/src/test/java/com/livk/socket/WebSocketClientTestTest.java b/spring-boot-example/spring-websocket/spring-websocket-session/src/test/java/com/livk/socket/WebSocketClientTestTest.java index 5fb36d3c4..fdd02480a 100644 --- a/spring-boot-example/spring-websocket/spring-websocket-session/src/test/java/com/livk/socket/WebSocketClientTestTest.java +++ b/spring-boot-example/spring-websocket/spring-websocket-session/src/test/java/com/livk/socket/WebSocketClientTestTest.java @@ -37,7 +37,7 @@ */ @Disabled("单独测试,性能损耗大") @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT, - useMainMethod = SpringBootTest.UseMainMethod.ALWAYS) + useMainMethod = SpringBootTest.UseMainMethod.ALWAYS) class WebSocketClientTestTest { @Test @@ -53,5 +53,5 @@ void testMain() { } assertEquals(0, countDownLatch.getCount()); } -} +} diff --git a/spring-boot-example/spring-zookeeper/zookeeper-lock/src/main/java/com/livk/zookeeper/LockController.java b/spring-boot-example/spring-zookeeper/zookeeper-lock/src/main/java/com/livk/zookeeper/LockController.java index aa4770e95..1f9e96246 100644 --- a/spring-boot-example/spring-zookeeper/zookeeper-lock/src/main/java/com/livk/zookeeper/LockController.java +++ b/spring-boot-example/spring-zookeeper/zookeeper-lock/src/main/java/com/livk/zookeeper/LockController.java @@ -46,15 +46,17 @@ public class LockController { public void lock(@RequestParam Integer id) throws InterruptedException { Lock lock = lockRegistry.obtain("zookeeper"); while (!lock.tryLock()) { - //获取不到锁直接空转 + // 获取不到锁直接空转 Thread.sleep(100); } try { log.info("{} is locked", id); Thread.sleep(1000); - } catch (InterruptedException ignored) { + } + catch (InterruptedException ignored) { - } finally { + } + finally { lock.unlock(); } } diff --git a/spring-boot-example/spring-zookeeper/zookeeper-lock/src/test/java/com/livk/zookeeper/LockControllerTest.java b/spring-boot-example/spring-zookeeper/zookeeper-lock/src/test/java/com/livk/zookeeper/LockControllerTest.java index 00c3dbf4d..6398ef61d 100644 --- a/spring-boot-example/spring-zookeeper/zookeeper-lock/src/test/java/com/livk/zookeeper/LockControllerTest.java +++ b/spring-boot-example/spring-zookeeper/zookeeper-lock/src/test/java/com/livk/zookeeper/LockControllerTest.java @@ -48,11 +48,10 @@ void lock() throws InterruptedException { String param = String.valueOf(i); service.submit(() -> { try { - mockMvc.perform(get("/lock") - .queryParam("id", param)) - .andExpect(status().isOk()); + mockMvc.perform(get("/lock").queryParam("id", param)).andExpect(status().isOk()); countDownLatch.countDown(); - } catch (Exception e) { + } + catch (Exception e) { throw new RuntimeException(e); } }); @@ -60,4 +59,5 @@ void lock() throws InterruptedException { countDownLatch.await(); service.shutdown(); } + } diff --git a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/curator/CuratorAutoConfiguration.java b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/curator/CuratorAutoConfiguration.java index edecb0675..60a86ff70 100644 --- a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/curator/CuratorAutoConfiguration.java +++ b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/curator/CuratorAutoConfiguration.java @@ -47,30 +47,27 @@ public class CuratorAutoConfiguration { /** * Curator framework curator framework. - * - * @param properties the properties - * @param retryPolicy the retry policy + * @param properties the properties + * @param retryPolicy the retry policy * @param curatorFrameworkBuilderCustomizers the curator framework builder customizers - * @param ensembleProviders the ensemble providers - * @param tracerDrivers the tracer drivers + * @param ensembleProviders the ensemble providers + * @param tracerDrivers the tracer drivers * @return the curator framework * @throws Exception the exception */ @Bean(destroyMethod = "close") @ConditionalOnMissingBean public CuratorFramework curatorFramework(CuratorProperties properties, RetryPolicy retryPolicy, - ObjectProvider curatorFrameworkBuilderCustomizers, - ObjectProvider ensembleProviders, - ObjectProvider tracerDrivers) throws Exception { + ObjectProvider curatorFrameworkBuilderCustomizers, + ObjectProvider ensembleProviders, ObjectProvider tracerDrivers) + throws Exception { return CuratorFactory.curatorFramework(properties, retryPolicy, - curatorFrameworkBuilderCustomizers::orderedStream, - ensembleProviders::getIfAvailable, - tracerDrivers::getIfAvailable); + curatorFrameworkBuilderCustomizers::orderedStream, ensembleProviders::getIfAvailable, + tracerDrivers::getIfAvailable); } /** * Exponential backoff retry policy. - * * @param properties the properties * @return the retry policy */ @@ -82,7 +79,6 @@ public RetryPolicy exponentialBackoffRetry(CuratorProperties properties) { /** * Curator template curator template. - * * @param curatorFramework the curator framework * @return the curator template */ @@ -91,4 +87,5 @@ public RetryPolicy exponentialBackoffRetry(CuratorProperties properties) { public CuratorTemplate curatorTemplate(CuratorFramework curatorFramework) { return new CuratorTemplate(curatorFramework); } + } diff --git a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/curator/CuratorFactory.java b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/curator/CuratorFactory.java index 223aeb4e7..c4659c307 100644 --- a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/curator/CuratorFactory.java +++ b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/curator/CuratorFactory.java @@ -21,31 +21,31 @@ public abstract class CuratorFactory { /** * Curator framework - * - * @param properties the properties - * @param retryPolicy the retry policy - * @param optionalCuratorFrameworkCustomizerProvider the optional curator framework customizer provider - * @param optionalEnsembleProvider the optional ensemble provider - * @param optionalTracerDriverProvider the optional tracer driver provider + * @param properties the properties + * @param retryPolicy the retry policy + * @param optionalCuratorFrameworkCustomizerProvider the optional curator framework + * customizer provider + * @param optionalEnsembleProvider the optional ensemble provider + * @param optionalTracerDriverProvider the optional tracer driver provider * @return the curator framework * @throws Exception the exception */ - public static CuratorFramework curatorFramework(CuratorProperties properties, - RetryPolicy retryPolicy, - Supplier> optionalCuratorFrameworkCustomizerProvider, - Supplier optionalEnsembleProvider, - Supplier optionalTracerDriverProvider) - throws Exception { + public static CuratorFramework curatorFramework(CuratorProperties properties, RetryPolicy retryPolicy, + Supplier> optionalCuratorFrameworkCustomizerProvider, + Supplier optionalEnsembleProvider, Supplier optionalTracerDriverProvider) + throws Exception { CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder(); EnsembleProvider ensembleProvider = optionalEnsembleProvider.get(); if (ensembleProvider != null) { builder.ensembleProvider(ensembleProvider); - } else { + } + else { builder.connectString(properties.getConnectString()); } builder.sessionTimeoutMs((int) properties.getSessionTimeout().toMillis()) - .connectionTimeoutMs((int) properties.getConnectionTimeout().toMillis()).retryPolicy(retryPolicy); + .connectionTimeoutMs((int) properties.getConnectionTimeout().toMillis()) + .retryPolicy(retryPolicy); Stream customizers = optionalCuratorFrameworkCustomizerProvider.get(); if (customizers != null) { @@ -61,7 +61,7 @@ public static CuratorFramework curatorFramework(CuratorProperties properties, curator.start(); if (log.isTraceEnabled()) { log.trace("blocking until connected to zookeeper for " + properties.getBlockUntilConnectedWait() - + properties.getBlockUntilConnectedUnit()); + + properties.getBlockUntilConnectedUnit()); } curator.blockUntilConnected(properties.getBlockUntilConnectedWait(), properties.getBlockUntilConnectedUnit()); if (log.isTraceEnabled()) { @@ -72,12 +72,12 @@ public static CuratorFramework curatorFramework(CuratorProperties properties, /** * Retry policy retry policy. - * * @param properties the properties * @return the retry policy */ public static RetryPolicy retryPolicy(CuratorProperties properties) { return new ExponentialBackoffRetry(properties.getBaseSleepTimeMs(), properties.getMaxRetries(), - properties.getMaxSleepMs()); + properties.getMaxSleepMs()); } + } diff --git a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/curator/CuratorFrameworkBuilderCustomizer.java b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/curator/CuratorFrameworkBuilderCustomizer.java index 2cebf6ead..5a73c7807 100644 --- a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/curator/CuratorFrameworkBuilderCustomizer.java +++ b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/curator/CuratorFrameworkBuilderCustomizer.java @@ -29,4 +29,5 @@ */ @FunctionalInterface public interface CuratorFrameworkBuilderCustomizer extends Customizer { + } diff --git a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/curator/actuator/CuratorHealthContributorAutoConfiguration.java b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/curator/actuator/CuratorHealthContributorAutoConfiguration.java index a5ca8429e..601cabd96 100644 --- a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/curator/actuator/CuratorHealthContributorAutoConfiguration.java +++ b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/curator/actuator/CuratorHealthContributorAutoConfiguration.java @@ -38,12 +38,12 @@ * @author livk */ @SpringAutoService -@AutoConfiguration(after = {CuratorAutoConfiguration.class}) -@ConditionalOnClass({CuratorFramework.class, HealthIndicator.class}) +@AutoConfiguration(after = { CuratorAutoConfiguration.class }) +@ConditionalOnClass({ CuratorFramework.class, HealthIndicator.class }) @ConditionalOnBean(CuratorFramework.class) @ConditionalOnEnabledHealthIndicator("curator") public class CuratorHealthContributorAutoConfiguration - extends CompositeHealthContributorConfiguration { + extends CompositeHealthContributorConfiguration { /** * Instantiates a new Curator health contributor auto configuration. @@ -54,13 +54,13 @@ public CuratorHealthContributorAutoConfiguration() { /** * Curator health contributor health contributor. - * * @param curatorFrameworkFactories the curator framework factories * @return the health contributor */ @Bean - @ConditionalOnMissingBean(name = {"curatorHealthIndicator", "curatorHealthContributor"}) + @ConditionalOnMissingBean(name = { "curatorHealthIndicator", "curatorHealthContributor" }) public HealthContributor curatorHealthContributor(Map curatorFrameworkFactories) { return createContributor(curatorFrameworkFactories); } + } diff --git a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/curator/actuator/CuratorHealthIndicator.java b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/curator/actuator/CuratorHealthIndicator.java index 7d6b90626..c4a82d036 100644 --- a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/curator/actuator/CuratorHealthIndicator.java +++ b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/curator/actuator/CuratorHealthIndicator.java @@ -37,15 +37,19 @@ protected void doHealthCheck(Health.Builder builder) { CuratorFrameworkState state = curatorFramework.getState(); if (state != CuratorFrameworkState.STARTED) { builder.down().withDetail("error", "Client not started"); - } else if (curatorFramework.checkExists().forPath("/") == null) { + } + else if (curatorFramework.checkExists().forPath("/") == null) { builder.down().withDetail("error", "Root for namespace does not exist"); - } else { + } + else { builder.up(); } builder.withDetail("connectionString", curatorFramework.getZookeeperClient().getCurrentConnectionString()) .withDetail("state", state); - } catch (Exception e) { + } + catch (Exception e) { builder.down(e); } } + } diff --git a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/dynamic/DynamicAutoConfiguration.java b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/dynamic/DynamicAutoConfiguration.java index 6064ad5eb..502017830 100644 --- a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/dynamic/DynamicAutoConfiguration.java +++ b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/dynamic/DynamicAutoConfiguration.java @@ -42,7 +42,6 @@ public class DynamicAutoConfiguration { /** * Dynamic datasource dynamic datasource. - * * @param datasourceProperties the datasource properties * @return the dynamic datasource */ @@ -51,7 +50,8 @@ public DynamicDatasource dynamicDatasource(DynamicDatasourceProperties datasourc Map datasourceMap = datasourceProperties.getDatasource() .entrySet() .stream() - .collect(Collectors.toMap(Map.Entry::getKey, entry -> entry.getValue().initializeDataSourceBuilder().build())); + .collect(Collectors.toMap(Map.Entry::getKey, + entry -> entry.getValue().initializeDataSourceBuilder().build())); DynamicDatasource dynamicDatasource = new DynamicDatasource(); dynamicDatasource.setTargetDataSources(datasourceMap); dynamicDatasource.setDefaultTargetDataSource(datasourceMap.get(datasourceProperties.getPrimary())); @@ -60,11 +60,11 @@ public DynamicDatasource dynamicDatasource(DynamicDatasourceProperties datasourc /** * Data source interceptor data source interceptor. - * * @return the data source interceptor */ @Bean public DataSourceInterceptor dataSourceInterceptor() { return new DataSourceInterceptor(); } + } diff --git a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/dynamic/DynamicDatasourceProperties.java b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/dynamic/DynamicDatasourceProperties.java index 1b90116df..09e7163fd 100644 --- a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/dynamic/DynamicDatasourceProperties.java +++ b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/dynamic/DynamicDatasourceProperties.java @@ -54,9 +54,11 @@ public void afterPropertiesSet() { if (!datasource.containsKey(primary)) { throw new PrimaryNotFountException(primary + "数据源不存在!\n当前数据源:" + datasource.keySet()); } - } else { + } + else { throw new PrimaryNotFountException("缺少primary数据源!"); } log.info("当前主数据源:" + primary); } + } diff --git a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/dynamic/EnableDynamicDatasource.java b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/dynamic/EnableDynamicDatasource.java index 1c41b22f2..096169612 100644 --- a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/dynamic/EnableDynamicDatasource.java +++ b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/dynamic/EnableDynamicDatasource.java @@ -33,6 +33,7 @@ */ @AutoImport @Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.TYPE}) +@Target({ ElementType.TYPE }) public @interface EnableDynamicDatasource { + } diff --git a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/dynamic/exception/PrimaryNotFountException.java b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/dynamic/exception/PrimaryNotFountException.java index 25885647d..1d227962e 100644 --- a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/dynamic/exception/PrimaryNotFountException.java +++ b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/dynamic/exception/PrimaryNotFountException.java @@ -31,7 +31,6 @@ public PrimaryNotFountException() { /** * Instantiates a new Primary not fount exception. - * * @param message the message */ public PrimaryNotFountException(String message) { @@ -40,9 +39,8 @@ public PrimaryNotFountException(String message) { /** * Instantiates a new Primary not fount exception. - * * @param message the message - * @param cause the cause + * @param cause the cause */ public PrimaryNotFountException(String message, Throwable cause) { super(message, cause); @@ -50,7 +48,6 @@ public PrimaryNotFountException(String message, Throwable cause) { /** * Instantiates a new Primary not fount exception. - * * @param cause the cause */ public PrimaryNotFountException(Throwable cause) { @@ -59,14 +56,13 @@ public PrimaryNotFountException(Throwable cause) { /** * Instantiates a new Primary not fount exception. - * - * @param message the message - * @param cause the cause - * @param enableSuppression the enable suppression + * @param message the message + * @param cause the cause + * @param enableSuppression the enable suppression * @param writableStackTrace the writable stack trace */ protected PrimaryNotFountException(String message, Throwable cause, boolean enableSuppression, - boolean writableStackTrace) { + boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } diff --git a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/easyexcel/ExcelAutoConfiguration.java b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/easyexcel/ExcelAutoConfiguration.java index 17b7ea28e..49df82933 100644 --- a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/easyexcel/ExcelAutoConfiguration.java +++ b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/easyexcel/ExcelAutoConfiguration.java @@ -53,6 +53,7 @@ public class ExcelAutoConfiguration { @AutoConfiguration @ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET) public static class ExcelWebMvcAutoConfiguration implements WebMvcConfigurer { + @Override public void addArgumentResolvers(List resolvers) { resolvers.add(new ExcelMethodArgumentResolver()); @@ -62,6 +63,7 @@ public void addArgumentResolvers(List resolvers) public void addReturnValueHandlers(List handlers) { handlers.add(new ExcelMethodReturnValueHandler()); } + } /** @@ -72,8 +74,8 @@ public void addReturnValueHandlers(List handler public static class ExcelWebFluxAutoConfiguration implements WebFluxConfigurer { /** - * Reactive excel method return value handler reactive excel method return value handler. - * + * Reactive excel method return value handler reactive excel method return value + * handler. * @return the reactive excel method return value handler */ @Bean @@ -85,5 +87,7 @@ public ReactiveExcelMethodReturnValueHandler reactiveExcelMethodReturnValueHandl public void configureArgumentResolvers(ArgumentResolverConfigurer configurer) { configurer.addCustomResolver(new ReactiveExcelMethodArgumentResolver()); } + } + } diff --git a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/http/ClassPathHttpScanner.java b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/http/ClassPathHttpScanner.java index 9494f3637..30ff6e521 100644 --- a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/http/ClassPathHttpScanner.java +++ b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/http/ClassPathHttpScanner.java @@ -48,8 +48,7 @@ public class ClassPathHttpScanner extends ClassPathBeanDefinitionScanner { /** * Instantiates a new Class path http scanner. - * - * @param registry the registry + * @param registry the registry * @param environment the environment */ public ClassPathHttpScanner(BeanDefinitionRegistry registry, Environment environment) { @@ -58,7 +57,6 @@ public ClassPathHttpScanner(BeanDefinitionRegistry registry, Environment environ /** * Register filters. - * * @param annotationType the annotation type */ public void registerFilters(Class annotationType) { @@ -98,4 +96,5 @@ protected Set doScan(@NonNull String... basePackages) { } return beanDefinitions; } + } diff --git a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/http/HttpInterfaceAutoConfiguration.java b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/http/HttpInterfaceAutoConfiguration.java index 197a98003..030afd026 100644 --- a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/http/HttpInterfaceAutoConfiguration.java +++ b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/http/HttpInterfaceAutoConfiguration.java @@ -50,7 +50,6 @@ public class HttpInterfaceAutoConfiguration { /** * Web client web client. - * * @param builder the builder * @return the web client */ @@ -62,22 +61,21 @@ public WebClient webClient(WebClient.Builder builder) { /** * Http service proxy factory http service proxy factory. - * - * @param webClient the web client + * @param webClient the web client * @param customizers the customizers * @return the http service proxy factory */ @Bean public HttpServiceProxyFactory httpServiceProxyFactory(WebClient webClient, - ObjectProvider customizers) { - HttpServiceProxyFactory.Builder builder = HttpServiceProxyFactory.builder(WebClientAdapter.forClient(webClient)); + ObjectProvider customizers) { + HttpServiceProxyFactory.Builder builder = HttpServiceProxyFactory + .builder(WebClientAdapter.forClient(webClient)); customizers.orderedStream().forEach(customizer -> customizer.customize(builder)); return builder.build(); } /** * 添加SpringEL解析 - * * @param beanFactory bean factory * @return HttpServiceProxyFactoryCustomizer */ @@ -85,4 +83,5 @@ public HttpServiceProxyFactory httpServiceProxyFactory(WebClient webClient, public HttpServiceProxyFactoryCustomizer embeddedValueResolverCustomizer(ConfigurableBeanFactory beanFactory) { return builder -> builder.embeddedValueResolver(new EmbeddedValueResolver(beanFactory)); } + } diff --git a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/http/annotation/HttpProvider.java b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/http/annotation/HttpProvider.java index 10a5106bf..f8e953506 100644 --- a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/http/annotation/HttpProvider.java +++ b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/http/annotation/HttpProvider.java @@ -34,27 +34,26 @@ * @author livk * @see HttpExchange */ -@Target({ElementType.TYPE}) +@Target({ ElementType.TYPE }) @Retention(RetentionPolicy.RUNTIME) @Component @HttpExchange public @interface HttpProvider { /** - * The value may indicate a suggestion for a logical component name, - * to be turned into a Spring bean in case of an autodetected component. - * + * The value may indicate a suggestion for a logical component name, to be turned into + * a Spring bean in case of an autodetected component. * @return the suggested component name, if any (or empty String otherwise) */ @AliasFor(annotation = Component.class, attribute = "value") String value() default ""; /** - * The URL for the request, either a full URL or a path only that is relative - * to a URL declared in a type-level {@code @HttpExchange}, and/or a globally - * configured base URL. - *

By default, this is empty. - * + * The URL for the request, either a full URL or a path only that is relative to a URL + * declared in a type-level {@code @HttpExchange}, and/or a globally configured base + * URL. + *

+ * By default, this is empty. * @return http url */ @AliasFor(annotation = HttpExchange.class, attribute = "url") @@ -62,10 +61,11 @@ /** * The HTTP method to use. - *

Supported at the type level as well as at the method level. - * When used at the type level, all method-level mappings inherit this value. - *

By default, this is empty. - * + *

+ * Supported at the type level as well as at the method level. When used at the type + * level, all method-level mappings inherit this value. + *

+ * By default, this is empty. * @return http method */ @AliasFor(annotation = HttpExchange.class, attribute = "method") @@ -73,10 +73,11 @@ /** * The media type for the {@code "Content-Type"} header. - *

Supported at the type level as well as at the method level, in which - * case the method-level values override type-level values. - *

By default, this is empty. - * + *

+ * Supported at the type level as well as at the method level, in which case the + * method-level values override type-level values. + *

+ * By default, this is empty. * @return http contentType */ @AliasFor(annotation = HttpExchange.class, attribute = "contentType") @@ -84,12 +85,14 @@ /** * The media types for the {@code "Accept"} header. - *

Supported at the type level as well as at the method level, in which - * case the method-level values override type-level values. - *

By default, this is empty. - * + *

+ * Supported at the type level as well as at the method level, in which case the + * method-level values override type-level values. + *

+ * By default, this is empty. * @return http accept */ @AliasFor(annotation = HttpExchange.class, attribute = "accept") String[] accept() default {}; + } diff --git a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/http/factory/HttpFactoryBean.java b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/http/factory/HttpFactoryBean.java index 64310aecc..176169a04 100644 --- a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/http/factory/HttpFactoryBean.java +++ b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/http/factory/HttpFactoryBean.java @@ -36,12 +36,10 @@ public class HttpFactoryBean implements FactoryBean, BeanFactoryAware { private BeanFactory beanFactory; - private Class type; /** * Sets type. - * * @param httpInterfaceTypeName the http interface type name */ public void setType(String httpInterfaceTypeName) { @@ -63,4 +61,5 @@ public Class getObjectType() { public void setBeanFactory(@NonNull BeanFactory beanFactory) throws BeansException { this.beanFactory = beanFactory; } + } diff --git a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/http/factory/HttpServiceRegistrar.java b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/http/factory/HttpServiceRegistrar.java index 09f2ab696..66cfa2fc4 100644 --- a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/http/factory/HttpServiceRegistrar.java +++ b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/http/factory/HttpServiceRegistrar.java @@ -47,7 +47,7 @@ public class HttpServiceRegistrar implements ImportBeanDefinitionRegistrar { @Override public void registerBeanDefinitions(@NonNull AnnotationMetadata importingClassMetadata, - @NonNull BeanDefinitionRegistry registry) { + @NonNull BeanDefinitionRegistry registry) { List packages = AutoConfigurationPackages.get(beanFactory); ClassPathHttpScanner scanner = new ClassPathHttpScanner(registry, environment); scanner.registerFilters(HttpProvider.class); diff --git a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/ip2region/Ip2RegionProperties.java b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/ip2region/Ip2RegionProperties.java index ce4d68522..4fa9b8a38 100644 --- a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/ip2region/Ip2RegionProperties.java +++ b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/ip2region/Ip2RegionProperties.java @@ -44,10 +44,10 @@ public class Ip2RegionProperties { /** * Get file resource resource [ ]. - * * @return the resource [ ] */ public Resource getFileResource() { return ResourceUtils.getResource(filePath); } + } diff --git a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/ip2region/Ip2regionAutoConfiguration.java b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/ip2region/Ip2regionAutoConfiguration.java index 3ab3b4562..6da5afdb7 100644 --- a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/ip2region/Ip2regionAutoConfiguration.java +++ b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/ip2region/Ip2regionAutoConfiguration.java @@ -49,7 +49,6 @@ public class Ip2regionAutoConfiguration { /** * Ip 2 region search ip 2 region search. - * * @param properties the properties * @return the ip 2 region search */ @@ -64,7 +63,6 @@ public Ip2RegionSearch ip2RegionSearch(Ip2RegionProperties properties) { /** * Request ip bean factory processor request ip bean factory processor. - * * @return the request ip bean factory processor */ @Bean @@ -89,7 +87,6 @@ public void addArgumentResolvers(List resolvers) /** * Ip filter filter registration bean filter registration bean. - * * @return the filter registration bean */ @Bean @@ -101,5 +98,7 @@ public FilterRegistrationBean ipFilterFilterRegistrationBean() registrationBean.setOrder(1); return registrationBean; } + } + } diff --git a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/limit/EnableLimit.java b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/limit/EnableLimit.java index 701e4c2a3..6d39f4aaa 100644 --- a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/limit/EnableLimit.java +++ b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/limit/EnableLimit.java @@ -32,5 +32,4 @@ @Retention(RetentionPolicy.RUNTIME) public @interface EnableLimit { - } diff --git a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/limit/LimitAutoConfiguration.java b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/limit/LimitAutoConfiguration.java index 3db7b5878..40bdf598d 100644 --- a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/limit/LimitAutoConfiguration.java +++ b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/limit/LimitAutoConfiguration.java @@ -40,7 +40,6 @@ public class LimitAutoConfiguration { /** * Limit interceptor limit interceptor. - * * @param provider the provider * @return the limit interceptor */ @@ -53,12 +52,12 @@ public LimitInterceptor limitInterceptor(ObjectProvider provider) * The type Redisson limit configuration. */ @ConditionalOnClass(RedissonClient.class) - @AutoConfiguration(after = {RedissonAutoConfiguration.class}, - afterName = {"org.redisson.spring.starter.RedissonAutoConfiguration"}) + @AutoConfiguration(after = { RedissonAutoConfiguration.class }, + afterName = { "org.redisson.spring.starter.RedissonAutoConfiguration" }) public static class RedissonLimitConfiguration { + /** * Redisson limit executor limit executor. - * * @param redissonClient the redisson client * @return the limit executor */ @@ -67,5 +66,7 @@ public static class RedissonLimitConfiguration { public LimitExecutor redissonLimitExecutor(RedissonClient redissonClient) { return new RedissonLimitExecutor(redissonClient); } + } + } diff --git a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/lock/LockAutoConfiguration.java b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/lock/LockAutoConfiguration.java index 26a28aeb7..7c1796c5d 100644 --- a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/lock/LockAutoConfiguration.java +++ b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/lock/LockAutoConfiguration.java @@ -47,7 +47,6 @@ public class LockAutoConfiguration { /** * Lock aspect lock aspect. - * * @param distributedLockProvider the distributed lock provider * @return the lock aspect */ @@ -59,7 +58,6 @@ public LockInterceptor lockInterceptor(ObjectProvider distribut /** * Local lock distributed lock. - * * @return the distributed lock */ @Bean @@ -72,11 +70,11 @@ public DistributedLock localLock() { */ @ConditionalOnClass(RedissonClient.class) @AutoConfiguration(after = RedissonAutoConfiguration.class, - afterName = {"org.redisson.spring.starter.RedissonAutoConfiguration"}) + afterName = { "org.redisson.spring.starter.RedissonAutoConfiguration" }) public static class RedissonLockAutoConfiguration { + /** * Redisson lock distributed lock. - * * @param redissonClient the redisson client * @return the distributed lock */ @@ -84,6 +82,7 @@ public static class RedissonLockAutoConfiguration { public DistributedLock redissonLock(RedissonClient redissonClient) { return new RedissonLock(redissonClient); } + } /** @@ -92,9 +91,9 @@ public DistributedLock redissonLock(RedissonClient redissonClient) { @ConditionalOnClass(CuratorFramework.class) @AutoConfiguration(after = CuratorAutoConfiguration.class) public static class CuratorLockAutoConfiguration { + /** * Redisson lock distributed lock. - * * @param curatorFramework the curator framework * @return the distributed lock */ @@ -102,5 +101,7 @@ public static class CuratorLockAutoConfiguration { public DistributedLock redissonLock(CuratorFramework curatorFramework) { return new CuratorLock(curatorFramework); } + } + } diff --git a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/mapstruct/MapstructAutoConfiguration.java b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/mapstruct/MapstructAutoConfiguration.java index daa0b711c..8cf78d4ae 100644 --- a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/mapstruct/MapstructAutoConfiguration.java +++ b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/mapstruct/MapstructAutoConfiguration.java @@ -43,7 +43,6 @@ public class MapstructAutoConfiguration { /** * Generic mapstruct service generic mapstruct service. - * * @param repository the repository * @return the generic mapstruct service */ @@ -54,7 +53,6 @@ public GenericMapstructService genericMapstructService(ConverterRepository repos /** * Converter repository converter repository. - * * @return the converter repository */ @Bean @@ -65,7 +63,6 @@ public ConverterRepository converterRepository() { /** * Spring mapstruct locator mapstruct locator. - * * @return the mapstruct locator */ @Bean diff --git a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/mybatisplugins/inject/SqlDataInjectionAutoConfiguration.java b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/mybatisplugins/inject/SqlDataInjectionAutoConfiguration.java index dbbefdfad..e0a9f67a0 100644 --- a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/mybatisplugins/inject/SqlDataInjectionAutoConfiguration.java +++ b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/mybatisplugins/inject/SqlDataInjectionAutoConfiguration.java @@ -36,16 +36,16 @@ */ @SpringAutoService(EnableSqlPlugin.class) @AutoConfiguration(before = MybatisAutoConfiguration.class) -@ConditionalOnClass({SqlSessionFactory.class, SqlSessionFactoryBean.class}) +@ConditionalOnClass({ SqlSessionFactory.class, SqlSessionFactoryBean.class }) public class SqlDataInjectionAutoConfiguration { /** * Sql data injection configuration customizer configuration customizer. - * * @return the configuration customizer */ @Bean public ConfigurationCustomizer sqlDataInjectionConfigurationCustomizer() { return configuration -> configuration.addInterceptor(new SqlDataInjection()); } + } diff --git a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/mybatisplugins/monitor/MybatisLogMonitorAutoConfiguration.java b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/mybatisplugins/monitor/MybatisLogMonitorAutoConfiguration.java index b230b5708..88192f4aa 100644 --- a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/mybatisplugins/monitor/MybatisLogMonitorAutoConfiguration.java +++ b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/mybatisplugins/monitor/MybatisLogMonitorAutoConfiguration.java @@ -39,20 +39,20 @@ @SpringAutoService(EnableSqlMonitor.class) @AutoConfiguration(before = MybatisAutoConfiguration.class) @EnableConfigurationProperties(MybatisLogMonitorProperties.class) -@ConditionalOnClass({SqlSessionFactory.class, SqlSessionFactoryBean.class}) +@ConditionalOnClass({ SqlSessionFactory.class, SqlSessionFactoryBean.class }) public class MybatisLogMonitorAutoConfiguration { /** * Mybatis log monitor configuration customizer configuration customizer. - * * @param monitorProperties the properties * @return the configuration customizer */ @Bean - public ConfigurationCustomizer mybatisLogMonitorConfigurationCustomizer(MybatisLogMonitorProperties monitorProperties) { + public ConfigurationCustomizer mybatisLogMonitorConfigurationCustomizer( + MybatisLogMonitorProperties monitorProperties) { MybatisLogMonitor logMonitor = new MybatisLogMonitor(); logMonitor.setProperties(monitorProperties.properties()); - return configuration -> - configuration.addInterceptor(logMonitor); + return configuration -> configuration.addInterceptor(logMonitor); } + } diff --git a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/mybatisplugins/monitor/MybatisLogMonitorProperties.java b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/mybatisplugins/monitor/MybatisLogMonitorProperties.java index 018b3f5ac..b3a1eceb4 100644 --- a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/mybatisplugins/monitor/MybatisLogMonitorProperties.java +++ b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/mybatisplugins/monitor/MybatisLogMonitorProperties.java @@ -46,7 +46,6 @@ public class MybatisLogMonitorProperties { /** * Time out name string. - * * @return the string */ public static String timeOutName() { @@ -55,7 +54,6 @@ public static String timeOutName() { /** * Unit name string. - * * @return the string */ public static String unitName() { @@ -64,7 +62,6 @@ public static String unitName() { /** * Properties properties. - * * @return the properties */ public Properties properties() { @@ -73,4 +70,5 @@ public Properties properties() { properties.put(unitName(), unit); return properties; } + } diff --git a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/mybatisplugins/monitor/annotation/EnableSqlMonitor.java b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/mybatisplugins/monitor/annotation/EnableSqlMonitor.java index 236743aa3..0b24cc75e 100644 --- a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/mybatisplugins/monitor/annotation/EnableSqlMonitor.java +++ b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/mybatisplugins/monitor/annotation/EnableSqlMonitor.java @@ -35,4 +35,5 @@ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface EnableSqlMonitor { + } diff --git a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/mybatisplugins/monitor/event/MonitorSQLTimeOutEvent.java b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/mybatisplugins/monitor/event/MonitorSQLTimeOutEvent.java index b1583826b..c88e6d1b4 100644 --- a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/mybatisplugins/monitor/event/MonitorSQLTimeOutEvent.java +++ b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/mybatisplugins/monitor/event/MonitorSQLTimeOutEvent.java @@ -25,9 +25,9 @@ * @author livk */ public class MonitorSQLTimeOutEvent extends ApplicationEvent { + /** * Instantiates a new Monitor sql time out event. - * * @param source the source */ public MonitorSQLTimeOutEvent(MonitorSQLInfo source) { @@ -36,10 +36,10 @@ public MonitorSQLTimeOutEvent(MonitorSQLInfo source) { /** * Info monitor sql info. - * * @return the monitor sql info */ public MonitorSQLInfo info() { return (MonitorSQLInfo) source; } + } diff --git a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/mybatisplugins/monitor/interceptor/MybatisLogMonitor.java b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/mybatisplugins/monitor/interceptor/MybatisLogMonitor.java index cfbaa3ed5..b9d8da140 100644 --- a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/mybatisplugins/monitor/interceptor/MybatisLogMonitor.java +++ b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/mybatisplugins/monitor/interceptor/MybatisLogMonitor.java @@ -43,12 +43,7 @@ */ @Slf4j @Intercepts({ - @Signature( - type = StatementHandler.class, - method = "prepare", - args = {Connection.class, Integer.class} - ) -}) + @Signature(type = StatementHandler.class, method = "prepare", args = { Connection.class, Integer.class }) }) @RequiredArgsConstructor public class MybatisLogMonitor implements Interceptor { @@ -74,9 +69,8 @@ public void setProperties(Properties properties) { } private long timeOut() { - return ((ChronoUnit) properties.get(MybatisLogMonitorProperties.unitName())) - .getDuration() - .toMillis() * - (Long) properties.get(MybatisLogMonitorProperties.timeOutName()); + return ((ChronoUnit) properties.get(MybatisLogMonitorProperties.unitName())).getDuration().toMillis() + * (Long) properties.get(MybatisLogMonitorProperties.timeOutName()); } + } diff --git a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/mybatisplugins/type/MybatisTypeHandlerAutoConfiguration.java b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/mybatisplugins/type/MybatisTypeHandlerAutoConfiguration.java index b096772dc..308ffa572 100644 --- a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/mybatisplugins/type/MybatisTypeHandlerAutoConfiguration.java +++ b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/mybatisplugins/type/MybatisTypeHandlerAutoConfiguration.java @@ -39,12 +39,11 @@ */ @SpringAutoService @AutoConfiguration -@ConditionalOnClass({SqlSessionFactory.class, SqlSessionFactoryBean.class}) +@ConditionalOnClass({ SqlSessionFactory.class, SqlSessionFactoryBean.class }) public class MybatisTypeHandlerAutoConfiguration { /** * Mysql configuration customizer. - * * @param mapperProvider the mapper provider * @return the configuration customizer */ @@ -55,10 +54,8 @@ public ConfigurationCustomizer mysqlConfigurationCustomizer(ObjectProvider configuration.getTypeHandlerRegistry().register(new MysqlJsonTypeHandler(mapper)); } - /** * Postgresql configuration customizer. - * * @param mapperProvider the mapper provider * @return the configuration customizer */ @@ -68,4 +65,5 @@ public ConfigurationCustomizer postgresqlConfigurationCustomizer(ObjectProvider< ObjectMapper mapper = mapperProvider.getIfUnique(JsonMapper::new); return configuration -> configuration.getTypeHandlerRegistry().register(new PostgresJsonTypeHandler(mapper)); } + } diff --git a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/oss/OSSAutoConfiguration.java b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/oss/OSSAutoConfiguration.java index 9fff05626..b36ea856d 100644 --- a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/oss/OSSAutoConfiguration.java +++ b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/oss/OSSAutoConfiguration.java @@ -42,7 +42,6 @@ public class OSSAutoConfiguration { /** * Oss template oss template. - * * @param abstractService the abstract service * @return the oss template */ @@ -62,7 +61,6 @@ public static class MinioOSSAutoConfiguration { /** * Minio service minio service. - * * @return the minio service */ @Bean(destroyMethod = "close") @@ -70,6 +68,7 @@ public static class MinioOSSAutoConfiguration { public MinioService minioService() { return new MinioService(); } + } /** @@ -81,7 +80,6 @@ public static class AliyunOSSAutoConfiguration { /** * Minio service minio service. - * * @return the minio service */ @Bean(destroyMethod = "close") @@ -89,5 +87,7 @@ public static class AliyunOSSAutoConfiguration { public AliyunOSSService aliyunOSSService() { return new AliyunOSSService(); } + } + } diff --git a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/oss/OSSProperties.java b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/oss/OSSProperties.java index 3045038c0..986710fd7 100644 --- a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/oss/OSSProperties.java +++ b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/oss/OSSProperties.java @@ -33,6 +33,7 @@ @Data @ConfigurationProperties(OSSProperties.PREFIX) public class OSSProperties { + /** * The constant PREFIX. */ @@ -50,16 +51,13 @@ public class OSSProperties { /** * Instantiates a new Oss properties. - * - * @param url the url + * @param url the url * @param accessKey the access key * @param secretKey the secret key - * @param region the region + * @param region the region */ - public OSSProperties(@Name("url") URI url, - @Name("accessKey") String accessKey, - @Name("secretKey") String secretKey, - @Name("region") String region) { + public OSSProperties(@Name("url") URI url, @Name("accessKey") String accessKey, @Name("secretKey") String secretKey, + @Name("region") String region) { Assert.notNull(url, "url not be blank"); Assert.hasText(accessKey, "accessKey not be blank"); Assert.hasText(secretKey, "secretKey not be blank"); @@ -72,7 +70,6 @@ public OSSProperties(@Name("url") URI url, /** * Endpoint string. - * * @return the string */ private String endpoint(URI url) { @@ -81,7 +78,6 @@ private String endpoint(URI url) { /** * Gets prefix. - * * @return the prefix */ private String prefix(URI uri) { @@ -91,4 +87,5 @@ private String prefix(URI uri) { } throw new RuntimeException("url缺少前缀!"); } + } diff --git a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/oss/client/OSSClientFactory.java b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/oss/client/OSSClientFactory.java index 51444c498..145036ae1 100644 --- a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/oss/client/OSSClientFactory.java +++ b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/oss/client/OSSClientFactory.java @@ -27,19 +27,18 @@ public interface OSSClientFactory { /** * Instance t. - * - * @param endpoint the endpoint + * @param endpoint the endpoint * @param accessKey the access key * @param secretKey the secret key - * @param region the region + * @param region the region * @return the t */ T instance(String endpoint, String accessKey, String secretKey, String region); /** * Prefix string. - * * @return the string */ String name(); + } diff --git a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/oss/client/OSSClientFactoryLoader.java b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/oss/client/OSSClientFactoryLoader.java index 3f1a4288c..39839436a 100644 --- a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/oss/client/OSSClientFactoryLoader.java +++ b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/oss/client/OSSClientFactoryLoader.java @@ -26,10 +26,10 @@ public interface OSSClientFactoryLoader { /** * Loader oss client factory. - * - * @param the type parameter + * @param the type parameter * @param prefix the prefix * @return the oss client factory */ OSSClientFactory loader(String prefix); + } diff --git a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/oss/exception/OSSClientFactoryNotFoundException.java b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/oss/exception/OSSClientFactoryNotFoundException.java index cad0d1397..119194d6c 100644 --- a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/oss/exception/OSSClientFactoryNotFoundException.java +++ b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/oss/exception/OSSClientFactoryNotFoundException.java @@ -31,7 +31,6 @@ public OSSClientFactoryNotFoundException() { /** * Instantiates a new Oss client factory not found exception. - * * @param message the message */ public OSSClientFactoryNotFoundException(String message) { @@ -40,9 +39,8 @@ public OSSClientFactoryNotFoundException(String message) { /** * Instantiates a new Oss client factory not found exception. - * * @param message the message - * @param cause the cause + * @param cause the cause */ public OSSClientFactoryNotFoundException(String message, Throwable cause) { super(message, cause); @@ -50,7 +48,6 @@ public OSSClientFactoryNotFoundException(String message, Throwable cause) { /** * Instantiates a new Oss client factory not found exception. - * * @param cause the cause */ public OSSClientFactoryNotFoundException(Throwable cause) { @@ -59,14 +56,14 @@ public OSSClientFactoryNotFoundException(Throwable cause) { /** * Instantiates a new Oss client factory not found exception. - * - * @param message the message - * @param cause the cause - * @param enableSuppression the enable suppression + * @param message the message + * @param cause the cause + * @param enableSuppression the enable suppression * @param writableStackTrace the writable stack trace */ protected OSSClientFactoryNotFoundException(String message, Throwable cause, boolean enableSuppression, - boolean writableStackTrace) { + boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } + } diff --git a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/oss/support/AbstractService.java b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/oss/support/AbstractService.java index 3d654beb4..636b30f41 100644 --- a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/oss/support/AbstractService.java +++ b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/oss/support/AbstractService.java @@ -44,13 +44,16 @@ public void setApplicationContext(ApplicationContext applicationContext) throws OSSProperties properties = applicationContext.getBean(OSSProperties.class); OSSClientFactoryPatternResolver resolver = new OSSClientFactoryPatternResolver(); OSSClientFactory factory = resolver.loader(properties.getPrefix()); - this.client = factory.instance(properties.getEndpoint(), properties.getAccessKey(), properties.getSecretKey(), properties.getRegion()); + this.client = factory.instance(properties.getEndpoint(), properties.getAccessKey(), properties.getSecretKey(), + properties.getRegion()); if (applicationContext instanceof GenericApplicationContext context) { ResolvableType resolvableType = ResolvableType.forInstance(client); - BeanDefinitionBuilder definitionBuilder = BeanDefinitionBuilder.rootBeanDefinition(resolvableType, () -> client); + BeanDefinitionBuilder definitionBuilder = BeanDefinitionBuilder.rootBeanDefinition(resolvableType, + () -> client); AbstractBeanDefinition beanDefinition = definitionBuilder.getBeanDefinition(); context.registerBeanDefinition(factory.name(), beanDefinition); } } + } diff --git a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/oss/support/OSSClientFactoryPatternResolver.java b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/oss/support/OSSClientFactoryPatternResolver.java index 23fce1b13..5f05a40b9 100644 --- a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/oss/support/OSSClientFactoryPatternResolver.java +++ b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/oss/support/OSSClientFactoryPatternResolver.java @@ -64,7 +64,8 @@ public OSSClientFactory loader(String prefix) { if (log.isDebugEnabled()) { log.debug("oss factory匹配失败, 加载Spring SPI"); } - List factoryLoaders = SpringFactoriesLoader.loadFactories(OSSClientFactoryLoader.class, ClassUtils.getDefaultClassLoader()); + List factoryLoaders = SpringFactoriesLoader.loadFactories(OSSClientFactoryLoader.class, + ClassUtils.getDefaultClassLoader()); for (OSSClientFactoryLoader factoryLoader : factoryLoaders) { OSSClientFactory clientFactory = factoryLoader.loader(prefix); if (clientFactory != null) { diff --git a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/oss/support/OSSOperations.java b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/oss/support/OSSOperations.java index 7ed50f41d..a7ed2ffd8 100644 --- a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/oss/support/OSSOperations.java +++ b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/oss/support/OSSOperations.java @@ -29,7 +29,6 @@ public sealed interface OSSOperations extends AutoCloseable permits AbstractServ /** * Exist boolean. - * * @param bucketName the bucket name * @return the boolean */ @@ -37,63 +36,55 @@ public sealed interface OSSOperations extends AutoCloseable permits AbstractServ /** * Create bucket. - * * @param bucketName the bucket name */ void createBucket(String bucketName); /** * All buckets list. - * * @return the list */ List allBuckets(); /** * Remove. - * * @param bucketName the bucket name */ void removeObj(String bucketName); /** * Exist boolean. - * * @param bucketName the bucket name - * @param fileName the file name + * @param fileName the file name * @return the boolean */ boolean exist(String bucketName, String fileName); /** * Upload. - * - * @param bucketName the bucket name - * @param fileName the file name + * @param bucketName the bucket name + * @param fileName the file name * @param inputStream the input stream */ void upload(String bucketName, String fileName, InputStream inputStream); /** * Download input stream. - * * @param bucketName the bucket name - * @param fileName the file name + * @param fileName the file name * @return the input stream */ InputStream download(String bucketName, String fileName); /** * Remove. - * * @param bucketName the bucket name - * @param fileName the file name + * @param fileName the file name */ void removeObj(String bucketName, String fileName); /** * Remove objs. - * * @param bucketName the bucket name */ default void removeObjs(String bucketName) { @@ -105,28 +96,26 @@ default void removeObjs(String bucketName) { /** * Gets str url. - * * @param bucketName the bucket name - * @param fileName the file name + * @param fileName the file name * @return the str url */ String getStrUrl(String bucketName, String fileName); /** * Gets str url. - * * @param bucketName the bucket name - * @param fileName the file name - * @param expires the expires + * @param fileName the file name + * @param expires the expires * @return the str url */ String getStrUrl(String bucketName, String fileName, int expires); /** * Gets all obj. - * * @param bucketName the bucket name * @return the all obj */ List getAllObj(String bucketName); + } diff --git a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/oss/support/OSSTemplate.java b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/oss/support/OSSTemplate.java index bf8b96249..e9d10a249 100644 --- a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/oss/support/OSSTemplate.java +++ b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/oss/support/OSSTemplate.java @@ -54,7 +54,6 @@ public void removeObj(String bucketName) { /** * Remove bucket and obj. - * * @param bucketName the bucket name */ public void removeBucketAndObj(String bucketName) { @@ -106,9 +105,8 @@ public void close() throws Exception { /** * Get external link string. - * * @param bucketName the bucket name - * @param fileName the file name + * @param fileName the file name * @return the string */ public String getExternalLink(String bucketName, String fileName) { @@ -116,8 +114,10 @@ public String getExternalLink(String bucketName, String fileName) { int index = url.indexOf('?'); if (index == -1) { return url; - } else { + } + else { return url.substring(0, index); } } + } diff --git a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/oss/support/aliyun/AliyunClientFactory.java b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/oss/support/aliyun/AliyunClientFactory.java index c085c0d0f..dc6850b1d 100644 --- a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/oss/support/aliyun/AliyunClientFactory.java +++ b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/oss/support/aliyun/AliyunClientFactory.java @@ -33,15 +33,12 @@ public class AliyunClientFactory implements OSSClientFactory { @Override public OSS instance(String endpoint, String accessKey, String secretKey, String region) { CredentialsProvider provider = new DefaultCredentialProvider(accessKey, secretKey); - return OSSClientBuilder.create() - .endpoint(endpoint) - .credentialsProvider(provider) - .region(region) - .build(); + return OSSClientBuilder.create().endpoint(endpoint).credentialsProvider(provider).region(region).build(); } @Override public String name() { return "aliyun"; } + } diff --git a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/oss/support/aliyun/AliyunOSSService.java b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/oss/support/aliyun/AliyunOSSService.java index c6ebb0dc1..8587cee49 100644 --- a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/oss/support/aliyun/AliyunOSSService.java +++ b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/oss/support/aliyun/AliyunOSSService.java @@ -45,7 +45,7 @@ public boolean exist(String bucketName) { public void createBucket(String bucketName) { if (!client.doesBucketExist(bucketName)) { client.createBucket((bucketName)); - //设置cors + // 设置cors SetBucketCORSRequest request = new SetBucketCORSRequest(bucketName); SetBucketCORSRequest.CORSRule rule = new SetBucketCORSRequest.CORSRule(); rule.addAllowedMethod("GET"); @@ -61,10 +61,7 @@ public void createBucket(String bucketName) { @Override public List allBuckets() { - return client.listBuckets() - .stream() - .map(Bucket::getName) - .toList(); + return client.listBuckets().stream().map(Bucket::getName).toList(); } @Override @@ -106,15 +103,12 @@ public String getStrUrl(String bucketName, String fileName, int expires) { @Override public List getAllObj(String bucketName) { - return client.listObjects(bucketName) - .getObjectSummaries() - .stream() - .map(OSSObjectSummary::getKey) - .toList(); + return client.listObjects(bucketName).getObjectSummaries().stream().map(OSSObjectSummary::getKey).toList(); } @Override public void close() throws Exception { client.shutdown(); } + } diff --git a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/oss/support/minio/MinioClientFactory.java b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/oss/support/minio/MinioClientFactory.java index 42aa4b2f4..e76507606 100644 --- a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/oss/support/minio/MinioClientFactory.java +++ b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/oss/support/minio/MinioClientFactory.java @@ -29,15 +29,12 @@ public class MinioClientFactory implements OSSClientFactory { @Override public MinioClient instance(String endpoint, String accessKey, String secretKey, String region) { - return new MinioClient.Builder() - .endpoint(endpoint) - .credentials(accessKey, secretKey) - .region(region) - .build(); + return new MinioClient.Builder().endpoint(endpoint).credentials(accessKey, secretKey).region(region).build(); } @Override public String name() { return "minio"; } + } diff --git a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/oss/support/minio/MinioService.java b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/oss/support/minio/MinioService.java index 391158a1e..53743d2df 100644 --- a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/oss/support/minio/MinioService.java +++ b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/oss/support/minio/MinioService.java @@ -36,19 +36,10 @@ */ public class MinioService extends AbstractService { - private static final String POLICY_JSON = "{" + - " \"Statement\": [" + - " {" + - " \"Action\": \"s3:GetObject\"," + - " \"Effect\": \"Allow\"," + - " \"Principal\": \"*\"," + - " \"Resource\": [" + - " \"arn:aws:s3:::${bucketName}/*\"" + - " ]" + - " }" + - " ]," + - " \"Version\": \"2012-10-17\"" + - "}"; + private static final String POLICY_JSON = "{" + " \"Statement\": [" + " {" + + " \"Action\": \"s3:GetObject\"," + " \"Effect\": \"Allow\"," + " \"Principal\": \"*\"," + + " \"Resource\": [" + " \"arn:aws:s3:::${bucketName}/*\"" + " ]" + " }" + " ]," + + " \"Version\": \"2012-10-17\"" + "}"; @SneakyThrows @Override @@ -61,22 +52,16 @@ public boolean exist(String bucketName) { public void createBucket(String bucketName) { if (!this.exist(bucketName)) { client.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build()); - //设置桶策略 + // 设置桶策略 String config = POLICY_JSON.replaceAll("\\$\\{bucketName}", bucketName); - client.setBucketPolicy(SetBucketPolicyArgs.builder() - .bucket(bucketName) - .config(config) - .build()); + client.setBucketPolicy(SetBucketPolicyArgs.builder().bucket(bucketName).config(config).build()); } } @SneakyThrows @Override public List allBuckets() { - return client.listBuckets() - .stream() - .map(Bucket::name) - .collect(Collectors.toList()); + return client.listBuckets().stream().map(Bucket::name).collect(Collectors.toList()); } @SneakyThrows @@ -88,11 +73,9 @@ public void removeObj(String bucketName) { @Override public boolean exist(String bucketName, String fileName) { try { - return client.statObject(StatObjectArgs.builder() - .bucket(bucketName) - .object(fileName) - .build()) != null; - } catch (Exception e) { + return client.statObject(StatObjectArgs.builder().bucket(bucketName).object(fileName).build()) != null; + } + catch (Exception e) { return false; } } @@ -110,29 +93,20 @@ public void upload(String bucketName, String fileName, InputStream inputStream) @SneakyThrows @Override public InputStream download(String bucketName, String fileName) { - return client.getObject(GetObjectArgs.builder() - .bucket(bucketName) - .object(fileName) - .build()); + return client.getObject(GetObjectArgs.builder().bucket(bucketName).object(fileName).build()); } @SneakyThrows @Override public void removeObj(String bucketName, String fileName) { - client.removeObject(RemoveObjectArgs.builder() - .bucket(bucketName) - .object(fileName) - .build()); + client.removeObject(RemoveObjectArgs.builder().bucket(bucketName).object(fileName).build()); } @SneakyThrows @Override public String getStrUrl(String bucketName, String fileName) { - return client.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder() - .bucket(bucketName) - .object(fileName) - .method(Method.GET) - .build()); + return client.getPresignedObjectUrl( + GetPresignedObjectUrlArgs.builder().bucket(bucketName).object(fileName).method(Method.GET).build()); } @SneakyThrows @@ -149,9 +123,7 @@ public String getStrUrl(String bucketName, String fileName, int expires) { @SneakyThrows @Override public List getAllObj(String bucketName) { - Iterable> results = client.listObjects(ListObjectsArgs.builder() - .bucket(bucketName) - .build()); + Iterable> results = client.listObjects(ListObjectsArgs.builder().bucket(bucketName).build()); List list = new ArrayList<>(); for (Result result : results) { list.add(result.get().objectName()); @@ -163,4 +135,5 @@ public List getAllObj(String bucketName) { public void close() { client = null; } + } diff --git a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/qrcode/QRCodeAutoConfiguration.java b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/qrcode/QRCodeAutoConfiguration.java index 5554836ef..dcb011eb2 100644 --- a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/qrcode/QRCodeAutoConfiguration.java +++ b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/qrcode/QRCodeAutoConfiguration.java @@ -48,7 +48,6 @@ public class QRCodeAutoConfiguration { /** * Google qr code generator qr code generator. - * * @param builder the builder * @return the qr code generator */ @@ -71,6 +70,7 @@ public static class WebMvcQRCodeAutoConfiguration implements WebMvcConfigurer { public void addReturnValueHandlers(List handlers) { handlers.add(new QRCodeMethodReturnValueHandler(qrCodeGenerator)); } + } /** @@ -81,14 +81,17 @@ public void addReturnValueHandlers(List handler public static class WebFluxQRCodeAutoConfiguration implements WebFluxConfigurer { /** - * Reactive qr code method return value handler reactive qr code method return value handler. - * + * Reactive qr code method return value handler reactive qr code method return + * value handler. * @param qrCodeGenerator the qr code generator * @return the reactive qr code method return value handler */ @Bean - public ReactiveQRCodeMethodReturnValueHandler reactiveQRCodeMethodReturnValueHandler(QRCodeGenerator qrCodeGenerator) { + public ReactiveQRCodeMethodReturnValueHandler reactiveQRCodeMethodReturnValueHandler( + QRCodeGenerator qrCodeGenerator) { return new ReactiveQRCodeMethodReturnValueHandler(qrCodeGenerator); } + } + } diff --git a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/redis/CustomizeRedisAutoConfiguration.java b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/redis/CustomizeRedisAutoConfiguration.java index 11ac5130b..91e132812 100644 --- a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/redis/CustomizeRedisAutoConfiguration.java +++ b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/redis/CustomizeRedisAutoConfiguration.java @@ -42,12 +42,11 @@ */ @SpringAutoService @ConditionalOnClass(RedisOperations.class) -@AutoConfiguration(before = {RedisAutoConfiguration.class}) +@AutoConfiguration(before = { RedisAutoConfiguration.class }) public class CustomizeRedisAutoConfiguration { /** * Livk redis template universal redis template. - * * @param redisConnectionFactory the redis connection factory * @return the universal redis template */ @@ -57,29 +56,31 @@ public RedisOps redisOps(RedisConnectionFactory redisConnectionFactory) { return new RedisOps(redisConnectionFactory); } - /** * The type Customize reactive redis auto configuration. */ - @AutoConfiguration(before = {RedisReactiveAutoConfiguration.class}) - @ConditionalOnClass({ReactiveRedisConnectionFactory.class, ReactiveRedisTemplate.class, Flux.class}) + @AutoConfiguration(before = { RedisReactiveAutoConfiguration.class }) + @ConditionalOnClass({ ReactiveRedisConnectionFactory.class, ReactiveRedisTemplate.class, Flux.class }) public static class CustomizeReactiveRedisAutoConfiguration { /** * Universal reactive redis template universal reactive redis template. - * * @param redisConnectionFactory the redis connection factory * @return the universal reactive redis template */ @Bean @ConditionalOnMissingBean public ReactiveRedisOps reactiveRedisOps(ReactiveRedisConnectionFactory redisConnectionFactory) { - RedisSerializationContext serializationContext = RedisSerializationContext. - newSerializationContext() - .key(RedisSerializer.string()).value(JacksonSerializerUtils.json()) - .hashKey(RedisSerializer.string()).hashValue(JacksonSerializerUtils.json()).build(); + RedisSerializationContext serializationContext = RedisSerializationContext + .newSerializationContext() + .key(RedisSerializer.string()) + .value(JacksonSerializerUtils.json()) + .hashKey(RedisSerializer.string()) + .hashValue(JacksonSerializerUtils.json()) + .build(); return new ReactiveRedisOps(redisConnectionFactory, serializationContext); } + } } diff --git a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/redisearch/RediSearchAutoConfiguration.java b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/redisearch/RediSearchAutoConfiguration.java index 756ff80fb..d8bd78dfb 100644 --- a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/redisearch/RediSearchAutoConfiguration.java +++ b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/redisearch/RediSearchAutoConfiguration.java @@ -56,7 +56,6 @@ public class RediSearchAutoConfiguration { /** * Client resources client resources. - * * @param providers the providers * @return the client resources */ @@ -69,17 +68,15 @@ public ClientResources clientResources(ObjectProvider providers) { + public RedisModulesClient redisModulesClient(ClientResources clientResources, RediSearchProperties properties, + ObjectProvider providers) { RedisURI redisURI = RediSearchSupport.create(properties); RedisModulesClient client = RedisModulesClient.create(clientResources, redisURI); ClientOptions.Builder builder = client.getOptions().mutate(); @@ -90,17 +87,15 @@ public RedisModulesClient redisModulesClient(ClientResources clientResources, /** * Redis modules cluster client redis modules cluster client. - * * @param clientResources the client resources - * @param properties the properties - * @param providers the providers + * @param properties the properties + * @param providers the providers * @return the redis modules cluster client */ @Bean(destroyMethod = "close") @ConditionalOnProperty(name = "spring.redisearch.cluster.enabled", havingValue = "true") public RedisModulesClusterClient redisModulesClusterClient(ClientResources clientResources, - RediSearchProperties properties, - ObjectProvider providers) { + RediSearchProperties properties, ObjectProvider providers) { List redisURIList = RediSearchSupport.createCluster(properties); RedisModulesClusterClient clusterClient = RedisModulesClusterClient.create(clientResources, redisURIList); ClusterClientOptions.Builder builder = ((ClusterClientOptions) clusterClient.getOptions()).mutate(); @@ -114,7 +109,6 @@ public RedisModulesClusterClient redisModulesClusterClient(ClientResources clien /** * Pool config generic object pool config. - * * @param properties the properties * @return the generic object pool config */ @@ -131,32 +125,33 @@ public GenericObjectPoolConfig poolConfig(RediSearchProperties properties) { @Import(StatefulConnectionConfiguration.class) @ConditionalOnProperty(name = "spring.redisearch.cluster.enabled", havingValue = "false", matchIfMissing = true) public static class RediSearchPoolConfiguration { + /** * String generic object pool generic object pool. - * * @param redisModulesClient the redis modules client - * @param config the config + * @param config the config * @return the generic object pool */ @Bean(destroyMethod = "close") - public GenericObjectPool> stringGenericObjectPool(RedisModulesClient redisModulesClient, - GenericObjectPoolConfig> config) { + public GenericObjectPool> stringGenericObjectPool( + RedisModulesClient redisModulesClient, + GenericObjectPoolConfig> config) { return RediSearchSupport.pool(redisModulesClient::connect, config); } - /** * Generic object pool generic object pool. - * * @param redisModulesClient the redis modules client - * @param config the config + * @param config the config * @return the generic object pool */ @Bean(destroyMethod = "close") - public GenericObjectPool> genericObjectPool(RedisModulesClient redisModulesClient, - GenericObjectPoolConfig> config) { + public GenericObjectPool> genericObjectPool( + RedisModulesClient redisModulesClient, + GenericObjectPoolConfig> config) { return RediSearchSupport.pool(() -> redisModulesClient.connect(new JdkRedisCodec()), config); } + } /** @@ -166,30 +161,33 @@ public GenericObjectPool> generic @Import(StatefulConnectionConfiguration.class) @ConditionalOnProperty(name = "spring.redisearch.cluster.enabled", havingValue = "true") public static class RediSearchClusterPoolConfiguration { + /** * String generic object pool generic object pool. - * * @param redisModulesClusterClient the redis modules cluster client - * @param config the config + * @param config the config * @return the generic object pool */ @Bean(destroyMethod = "close") - public GenericObjectPool> stringGenericObjectPool(RedisModulesClusterClient redisModulesClusterClient, - GenericObjectPoolConfig> config) { + public GenericObjectPool> stringGenericObjectPool( + RedisModulesClusterClient redisModulesClusterClient, + GenericObjectPoolConfig> config) { return RediSearchSupport.pool(redisModulesClusterClient::connect, config); } /** * Generic object pool generic object pool. - * * @param redisModulesClusterClient the redis modules cluster client - * @param config the config + * @param config the config * @return the generic object pool */ @Bean(destroyMethod = "close") - public GenericObjectPool> genericObjectPool(RedisModulesClusterClient redisModulesClusterClient, - GenericObjectPoolConfig> config) { + public GenericObjectPool> genericObjectPool( + RedisModulesClusterClient redisModulesClusterClient, + GenericObjectPoolConfig> config) { return RediSearchSupport.pool(() -> redisModulesClusterClient.connect(new JdkRedisCodec()), config); } + } + } diff --git a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/redisearch/RediSearchProperties.java b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/redisearch/RediSearchProperties.java index bedade46f..5c9751d12 100644 --- a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/redisearch/RediSearchProperties.java +++ b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/redisearch/RediSearchProperties.java @@ -31,35 +31,44 @@ public class RediSearchProperties { private final Boolean ssl = false; + private final Pool pool = new Pool(); + /** * Database index used by the connection factory. */ private int database = 0; + /** * Redis server host. */ private String host = "localhost"; + /** * Login username of the redis server. */ private String username; + /** * Login password of the redis server. */ private String password; + /** * Redis server port. */ private int port = 6379; + /** * timeout. */ private Duration timeout; + /** * Client name to be set on connections with CLIENT SETNAME. */ private String clientName; + private Cluster cluster; /** @@ -100,6 +109,7 @@ public static class Pool { * indefinitely. */ private Duration maxWait = Duration.ofMillis(-1); + } /** @@ -121,5 +131,7 @@ public static class Cluster { * cluster. */ private Integer maxRedirects; + } + } diff --git a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/redisearch/RediSearchSupport.java b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/redisearch/RediSearchSupport.java index b6c36f89d..dea3d3064 100644 --- a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/redisearch/RediSearchSupport.java +++ b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/redisearch/RediSearchSupport.java @@ -43,24 +43,20 @@ final class RediSearchSupport { /** * Create cluster list. - * * @param properties the properties * @return the list */ public List createCluster(RediSearchProperties properties) { - return properties.getCluster().getNodes() - .stream() - .map(node -> { - String[] arr = node.split(":"); - RedisURI redisURI = RedisURI.create(arr[0], Integer.parseInt(arr[1])); - config(redisURI, properties); - return redisURI; - }).toList(); + return properties.getCluster().getNodes().stream().map(node -> { + String[] arr = node.split(":"); + RedisURI redisURI = RedisURI.create(arr[0], Integer.parseInt(arr[1])); + config(redisURI, properties); + return redisURI; + }).toList(); } /** * Create redis uri. - * * @param properties the properties * @return the redis uri */ @@ -71,8 +67,8 @@ public RedisURI create(RediSearchProperties properties) { } private void config(RedisURI redisURI, RediSearchProperties properties) { - redisURI.setCredentialsProvider(RedisCredentialsProvider.from( - () -> RedisCredentials.just(properties.getUsername(), properties.getPassword()))); + redisURI.setCredentialsProvider(RedisCredentialsProvider + .from(() -> RedisCredentials.just(properties.getUsername(), properties.getPassword()))); redisURI.setDatabase(properties.getDatabase()); Duration timeout = properties.getTimeout(); if (timeout != null) { @@ -84,8 +80,7 @@ private void config(RedisURI redisURI, RediSearchProperties properties) { /** * With pool config generic object pool config. - * - * @param the type parameter + * @param the type parameter * @param properties the properties * @return the generic object pool config */ @@ -106,47 +101,44 @@ public static GenericObjectPoolConfig withPoolConfig(RediSearchProperties /** * Pool generic object pool. - * - * @param the type parameter - * @param the type parameter - * @param supplier the supplier + * @param the type parameter + * @param the type parameter + * @param supplier the supplier * @param poolConfig the pool config * @return the generic object pool */ - public GenericObjectPool> pool(Supplier> supplier, - GenericObjectPoolConfig> poolConfig) { + public GenericObjectPool> pool( + Supplier> supplier, + GenericObjectPoolConfig> poolConfig) { return ConnectionPoolSupport.createGenericObjectPool(supplier, poolConfig); } /** * Pool generic object pool. - * - * @param the type parameter - * @param the type parameter - * @param client the client + * @param the type parameter + * @param the type parameter + * @param client the client * @param redisCodec the redis codec * @param poolConfig the pool config * @return the generic object pool */ public GenericObjectPool> pool(RedisModulesClient client, - RedisCodec redisCodec, - GenericObjectPoolConfig> poolConfig) { + RedisCodec redisCodec, GenericObjectPoolConfig> poolConfig) { return pool(() -> client.connect(redisCodec), poolConfig); } /** * Pool generic object pool. - * - * @param the type parameter - * @param the type parameter - * @param client the client + * @param the type parameter + * @param the type parameter + * @param client the client * @param redisCodec the redis codec * @param poolConfig the pool config * @return the generic object pool */ public GenericObjectPool> pool(RedisModulesClusterClient client, - RedisCodec redisCodec, - GenericObjectPoolConfig> poolConfig) { + RedisCodec redisCodec, GenericObjectPoolConfig> poolConfig) { return pool(() -> client.connect(redisCodec), poolConfig); } + } diff --git a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/redisearch/StatefulConnectionConfiguration.java b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/redisearch/StatefulConnectionConfiguration.java index ba35a7bef..48e55b165 100644 --- a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/redisearch/StatefulConnectionConfiguration.java +++ b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/redisearch/StatefulConnectionConfiguration.java @@ -32,25 +32,27 @@ public class StatefulConnectionConfiguration { /** * String connection stateful redis modules connection. - * * @param stringGenericObjectPool the string generic object pool * @return the stateful redis modules connection * @throws Exception the exception */ @Bean(destroyMethod = "close") - public StatefulRedisModulesConnection stringConnection(GenericObjectPool> stringGenericObjectPool) throws Exception { + public StatefulRedisModulesConnection stringConnection( + GenericObjectPool> stringGenericObjectPool) + throws Exception { return stringGenericObjectPool.getFactory().makeObject().getObject(); } /** * Connection stateful redis modules connection. - * * @param genericObjectPool the generic object pool * @return the stateful redis modules connection * @throws Exception the exception */ @Bean(destroyMethod = "close") - public StatefulRedisModulesConnection connection(GenericObjectPool> genericObjectPool) throws Exception { + public StatefulRedisModulesConnection connection( + GenericObjectPool> genericObjectPool) throws Exception { return genericObjectPool.getFactory().makeObject().getObject(); } + } diff --git a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/redisearch/codec/AbstractRedisCodec.java b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/redisearch/codec/AbstractRedisCodec.java index e621daabb..32fa97dca 100644 --- a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/redisearch/codec/AbstractRedisCodec.java +++ b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/redisearch/codec/AbstractRedisCodec.java @@ -73,7 +73,6 @@ public final ByteBuffer encodeValue(T value) { /** * Serialize the given object to binary data. - * * @param value object to serialize. Can be {@literal null}. * @return the equivalent binary data. Can be {@literal null}. * @throws CodecException the codec exception @@ -82,10 +81,10 @@ public final ByteBuffer encodeValue(T value) { /** * Deserialize an object from the given binary data. - * * @param bytes object binary representation. Can be {@literal null}. * @return the equivalent object instance. Can be {@literal null}. * @throws CodecException the codec exception */ protected abstract T deserialize(byte[] bytes) throws CodecException; + } diff --git a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/redisearch/codec/CodecException.java b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/redisearch/codec/CodecException.java index 4ee7f3c3a..86990ab5c 100644 --- a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/redisearch/codec/CodecException.java +++ b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/redisearch/codec/CodecException.java @@ -24,7 +24,6 @@ public class CodecException extends RuntimeException { /** * Constructs a new {@link CodecException} instance. - * * @param msg the detail message. */ public CodecException(String msg) { @@ -33,12 +32,11 @@ public CodecException(String msg) { /** * Constructs a new {@link CodecException} instance. - * - * @param msg the detail message. + * @param msg the detail message. * @param cause the nested exception. */ public CodecException(String msg, Throwable cause) { super(msg, cause); } -} +} diff --git a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/redisearch/codec/JacksonRedisCodec.java b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/redisearch/codec/JacksonRedisCodec.java index ee220c87f..c034dd349 100644 --- a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/redisearch/codec/JacksonRedisCodec.java +++ b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/redisearch/codec/JacksonRedisCodec.java @@ -38,7 +38,6 @@ public class JacksonRedisCodec extends AbstractRedisCodec { /** * Creates a new {@link JacksonRedisCodec} for the given target {@link Class}. - * * @param type must not be {@literal null}. */ public JacksonRedisCodec(Class type) { @@ -47,7 +46,6 @@ public JacksonRedisCodec(Class type) { /** * Creates a new {@link JacksonRedisCodec} for the given target {@link JavaType}. - * * @param javaType must not be {@literal null}. */ public JacksonRedisCodec(JavaType javaType) { @@ -56,9 +54,8 @@ public JacksonRedisCodec(JavaType javaType) { /** * Creates a new {@link JacksonRedisCodec} for the given target {@link Class}. - * * @param mapper must not be {@literal null}. - * @param type must not be {@literal null}. + * @param type must not be {@literal null}. * @since 3.0 */ public JacksonRedisCodec(ObjectMapper mapper, Class type) { @@ -76,7 +73,8 @@ private JavaType getJavaType(Class clazz) { protected byte[] serialize(T value) throws CodecException { try { return this.mapper.writeValueAsBytes(value); - } catch (Exception ex) { + } + catch (Exception ex) { throw new CodecException("Could not write JSON: " + ex.getMessage(), ex); } } @@ -85,8 +83,10 @@ protected byte[] serialize(T value) throws CodecException { protected T deserialize(byte[] bytes) throws CodecException { try { return this.mapper.readValue(bytes, javaType); - } catch (Exception ex) { + } + catch (Exception ex) { throw new CodecException("Could not read JSON: " + ex.getMessage(), ex); } } + } diff --git a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/redisearch/codec/JdkRedisCodec.java b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/redisearch/codec/JdkRedisCodec.java index 5e8463cfa..3e63c68c3 100644 --- a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/redisearch/codec/JdkRedisCodec.java +++ b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/redisearch/codec/JdkRedisCodec.java @@ -17,7 +17,6 @@ package com.livk.autoconfigure.redisearch.codec; - import org.springframework.core.ConfigurableObjectInputStream; import java.io.*; @@ -39,7 +38,6 @@ public JdkRedisCodec() { /** * Instantiates a new Jdk redis codec. - * * @param classLoader the class loader */ public JdkRedisCodec(ClassLoader classLoader) { @@ -49,8 +47,8 @@ public JdkRedisCodec(ClassLoader classLoader) { @Override protected byte[] serialize(Object value) throws CodecException { if (!(value instanceof Serializable)) { - throw new IllegalArgumentException(getClass().getSimpleName() + " requires a Serializable payload " + - "but received an object of type [" + value.getClass().getName() + "]"); + throw new IllegalArgumentException(getClass().getSimpleName() + " requires a Serializable payload " + + "but received an object of type [" + value.getClass().getName() + "]"); } try { ByteArrayOutputStream out = new ByteArrayOutputStream(1024); @@ -58,7 +56,8 @@ protected byte[] serialize(Object value) throws CodecException { objectOutputStream.writeObject(value); objectOutputStream.flush(); return out.toByteArray(); - } catch (IOException e) { + } + catch (IOException e) { throw new CodecException("Cannot serialize", e); } } @@ -69,8 +68,10 @@ protected Object deserialize(byte[] bytes) throws CodecException { try { ObjectInputStream objectInputStream = new ConfigurableObjectInputStream(inputStream, this.classLoader); return objectInputStream.readObject(); - } catch (IOException | ClassNotFoundException e) { + } + catch (IOException | ClassNotFoundException e) { throw new CodecException("Cannot deserialize", e); } } + } diff --git a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/redisearch/customizer/ClientOptionsBuilderCustomizer.java b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/redisearch/customizer/ClientOptionsBuilderCustomizer.java index c0ee2a027..22277a3a6 100644 --- a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/redisearch/customizer/ClientOptionsBuilderCustomizer.java +++ b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/redisearch/customizer/ClientOptionsBuilderCustomizer.java @@ -26,4 +26,5 @@ * @author livk */ public interface ClientOptionsBuilderCustomizer extends Customizer { + } diff --git a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/redisearch/customizer/ClientResourcesBuilderCustomizer.java b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/redisearch/customizer/ClientResourcesBuilderCustomizer.java index 34d4fc082..8f1255a8f 100644 --- a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/redisearch/customizer/ClientResourcesBuilderCustomizer.java +++ b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/redisearch/customizer/ClientResourcesBuilderCustomizer.java @@ -26,4 +26,5 @@ * @author livk */ public interface ClientResourcesBuilderCustomizer extends Customizer { + } diff --git a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/redisearch/customizer/ClusterClientOptionsBuilderCustomizer.java b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/redisearch/customizer/ClusterClientOptionsBuilderCustomizer.java index 62e740027..2ea9405de 100644 --- a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/redisearch/customizer/ClusterClientOptionsBuilderCustomizer.java +++ b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/redisearch/customizer/ClusterClientOptionsBuilderCustomizer.java @@ -26,4 +26,5 @@ * @author livk */ public interface ClusterClientOptionsBuilderCustomizer extends Customizer { + } diff --git a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/redisson/ByteBuddySupport.java b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/redisson/ByteBuddySupport.java index d65d4f4c5..17d784bc0 100644 --- a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/redisson/ByteBuddySupport.java +++ b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/redisson/ByteBuddySupport.java @@ -60,41 +60,38 @@ final class ByteBuddySupport { private static final String PACKAGE_NAME = "com.livk.autoconfigure.redisson."; - private static final Set> supportType = Sets.newHashSet( - Config.class, AddressResolverGroupFactory.class, Codec.class, RedissonNodeInitializer.class, - LoadBalancer.class, NatMapper.class, NameMapper.class, NettyHook.class, CredentialsResolver.class, - EventLoopGroup.class, ConnectionListener.class, ExecutorService.class, KeyManagerFactory.class, - TrustManagerFactory.class, CommandMapper.class); + private static final Set> supportType = Sets.newHashSet(Config.class, AddressResolverGroupFactory.class, + Codec.class, RedissonNodeInitializer.class, LoadBalancer.class, NatMapper.class, NameMapper.class, + NettyHook.class, CredentialsResolver.class, EventLoopGroup.class, ConnectionListener.class, + ExecutorService.class, KeyManagerFactory.class, TrustManagerFactory.class, CommandMapper.class); /** * Proxy converters set. - * * @return the set */ public static Set> makeConverters() { - return supportType.stream() - .map(ByteBuddySupport::make) - .collect(Collectors.toSet()); + return supportType.stream().map(ByteBuddySupport::make).collect(Collectors.toSet()); } private static ConfigBaseConverter make(Class type) { String name = PACKAGE_NAME + type.getSimpleName() + ConfigBaseConverter.class.getSimpleName() + "$Proxy"; - DynamicType.Builder.MethodDefinition.ReceiverTypeDefinition> typeDefinition = new GenericsByteBuddy(ClassFileVersion.JAVA_V17) + DynamicType.Builder.MethodDefinition.ReceiverTypeDefinition> typeDefinition = new GenericsByteBuddy( + ClassFileVersion.JAVA_V17) .>sub(ConfigBaseConverter.class, type) .name(name) .method(ElementMatchers.none()) .withoutCode(); try (DynamicType.Unloaded> unloaded = typeDefinition.make()) { - Class> proxyType = unloaded.load(ClassUtils.getDefaultClassLoader()).getLoaded(); + Class> proxyType = unloaded.load(ClassUtils.getDefaultClassLoader()) + .getLoaded(); return BeanUtils.instantiateClass(proxyType); } } - private static final class GenericsByteBuddy extends ByteBuddy { + /** * Instantiates a new Generics byte buddy. - * * @param classFileVersion the class file version */ public GenericsByteBuddy(ClassFileVersion classFileVersion) { @@ -103,22 +100,19 @@ public GenericsByteBuddy(ClassFileVersion classFileVersion) { /** * Sub dynamic type . builder. - * - * @param the type parameter - * @param type the type + * @param the type parameter + * @param type the type * @param generics the generics * @return the dynamic type . builder */ public DynamicType.Builder sub(Class type, Class... generics) { - TypeDefinition description = TypeDescription.Generic.Builder - .parameterizedType(type, generics).build(); + TypeDefinition description = TypeDescription.Generic.Builder.parameterizedType(type, generics).build(); return sub(description); } /** * Sub dynamic type . builder. - * - * @param the type parameter + * @param the type parameter * @param superType the super type * @return the dynamic type . builder */ @@ -128,9 +122,8 @@ public DynamicType.Builder sub(TypeDefinition superType) { /** * Sub dynamic type . builder. - * - * @param the type parameter - * @param superType the super type + * @param the type parameter + * @param superType the super type * @param constructorStrategy the constructor strategy * @return the dynamic type . builder */ @@ -139,28 +132,26 @@ public DynamicType.Builder sub(TypeDefinition superType, ConstructorStrat TypeList.Generic interfaceTypes; if (superType.isPrimitive() || superType.isArray() || superType.isFinal()) { throw new IllegalArgumentException("Cannot sub primitive, array or final types: " + superType); - } else if (superType.isInterface()) { + } + else if (superType.isInterface()) { actualSuperType = TypeDescription.Generic.OfNonGenericType.ForLoadedType.of(Object.class); interfaceTypes = new TypeList.Generic.Explicit(superType); - } else { + } + else { actualSuperType = superType.asGenericType(); interfaceTypes = new TypeList.Generic.Empty(); } - return new SubclassDynamicTypeBuilder<>(instrumentedTypeFactory.subclass(namingStrategy.subclass(superType.asGenericType()), - ModifierContributor.Resolver.of(Visibility.PUBLIC, TypeManifestation.PLAIN).resolve(superType.getModifiers()), - actualSuperType).withInterfaces(interfaceTypes), - classFileVersion, - auxiliaryTypeNamingStrategy, - annotationValueFilterFactory, - annotationRetention, - implementationContextFactory, - methodGraphCompiler, - typeValidation, - visibilityBridgeStrategy, - classWriterStrategy, - ignoredMethods, - constructorStrategy); + return new SubclassDynamicTypeBuilder<>( + instrumentedTypeFactory.subclass(namingStrategy.subclass(superType.asGenericType()), + ModifierContributor.Resolver.of(Visibility.PUBLIC, TypeManifestation.PLAIN) + .resolve(superType.getModifiers()), + actualSuperType) + .withInterfaces(interfaceTypes), + classFileVersion, auxiliaryTypeNamingStrategy, annotationValueFilterFactory, annotationRetention, + implementationContextFactory, methodGraphCompiler, typeValidation, visibilityBridgeStrategy, + classWriterStrategy, ignoredMethods, constructorStrategy); } + } } diff --git a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/redisson/ConfigBaseConverter.java b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/redisson/ConfigBaseConverter.java index e07b9fa8d..abff542c8 100644 --- a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/redisson/ConfigBaseConverter.java +++ b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/redisson/ConfigBaseConverter.java @@ -54,8 +54,10 @@ public abstract class ConfigBaseConverter implements Converter { private static final JacksonSupport support = JacksonSupport.create(createMapper()); + @SuppressWarnings("unchecked") - private final Class type = (Class) GenericTypeResolver.resolveTypeArgument(this.getClass(), ConfigBaseConverter.class); + private final Class type = (Class) GenericTypeResolver.resolveTypeArgument(this.getClass(), + ConfigBaseConverter.class); private static YAMLMapper createMapper() { YAMLMapper mapper = new YAMLMapper(); @@ -76,8 +78,8 @@ private static YAMLMapper createMapper() { mapper.addMixIn(KeyManagerFactory.class, ConfigSupport.IgnoreMixIn.class); mapper.addMixIn(TrustManagerFactory.class, ConfigSupport.IgnoreMixIn.class); mapper.addMixIn(CommandMapper.class, ConfigSupport.ClassMixIn.class); - FilterProvider filterProvider = new SimpleFilterProvider() - .addFilter("classFilter", SimpleBeanPropertyFilter.filterOutAllExcept()); + FilterProvider filterProvider = new SimpleFilterProvider().addFilter("classFilter", + SimpleBeanPropertyFilter.filterOutAllExcept()); mapper.setFilterProvider(filterProvider); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); @@ -88,4 +90,5 @@ private static YAMLMapper createMapper() { public T convert(@NonNull String source) { return support.readValue(source, type); } + } diff --git a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/redisson/ConfigCustomizer.java b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/redisson/ConfigCustomizer.java index 5975968b9..61b4f99fe 100644 --- a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/redisson/ConfigCustomizer.java +++ b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/redisson/ConfigCustomizer.java @@ -22,9 +22,8 @@ /** *

- * Customize the RedissonClient configuration. - * * - * * @param configuration the {@link Config} to customize + * Customize the RedissonClient configuration. * * @param configuration the {@link Config} + * to customize *

* * @author livk diff --git a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/redisson/ConfigProperties.java b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/redisson/ConfigProperties.java index b500efce7..29009cfd8 100644 --- a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/redisson/ConfigProperties.java +++ b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/redisson/ConfigProperties.java @@ -72,61 +72,49 @@ public static class RedissonConfig extends Config { /** * Instantiates a new Redisson config. - * - * @param clusterServersConfig the cluster servers config - * @param replicatedServersConfig the replicated servers config - * @param singleServerConfig the single server config - * @param sentinelServersConfig the sentinel connection config - * @param masterSlaveServersConfig the master slave connection config - * @param nettyHook the netty hook - * @param codec the codec - * @param redissonReferenceEnabled the redisson reference enabled - * @param threads the threads - * @param transportMode the transport mode - * @param nettyThreads the netty threads - * @param executor the executor - * @param eventLoopGroup the event loop group - * @param lockWatchdogTimeout the lock watchdog timeout - * @param checkLockSyncedSlaves the check lock synced slaves - * @param keepPubSubOrder the keep pub sub order - * @param addressResolverGroupFactory the address resolver group factory - * @param useScriptCache the use script cache - * @param minCleanUpDelay the min clean up delay - * @param maxCleanUpDelay the max clean up delay - * @param cleanUpKeysAmount the clean up keys amount - * @param useThreadClassLoader the use thread class loader + * @param clusterServersConfig the cluster servers config + * @param replicatedServersConfig the replicated servers config + * @param singleServerConfig the single server config + * @param sentinelServersConfig the sentinel connection config + * @param masterSlaveServersConfig the master slave connection config + * @param nettyHook the netty hook + * @param codec the codec + * @param redissonReferenceEnabled the redisson reference enabled + * @param threads the threads + * @param transportMode the transport mode + * @param nettyThreads the netty threads + * @param executor the executor + * @param eventLoopGroup the event loop group + * @param lockWatchdogTimeout the lock watchdog timeout + * @param checkLockSyncedSlaves the check lock synced slaves + * @param keepPubSubOrder the keep pub sub order + * @param addressResolverGroupFactory the address resolver group factory + * @param useScriptCache the use script cache + * @param minCleanUpDelay the min clean up delay + * @param maxCleanUpDelay the max clean up delay + * @param cleanUpKeysAmount the clean up keys amount + * @param useThreadClassLoader the use thread class loader * @param reliableTopicWatchdogTimeout the reliable topic watchdog timeout - * @param connectionListener the connection listener - * @param lazyInitialization the lazy initialization - * @param slavesSyncTimeout the slaves sync timeout + * @param connectionListener the connection listener + * @param lazyInitialization the lazy initialization + * @param slavesSyncTimeout the slaves sync timeout */ @ConstructorBinding - public RedissonConfig(ClusterServers clusterServersConfig, - ReplicatedServers replicatedServersConfig, - SingleServer singleServerConfig, - SentinelServers sentinelServersConfig, - MasterSlaveServers masterSlaveServersConfig, - @DefaultValue("! {}") NettyHook nettyHook, - Codec codec, - @DefaultValue("true") Boolean redissonReferenceEnabled, - @DefaultValue("16") Integer threads, - @DefaultValue("NIO") TransportMode transportMode, - @DefaultValue("32") Integer nettyThreads, - ExecutorService executor, - EventLoopGroup eventLoopGroup, - @DefaultValue("30000") Long lockWatchdogTimeout, - @DefaultValue("true") Boolean checkLockSyncedSlaves, - @DefaultValue("true") Boolean keepPubSubOrder, - @DefaultValue("! {}") AddressResolverGroupFactory addressResolverGroupFactory, - @DefaultValue("false") Boolean useScriptCache, - @DefaultValue("5") Integer minCleanUpDelay, - @DefaultValue("1800") Integer maxCleanUpDelay, - @DefaultValue("100") Integer cleanUpKeysAmount, - @DefaultValue("true") Boolean useThreadClassLoader, - @DefaultValue("600000") Long reliableTopicWatchdogTimeout, - ConnectionListener connectionListener, - Boolean lazyInitialization, - @DefaultValue("1000") Long slavesSyncTimeout) { + public RedissonConfig(ClusterServers clusterServersConfig, ReplicatedServers replicatedServersConfig, + SingleServer singleServerConfig, SentinelServers sentinelServersConfig, + MasterSlaveServers masterSlaveServersConfig, + @DefaultValue("! {}") NettyHook nettyHook, Codec codec, + @DefaultValue("true") Boolean redissonReferenceEnabled, @DefaultValue("16") Integer threads, + @DefaultValue("NIO") TransportMode transportMode, @DefaultValue("32") Integer nettyThreads, + ExecutorService executor, EventLoopGroup eventLoopGroup, + @DefaultValue("30000") Long lockWatchdogTimeout, @DefaultValue("true") Boolean checkLockSyncedSlaves, + @DefaultValue("true") Boolean keepPubSubOrder, + @DefaultValue("! {}") AddressResolverGroupFactory addressResolverGroupFactory, + @DefaultValue("false") Boolean useScriptCache, @DefaultValue("5") Integer minCleanUpDelay, + @DefaultValue("1800") Integer maxCleanUpDelay, @DefaultValue("100") Integer cleanUpKeysAmount, + @DefaultValue("true") Boolean useThreadClassLoader, + @DefaultValue("600000") Long reliableTopicWatchdogTimeout, ConnectionListener connectionListener, + Boolean lazyInitialization, @DefaultValue("1000") Long slavesSyncTimeout) { setConfig(clusterServersConfig, super::setClusterServersConfig); setConfig(replicatedServersConfig, super::setReplicatedServersConfig); setConfig(singleServerConfig, super::setSingleServerConfig); @@ -166,6 +154,7 @@ private void set(T t, Consumer consumer) { consumer.accept(t); } } + } /** @@ -175,7 +164,6 @@ private void set(T t, Consumer consumer) { @Data public static class ClusterServers extends BaseMasterSlaveServers { - private NatMapper natMapper = NatMapper.direct(); /** @@ -190,8 +178,8 @@ public static class ClusterServers extends BaseMasterSlaveServers { - private List sentinelAddresses = new ArrayList<>(); - private NatMapper natMapper = NatMapper.direct(); - private String masterName; - private String sentinelUsername; - private String sentinelPassword; /** @@ -282,14 +265,12 @@ public static class SentinelServers extends BaseMasterSlaveServers { + /** * Redis server address */ @@ -339,6 +321,7 @@ public static class SingleServer extends Base { */ private long dnsMonitoringInterval = 5000; + } /** @@ -364,10 +347,8 @@ public static abstract class BaseMasterSlaveServerseach slave node + * Redis 'slave' node minimum idle subscription (pub/sub) connection amount for + * each slave node */ private int subscriptionConnectionMinimumIdleSize = 1; /** - * Redis 'slave' node maximum subscription (pub/sub) connection pool size for each slave node + * Redis 'slave' node maximum subscription (pub/sub) connection pool size for + * each slave node */ private int subscriptionConnectionPoolSize = 50; - private long dnsMonitoringInterval = 5000; + } /** @@ -413,24 +394,22 @@ public static abstract class BaseMasterSlaveServers> { /** - * If pooled connection not used for a timeout time - * and current connections amount bigger than minimum idle connections pool size, - * then it will closed and removed from pool. - * Value in milliseconds. + * If pooled connection not used for a timeout time and current + * connections amount bigger than minimum idle connections pool size, then it will + * closed and removed from pool. Value in milliseconds. */ private int idleConnectionTimeout = 10000; /** - * Timeout during connecting to any Redis server. - * Value in milliseconds. + * Timeout during connecting to any Redis server. Value in milliseconds. */ private int connectTimeout = 10000; /** - * Redis server response timeout. Starts to countdown when Redis command was succesfully sent. - * Value in milliseconds. + * Redis server response timeout. Starts to countdown when Redis command was + * succesfully sent. Value in milliseconds. */ private int timeout = 3000; @@ -439,7 +418,6 @@ public static abstract class Base> { private int retryAttempts = 3; - private int retryInterval = 1500; /** @@ -448,10 +426,8 @@ public static abstract class Base> { private String password; - private String username; - private CredentialsResolver credentialsResolver = new DefaultCredentialsResolver(); /** @@ -466,40 +442,28 @@ public static abstract class Base> { private String clientName; - private boolean sslEnableEndpointIdentification = true; - private SslProvider sslProvider = SslProvider.JDK; - private URL sslTruststore; - private String sslTruststorePassword; - private URL sslKeystore; - private String sslKeystorePassword; - private String[] sslProtocols; - private String[] sslCiphers; - private TrustManagerFactory sslTrustManagerFactory; - private KeyManagerFactory sslKeyManagerFactory; - private int pingConnectionInterval = 30000; - private boolean keepAlive; private boolean tcpNoDelay = true; @@ -510,7 +474,6 @@ public static abstract class Base> { /** * Convert t. - * * @return the t */ @SuppressWarnings("unchecked") @@ -519,5 +482,7 @@ public T convert() { Assert.notNull(type, "type must not be null"); return BeanUtils.copy(this, type); } + } + } diff --git a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/redisson/RedissonAutoConfiguration.java b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/redisson/RedissonAutoConfiguration.java index f82b8ddf9..2178c98d9 100644 --- a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/redisson/RedissonAutoConfiguration.java +++ b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/redisson/RedissonAutoConfiguration.java @@ -41,17 +41,17 @@ @SpringAutoService @ConditionalOnClass(Redisson.class) @AutoConfiguration(before = RedisAutoConfiguration.class) -@EnableConfigurationProperties({ConfigProperties.class, RedisProperties.class}) +@EnableConfigurationProperties({ ConfigProperties.class, RedisProperties.class }) public class RedissonAutoConfiguration { /** * Codec converter bean factory post processor bean factory post processor. - * * @param baseConverters the base converters * @return the bean factory post processor */ @Bean - public BeanFactoryPostProcessor codecConverterBeanFactoryPostProcessor(ObjectProvider> baseConverters) { + public BeanFactoryPostProcessor codecConverterBeanFactoryPostProcessor( + ObjectProvider> baseConverters) { return beanFactory -> { ConversionService conversionService = beanFactory.getConversionService(); if (conversionService instanceof ConverterRegistry converterRegistry) { @@ -63,23 +63,20 @@ public BeanFactoryPostProcessor codecConverterBeanFactoryPostProcessor(ObjectPro /** * Redisson client redisson client. - * - * @param configProperties the config properties - * @param redisProperties the redis properties + * @param configProperties the config properties + * @param redisProperties the redis properties * @param configCustomizers the config customizers * @return the redisson client */ @Bean(destroyMethod = "shutdown") @ConditionalOnMissingBean - public RedissonClient redissonClient(ConfigProperties configProperties, - RedisProperties redisProperties, - ObjectProvider configCustomizers) { + public RedissonClient redissonClient(ConfigProperties configProperties, RedisProperties redisProperties, + ObjectProvider configCustomizers) { return RedissonClientFactory.create(configProperties, redisProperties, configCustomizers); } /** * Redisson connection factory redisson connection factory. - * * @param redisson the redisson * @return the redisson connection factory */ @@ -89,4 +86,5 @@ public RedissonClient redissonClient(ConfigProperties configProperties, public RedissonConnectionFactory redissonConnectionFactory(RedissonClient redisson) { return new RedissonConnectionFactory(redisson); } + } diff --git a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/redisson/RedissonClientFactory.java b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/redisson/RedissonClientFactory.java index c7a58df3e..a8be78a6c 100644 --- a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/redisson/RedissonClientFactory.java +++ b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/redisson/RedissonClientFactory.java @@ -41,17 +41,14 @@ public class RedissonClientFactory { /** * Create redisson client. - * - * @param properties the properties - * @param redisProperties the redis properties + * @param properties the properties + * @param redisProperties the redis properties * @param configCustomizers the config customizers * @return the redisson client */ - public static RedissonClient create(ConfigProperties properties, - RedisProperties redisProperties, - ObjectProvider configCustomizers) { - Config config = Optional.ofNullable(properties.getConfig()) - .orElse(createConfig(redisProperties)); + public static RedissonClient create(ConfigProperties properties, RedisProperties redisProperties, + ObjectProvider configCustomizers) { + Config config = Optional.ofNullable(properties.getConfig()).orElse(createConfig(redisProperties)); configCustomizers.orderedStream().forEach(customizer -> customizer.customize(config)); return Redisson.create(config); } @@ -70,7 +67,8 @@ private static Config createConfig(RedisProperties redisProperties) { .setDatabase(redisProperties.getDatabase()) .setConnectTimeout(timeout) .setPassword(redisProperties.getPassword()); - } else if (redisProperties.getCluster() != null) { + } + else if (redisProperties.getCluster() != null) { List nodeList = redisProperties.getCluster().getNodes(); String[] nodes = convert(nodeList); config = new Config(); @@ -78,7 +76,8 @@ private static Config createConfig(RedisProperties redisProperties) { .addNodeAddress(nodes) .setConnectTimeout(timeout) .setPassword(redisProperties.getPassword()); - } else { + } + else { config = new Config(); String prefix = REDIS_PROTOCOL_PREFIX; if (redisProperties.getSsl().isEnabled()) { @@ -98,10 +97,12 @@ private static String[] convert(List nodesObject) { for (String node : nodesObject) { if (!node.startsWith(REDIS_PROTOCOL_PREFIX) && !node.startsWith(REDISS_PROTOCOL_PREFIX)) { nodes.add(REDIS_PROTOCOL_PREFIX + node); - } else { + } + else { nodes.add(node); } } return nodes.toArray(new String[0]); } + } diff --git a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/useragent/UserAgentAutoConfiguration.java b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/useragent/UserAgentAutoConfiguration.java index b13c18b69..a2192fc78 100644 --- a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/useragent/UserAgentAutoConfiguration.java +++ b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/useragent/UserAgentAutoConfiguration.java @@ -44,7 +44,6 @@ @ImportAutoConfiguration(UserAgentConfiguration.class) public class UserAgentAutoConfiguration { - /** * The type Browscap auto configuration. */ @@ -54,9 +53,8 @@ public static class BrowscapAutoConfiguration { /** * User agent parser user agent parser. - * * @return the user agent parser - * @throws IOException the io exception + * @throws IOException the io exception * @throws ParseException the parse exception */ @Bean @@ -66,7 +64,6 @@ public UserAgentParser userAgentParser() throws IOException, ParseException { /** * Browscap user agent parse browscap user agent parse. - * * @param userAgentAnalyzer the user agent analyzer * @return the browscap user agent parse */ @@ -75,6 +72,7 @@ public UserAgentParser userAgentParser() throws IOException, ParseException { public BrowscapUserAgentConverter browscapUserAgentConverter(UserAgentParser userAgentAnalyzer) { return new BrowscapUserAgentConverter(userAgentAnalyzer); } + } /** @@ -86,22 +84,16 @@ public static class YauaaAutoConfiguration { /** * User agent analyzer user agent analyzer. - * * @return the user agent analyzer */ @Bean @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) public UserAgentAnalyzer userAgentAnalyzer() { - return UserAgentAnalyzer - .newBuilder() - .hideMatcherLoadStats() - .withCache(10000) - .build(); + return UserAgentAnalyzer.newBuilder().hideMatcherLoadStats().withCache(10000).build(); } /** * Yauaa user agent parse yauaa user agent parse. - * * @param userAgentAnalyzer the user agent analyzer * @return the yauaa user agent parse */ @@ -110,5 +102,7 @@ public UserAgentAnalyzer userAgentAnalyzer() { public YauaaUserAgentConverter yauaaUserAgentConverter(UserAgentAnalyzer userAgentAnalyzer) { return new YauaaUserAgentConverter(userAgentAnalyzer); } + } + } diff --git a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/useragent/UserAgentConfiguration.java b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/useragent/UserAgentConfiguration.java index 0d2853184..333172db9 100644 --- a/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/useragent/UserAgentConfiguration.java +++ b/spring-boot-extension-autoconfigure/src/main/java/com/livk/autoconfigure/useragent/UserAgentConfiguration.java @@ -46,7 +46,6 @@ public class UserAgentConfiguration { /** * User agent helper user agent helper. - * * @param applicationContext the application context * @return the user agent helper */ @@ -65,10 +64,8 @@ public static class UserAgentMvcAutoConfiguration implements WebMvcConfigurer { private final UserAgentHelper userAgentHelper; - /** * Filter registration bean filter registration bean. - * * @return the filter registration bean */ @Bean @@ -85,6 +82,7 @@ public FilterRegistrationBean filterRegistrationBean() { public void addArgumentResolvers(List resolvers) { resolvers.add(new UserAgentResolver(userAgentHelper)); } + } /** @@ -97,10 +95,8 @@ public static class UserAgentReactiveAutoConfiguration implements WebFluxConfigu private final UserAgentHelper userAgentHelper; - /** * Reactive user agent filter reactive user agent filter. - * * @return the reactive user agent filter */ @Bean @@ -112,5 +108,7 @@ public ReactiveUserAgentFilter reactiveUserAgentFilter() { public void configureArgumentResolvers(ArgumentResolverConfigurer configurer) { configurer.addCustomResolver(new ReactiveUserAgentResolver(userAgentHelper)); } + } + } diff --git a/spring-boot-extension-starters/http-spring-boot-starter/src/main/java/com/livk/http/marker/HttpMarker.java b/spring-boot-extension-starters/http-spring-boot-starter/src/main/java/com/livk/http/marker/HttpMarker.java index 5fdb2a4b5..ea879bcb0 100644 --- a/spring-boot-extension-starters/http-spring-boot-starter/src/main/java/com/livk/http/marker/HttpMarker.java +++ b/spring-boot-extension-starters/http-spring-boot-starter/src/main/java/com/livk/http/marker/HttpMarker.java @@ -29,4 +29,5 @@ */ @NoArgsConstructor(access = AccessLevel.PRIVATE) public final class HttpMarker { + } diff --git a/spring-boot-extension-starters/lock-local-spring-boot-starter/src/main/java/com/livk/lock/marker/LockMarker.java b/spring-boot-extension-starters/lock-local-spring-boot-starter/src/main/java/com/livk/lock/marker/LockMarker.java index 255d962f6..b211244ab 100644 --- a/spring-boot-extension-starters/lock-local-spring-boot-starter/src/main/java/com/livk/lock/marker/LockMarker.java +++ b/spring-boot-extension-starters/lock-local-spring-boot-starter/src/main/java/com/livk/lock/marker/LockMarker.java @@ -29,4 +29,5 @@ */ @NoArgsConstructor(access = AccessLevel.PRIVATE) public abstract class LockMarker { + } diff --git a/spring-boot-extension-starters/oss-spring-boot-starter/src/main/java/com/livk/oss/marker/OSSMarker.java b/spring-boot-extension-starters/oss-spring-boot-starter/src/main/java/com/livk/oss/marker/OSSMarker.java index b5096e2e2..7cbe4c856 100644 --- a/spring-boot-extension-starters/oss-spring-boot-starter/src/main/java/com/livk/oss/marker/OSSMarker.java +++ b/spring-boot-extension-starters/oss-spring-boot-starter/src/main/java/com/livk/oss/marker/OSSMarker.java @@ -25,4 +25,5 @@ */ @RequiredArgsConstructor(access = AccessLevel.PRIVATE) public class OSSMarker { + } diff --git a/spring-boot-extension-tests/curator-spring-boot-test/src/main/java/com/livk/curator/util/ZookeeperUtils.java b/spring-boot-extension-tests/curator-spring-boot-test/src/main/java/com/livk/curator/util/ZookeeperUtils.java index cdb9e6b58..eee964cf3 100644 --- a/spring-boot-extension-tests/curator-spring-boot-test/src/main/java/com/livk/curator/util/ZookeeperUtils.java +++ b/spring-boot-extension-tests/curator-spring-boot-test/src/main/java/com/livk/curator/util/ZookeeperUtils.java @@ -53,7 +53,6 @@ public class ZookeeperUtils { /** * 创建空节点,默认持久节点 - * * @param path 节点路径 * @param node 节点名称 * @return 完整路径 @@ -64,26 +63,23 @@ public String createNode(String path, String node) { /** * 创建带类型的空节点 - * - * @param path 节点路径 - * @param node 节点名称 + * @param path 节点路径 + * @param node 节点名称 * @param createMode 类型 CreateMode.PERSISTENT: 创建节点后,不删除就永久存在 - * CreateMode.PERSISTENT_SEQUENTIAL:节点path末尾会追加一个10位数的单调递增的序列 - * CreateMode.EPHEMERAL:创建后,回话结束节点会自动删除 - * CreateMode.EPHEMERAL_SEQUENTIAL:节点path末尾会追加一个10位数的单调递增的序列 + * CreateMode.PERSISTENT_SEQUENTIAL:节点path末尾会追加一个10位数的单调递增的序列 + * CreateMode.EPHEMERAL:创建后,回话结束节点会自动删除 + * CreateMode.EPHEMERAL_SEQUENTIAL:节点path末尾会追加一个10位数的单调递增的序列 * @return 路径 */ public String createNode(String path, String node, CreateMode createMode) { path = buildPath(path, node); log.info("create node for path: {} with createMode: {}", path, createMode.name()); try { - curatorFramework.create() - .creatingParentsIfNeeded() - .withMode(createMode) - .forPath(path); + curatorFramework.create().creatingParentsIfNeeded().withMode(createMode).forPath(path); log.info("create node :{} successfully", node); return path; - } catch (Exception e) { + } + catch (Exception e) { log.error("create node for path: {} with createMode: {} failed!", path, createMode.name(), e); return null; } @@ -91,9 +87,8 @@ public String createNode(String path, String node, CreateMode createMode) { /** * 创建节点,默认持久节点 - * - * @param path 节点路径 - * @param node 节点名称 + * @param path 节点路径 + * @param node 节点名称 * @param value 节点值 * @return 完整路径 */ @@ -103,35 +98,31 @@ public String createNode(String path, String node, String value) { /** * 创建节点,默认持久节点 - * - * @param path 节点路径 - * @param node 节点名称 - * @param value 节点值 + * @param path 节点路径 + * @param node 节点名称 + * @param value 节点值 * @param createMode 节点类型 * @return 完整路径 */ - public String createNode(String path, String node, String value, - CreateMode createMode) { + public String createNode(String path, String node, String value, CreateMode createMode) { if (Objects.isNull(value)) { log.error("ZooKeeper节点值不能为空!"); } path = buildPath(path, node); log.info("create node for path: {}, value: {}, with createMode: {}", path, value, createMode.name()); try { - curatorFramework.create() - .creatingParentsIfNeeded() - .withMode(createMode) - .forPath(path, value.getBytes()); + curatorFramework.create().creatingParentsIfNeeded().withMode(createMode).forPath(path, value.getBytes()); return path; - } catch (Exception e) { - log.error("create node for path: {}, value: {}, with createMode: {} failed!", path, value, createMode.name(), e); + } + catch (Exception e) { + log.error("create node for path: {}, value: {}, with createMode: {} failed!", path, value, + createMode.name(), e); } return null; } /** * 获取节点数据 - * * @param path 路径 * @param node 节点名称 * @return 完整路径 @@ -143,7 +134,8 @@ public String get(String path, String node) { if (bytes.length > 0) { return new String(bytes); } - } catch (Exception e) { + } + catch (Exception e) { log.error("get value for path: {}, node: {} failed!", path, node, e); } return null; @@ -151,9 +143,8 @@ public String get(String path, String node) { /** * 更新节点数据 - * - * @param path 节点路径 - * @param node 节点名称 + * @param path 节点路径 + * @param node 节点名称 * @param value 更新值 * @return 完整路径 */ @@ -167,7 +158,8 @@ public String update(String path, String node, String value) { try { curatorFramework.setData().forPath(path, value.getBytes()); return path; - } catch (Exception e) { + } + catch (Exception e) { log.error("update path: {} to value: {} failed!", path, value); } return null; @@ -175,7 +167,6 @@ public String update(String path, String node, String value) { /** * 删除节点,并且递归删除子节点 - * * @param path 路径 * @param node 节点名称 * @return 路径 @@ -187,7 +178,8 @@ public boolean delete(String path, String node) { try { curatorFramework.delete().deletingChildrenIfNeeded().forPath(path); return true; - } catch (Exception e) { + } + catch (Exception e) { log.error("delete node for path: {} failed!", path); } return false; @@ -195,7 +187,6 @@ public boolean delete(String path, String node) { /** * 获取子节点 - * * @param path 节点路径 * @return */ @@ -210,7 +201,8 @@ public List getChildren(String path) { try { return curatorFramework.getChildren().forPath(path); - } catch (Exception e) { + } + catch (Exception e) { log.error("get children path:{} error", path, e); } return null; @@ -218,7 +210,6 @@ public List getChildren(String path) { /** * 判断节点是否存在 - * * @param path 路径 * @param node 节点名称 * @return 结果 @@ -227,17 +218,17 @@ public boolean exists(String path, String node) { try { List list = getChildren(path); return !CollectionUtils.isEmpty(list) && list.contains(node); - } catch (Exception e) { + } + catch (Exception e) { return false; } } /** * 申请锁,指定请求等待时间 - * - * @param path 加锁zk节点 - * @param time 时间 - * @param unit 时间单位 + * @param path 加锁zk节点 + * @param time 时间 + * @param unit 时间单位 * @param runnable 执行方法 */ public void lock(String path, long time, TimeUnit unit, Runnable runnable) { @@ -246,40 +237,44 @@ public void lock(String path, long time, TimeUnit unit, Runnable runnable) { if (lock.acquire(time, unit)) { try { runnable.run(); - } finally { + } + finally { lock.release(); } - } else { + } + else { log.error("获取锁超时:{}!", path); } - } catch (Exception e) { + } + catch (Exception e) { log.error("获取锁失败: {}!", path); } } /** * 申请锁,指定请求等待时间 - * - * @param path 加锁zk节点 - * @param time 时间 - * @param unit 时间单位 + * @param path 加锁zk节点 + * @param time 时间 + * @param unit 时间单位 * @param callable 执行方法 * @return . */ - public T lock(String path, long time, TimeUnit unit, - Callable callable) { + public T lock(String path, long time, TimeUnit unit, Callable callable) { try { InterProcessMutex lock = new InterProcessMutex(curatorFramework, path); if (lock.acquire(time, unit)) { try { return callable.call(); - } finally { + } + finally { lock.release(); } - } else { + } + else { log.error("获取锁超时:{}!", path); } - } catch (Exception e) { + } + catch (Exception e) { log.error("获取锁失败: {}!", path); } return null; @@ -289,7 +284,6 @@ public T lock(String path, long time, TimeUnit unit, /** * 对一个节点进行监听,监听事件包括指定的路径节点的增、删、改的操作 - * * @param path 节点路径 */ @@ -302,15 +296,15 @@ public void watchNode(String path, boolean dataIsCompressed) { log.info("ZNode节点状态改变, stat={}", data.getStat()); }); curatorCache.start(); - } catch (Exception e) { + } + catch (Exception e) { log.error("创建NodeCache监听失败, path={}", path); } } /** * 对指定的路径节点的一级子目录进行监听,不对该节点的操作进行监听,对其子目录的节点进行增、删、改的操作监听 - * - * @param path 节点路径 + * @param path 节点路径 * @param listener 回调方法 */ public void watchChildren(String path, CuratorCacheListener listener) { @@ -318,16 +312,15 @@ public void watchChildren(String path, CuratorCacheListener listener) { CuratorCache curatorCache = CuratorCache.build(curatorFramework, path); curatorCache.start(); curatorCache.listenable().addListener(listener); - } catch (Exception e) { + } + catch (Exception e) { log.error("watch children failed for path: {}", path, e); } } /** - * 将指定的路径节点作为根节点(祖先节点),对其所有的子节点操作进行监听,呈现树形目录的监听,可以设置监听深度,最大监听深度为2147483647( - * int类型的最大值) - * - * @param path 节点路径 + * 将指定的路径节点作为根节点(祖先节点),对其所有的子节点操作进行监听,呈现树形目录的监听,可以设置监听深度,最大监听深度为2147483647( int类型的最大值) + * @param path 节点路径 * @param maxDepth 回调方法 * @param listener 监听 */ @@ -336,7 +329,8 @@ public void watchTree(String path, int maxDepth, CuratorCacheListener listener) CuratorCache curatorCache = CuratorCache.build(curatorFramework, path); curatorCache.start(); curatorCache.listenable().addListener(listener); - } catch (Exception e) { + } + catch (Exception e) { log.error("watch tree failed for path: {}", path, e); } } @@ -352,7 +346,8 @@ public String buildPath(String path, String node) { if (PATH_SEPARATOR.equals(path)) { return path + node; - } else { + } + else { return path + PATH_SEPARATOR + node; } } diff --git a/spring-boot-extension-tests/curator-spring-boot-test/src/test/java/com/livk/curator/CuratorAppTest.java b/spring-boot-extension-tests/curator-spring-boot-test/src/test/java/com/livk/curator/CuratorAppTest.java index a4e6b240e..86a908b1e 100644 --- a/spring-boot-extension-tests/curator-spring-boot-test/src/test/java/com/livk/curator/CuratorAppTest.java +++ b/spring-boot-extension-tests/curator-spring-boot-test/src/test/java/com/livk/curator/CuratorAppTest.java @@ -37,4 +37,5 @@ class CuratorAppTest { public void test() { assertNotNull(curatorFramework); } + } diff --git a/spring-boot-extension-tests/disruptor-spring-boot-test/src/main/java/com/livk/disruptor/DisruptorApp.java b/spring-boot-extension-tests/disruptor-spring-boot-test/src/main/java/com/livk/disruptor/DisruptorApp.java index 837d50b59..f424cea77 100644 --- a/spring-boot-extension-tests/disruptor-spring-boot-test/src/main/java/com/livk/disruptor/DisruptorApp.java +++ b/spring-boot-extension-tests/disruptor-spring-boot-test/src/main/java/com/livk/disruptor/DisruptorApp.java @@ -11,7 +11,9 @@ @EnableDisruptor(basePackageClasses = MessageModel.class) @SpringBootApplication public class DisruptorApp { + public static void main(String[] args) { SpringLauncher.run(args); } + } diff --git a/spring-boot-extension-tests/disruptor-spring-boot-test/src/main/java/com/livk/disruptor/consumer/MessageModelConsumer.java b/spring-boot-extension-tests/disruptor-spring-boot-test/src/main/java/com/livk/disruptor/consumer/MessageModelConsumer.java index 19250788c..4bf8d80ea 100644 --- a/spring-boot-extension-tests/disruptor-spring-boot-test/src/main/java/com/livk/disruptor/consumer/MessageModelConsumer.java +++ b/spring-boot-extension-tests/disruptor-spring-boot-test/src/main/java/com/livk/disruptor/consumer/MessageModelConsumer.java @@ -16,4 +16,5 @@ public class MessageModelConsumer implements DisruptorEventConsumer sendBatch() { disruptorMqService.batch(messages); return ResponseEntity.ok().build(); } + } diff --git a/spring-boot-extension-tests/disruptor-spring-boot-test/src/main/java/com/livk/disruptor/event/MessageModel.java b/spring-boot-extension-tests/disruptor-spring-boot-test/src/main/java/com/livk/disruptor/event/MessageModel.java index 01a2496c0..e41b1370c 100644 --- a/spring-boot-extension-tests/disruptor-spring-boot-test/src/main/java/com/livk/disruptor/event/MessageModel.java +++ b/spring-boot-extension-tests/disruptor-spring-boot-test/src/main/java/com/livk/disruptor/event/MessageModel.java @@ -11,5 +11,7 @@ @Builder @DisruptorEvent("messageDisruptorAuto") public class MessageModel { + private String message; + } diff --git a/spring-boot-extension-tests/disruptor-spring-boot-test/src/main/java/com/livk/disruptor/service/DisruptorMqService.java b/spring-boot-extension-tests/disruptor-spring-boot-test/src/main/java/com/livk/disruptor/service/DisruptorMqService.java index 710844d86..d7399ee1d 100644 --- a/spring-boot-extension-tests/disruptor-spring-boot-test/src/main/java/com/livk/disruptor/service/DisruptorMqService.java +++ b/spring-boot-extension-tests/disruptor-spring-boot-test/src/main/java/com/livk/disruptor/service/DisruptorMqService.java @@ -10,4 +10,5 @@ public interface DisruptorMqService { void send(String message); void batch(List messages); + } diff --git a/spring-boot-extension-tests/disruptor-spring-boot-test/src/main/java/com/livk/disruptor/service/impl/DisruptorMqServiceImpl.java b/spring-boot-extension-tests/disruptor-spring-boot-test/src/main/java/com/livk/disruptor/service/impl/DisruptorMqServiceImpl.java index 893f8d77c..7ec6a4e14 100644 --- a/spring-boot-extension-tests/disruptor-spring-boot-test/src/main/java/com/livk/disruptor/service/impl/DisruptorMqServiceImpl.java +++ b/spring-boot-extension-tests/disruptor-spring-boot-test/src/main/java/com/livk/disruptor/service/impl/DisruptorMqServiceImpl.java @@ -30,13 +30,12 @@ public void send(String message) { @Override public void batch(List messages) { - List messageModels = messages.stream() - .map(this::toMessageModel) - .toList(); + List messageModels = messages.stream().map(this::toMessageModel).toList(); producer.sendBatch(messageModels); } private MessageModel toMessageModel(String message) { return MessageModel.builder().message(message).build(); } + } diff --git a/spring-boot-extension-tests/disruptor-spring-boot-test/src/test/java/com/livk/disruptor/controller/DisruptorMqControllerTest.java b/spring-boot-extension-tests/disruptor-spring-boot-test/src/test/java/com/livk/disruptor/controller/DisruptorMqControllerTest.java index 004f7f9f7..20ec2ef82 100644 --- a/spring-boot-extension-tests/disruptor-spring-boot-test/src/test/java/com/livk/disruptor/controller/DisruptorMqControllerTest.java +++ b/spring-boot-extension-tests/disruptor-spring-boot-test/src/test/java/com/livk/disruptor/controller/DisruptorMqControllerTest.java @@ -22,15 +22,12 @@ class DisruptorMqControllerTest { @Test void send() throws Exception { - mockMvc.perform(post("/msg")) - .andDo(print()) - .andExpect(status().isOk()); + mockMvc.perform(post("/msg")).andDo(print()).andExpect(status().isOk()); } @Test void sendBatch() throws Exception { - mockMvc.perform(post("/msg/batch")) - .andDo(print()) - .andExpect(status().isOk()); + mockMvc.perform(post("/msg/batch")).andDo(print()).andExpect(status().isOk()); } + } diff --git a/spring-boot-extension-tests/dynamic-spring-boot-test/src/main/java/com/livk/dynamic/DynamicApp.java b/spring-boot-extension-tests/dynamic-spring-boot-test/src/main/java/com/livk/dynamic/DynamicApp.java index d5a58e369..40e25d734 100644 --- a/spring-boot-extension-tests/dynamic-spring-boot-test/src/main/java/com/livk/dynamic/DynamicApp.java +++ b/spring-boot-extension-tests/dynamic-spring-boot-test/src/main/java/com/livk/dynamic/DynamicApp.java @@ -27,7 +27,9 @@ @EnableDynamicDatasource @SpringBootApplication public class DynamicApp { + public static void main(String[] args) { SpringLauncher.run(args); } + } diff --git a/spring-boot-extension-tests/dynamic-spring-boot-test/src/main/java/com/livk/dynamic/entity/User.java b/spring-boot-extension-tests/dynamic-spring-boot-test/src/main/java/com/livk/dynamic/entity/User.java index 23f1eb151..2fa8b48f2 100644 --- a/spring-boot-extension-tests/dynamic-spring-boot-test/src/main/java/com/livk/dynamic/entity/User.java +++ b/spring-boot-extension-tests/dynamic-spring-boot-test/src/main/java/com/livk/dynamic/entity/User.java @@ -34,4 +34,5 @@ public class User { private String username; private String password; + } diff --git a/spring-boot-extension-tests/dynamic-spring-boot-test/src/main/java/com/livk/dynamic/mapper/UserMapper.java b/spring-boot-extension-tests/dynamic-spring-boot-test/src/main/java/com/livk/dynamic/mapper/UserMapper.java index 1b60d444d..568d588ed 100644 --- a/spring-boot-extension-tests/dynamic-spring-boot-test/src/main/java/com/livk/dynamic/mapper/UserMapper.java +++ b/spring-boot-extension-tests/dynamic-spring-boot-test/src/main/java/com/livk/dynamic/mapper/UserMapper.java @@ -39,4 +39,5 @@ public interface UserMapper { @Select("select * from ${table}") List selectList(String table); + } diff --git a/spring-boot-extension-tests/dynamic-spring-boot-test/src/test/java/com/livk/dynamic/controller/DataSourceInit.java b/spring-boot-extension-tests/dynamic-spring-boot-test/src/test/java/com/livk/dynamic/controller/DataSourceInit.java index 459263c9a..b94c5a7a0 100644 --- a/spring-boot-extension-tests/dynamic-spring-boot-test/src/test/java/com/livk/dynamic/controller/DataSourceInit.java +++ b/spring-boot-extension-tests/dynamic-spring-boot-test/src/test/java/com/livk/dynamic/controller/DataSourceInit.java @@ -51,4 +51,5 @@ public void afterPropertiesSet() throws Exception { ScriptUtils.executeSqlScript(applicationContext.getBean(DataSource.class).getConnection(), initPgsql); DataSourceContextHolder.clear(); } + } diff --git a/spring-boot-extension-tests/dynamic-spring-boot-test/src/test/java/com/livk/dynamic/controller/UserControllerTest.java b/spring-boot-extension-tests/dynamic-spring-boot-test/src/test/java/com/livk/dynamic/controller/UserControllerTest.java index d6c193fee..4bf09bdb3 100644 --- a/spring-boot-extension-tests/dynamic-spring-boot-test/src/test/java/com/livk/dynamic/controller/UserControllerTest.java +++ b/spring-boot-extension-tests/dynamic-spring-boot-test/src/test/java/com/livk/dynamic/controller/UserControllerTest.java @@ -59,9 +59,7 @@ void testMysqlSave() throws Exception { @Order(2) @Test void testMysqlUser() throws Exception { - mockMvc.perform(get("/user/mysql")) - .andDo(print()) - .andExpect(status().isOk()); + mockMvc.perform(get("/user/mysql")).andDo(print()).andExpect(status().isOk()); } @Order(3) @@ -76,10 +74,10 @@ void testPgsqlSave() throws Exception { @Order(4) @Test void testPgsqlUser() throws Exception { - mockMvc.perform(get("/user/pgsql")) - .andDo(print()) - .andExpect(status().isOk()); + mockMvc.perform(get("/user/pgsql")).andDo(print()).andExpect(status().isOk()); } + } -//Generated with love by TestMe :) Please report issues and submit feature requests at: http://weirddev.com/forum#!/testme +// Generated with love by TestMe :) Please report issues and submit feature requests at: +// http://weirddev.com/forum#!/testme diff --git a/spring-boot-extension-tests/easyexcel-spring-boot-test/easyexcel-spring-boot-test-webflux/src/main/java/com/livk/excel/reactive/ReactiveExcelApp.java b/spring-boot-extension-tests/easyexcel-spring-boot-test/easyexcel-spring-boot-test-webflux/src/main/java/com/livk/excel/reactive/ReactiveExcelApp.java index 3af0ff66b..ac0777084 100644 --- a/spring-boot-extension-tests/easyexcel-spring-boot-test/easyexcel-spring-boot-test-webflux/src/main/java/com/livk/excel/reactive/ReactiveExcelApp.java +++ b/spring-boot-extension-tests/easyexcel-spring-boot-test/easyexcel-spring-boot-test-webflux/src/main/java/com/livk/excel/reactive/ReactiveExcelApp.java @@ -33,4 +33,5 @@ public class ReactiveExcelApp { public static void main(String[] args) { SpringLauncher.run(args); } + } diff --git a/spring-boot-extension-tests/easyexcel-spring-boot-test/easyexcel-spring-boot-test-webflux/src/main/java/com/livk/excel/reactive/controller/Info2Controller.java b/spring-boot-extension-tests/easyexcel-spring-boot-test/easyexcel-spring-boot-test-webflux/src/main/java/com/livk/excel/reactive/controller/Info2Controller.java index 0bd7f1d7a..ee913bac9 100644 --- a/spring-boot-extension-tests/easyexcel-spring-boot-test/easyexcel-spring-boot-test-webflux/src/main/java/com/livk/excel/reactive/controller/Info2Controller.java +++ b/spring-boot-extension-tests/easyexcel-spring-boot-test/easyexcel-spring-boot-test-webflux/src/main/java/com/livk/excel/reactive/controller/Info2Controller.java @@ -44,7 +44,8 @@ public class Info2Controller { @RequestExcel @PostMapping("uploadAndDownload") public Map> uploadAndDownload(@ExcelParam Map> mapData) { - return mapData.values().stream() + return mapData.values() + .stream() .flatMap(Collection::stream) .collect(Collectors.groupingBy(info -> String.valueOf(Long.parseLong(info.getPhone()) % 10))); } @@ -54,4 +55,5 @@ public Map> download(@RequestBody List dataExcels) { return dataExcels.stream() .collect(Collectors.groupingBy(info -> String.valueOf(Long.parseLong(info.getPhone()) % 10))); } + } diff --git a/spring-boot-extension-tests/easyexcel-spring-boot-test/easyexcel-spring-boot-test-webflux/src/main/java/com/livk/excel/reactive/controller/InfoController.java b/spring-boot-extension-tests/easyexcel-spring-boot-test/easyexcel-spring-boot-test-webflux/src/main/java/com/livk/excel/reactive/controller/InfoController.java index 3a40f4b02..a0b4b3d1e 100644 --- a/spring-boot-extension-tests/easyexcel-spring-boot-test/easyexcel-spring-boot-test-webflux/src/main/java/com/livk/excel/reactive/controller/InfoController.java +++ b/spring-boot-extension-tests/easyexcel-spring-boot-test/easyexcel-spring-boot-test-webflux/src/main/java/com/livk/excel/reactive/controller/InfoController.java @@ -75,4 +75,5 @@ public Mono> uploadDownLoadMono(@ExcelParam Mono> dataExce public Flux uploadDownLoadFlux(@ExcelParam Mono> dataExcels) { return dataExcels.flatMapMany(Flux::fromIterable); } + } diff --git a/spring-boot-extension-tests/easyexcel-spring-boot-test/easyexcel-spring-boot-test-webflux/src/test/java/com/livk/excel/reactive/controller/Info2ControllerTest.java b/spring-boot-extension-tests/easyexcel-spring-boot-test/easyexcel-spring-boot-test-webflux/src/test/java/com/livk/excel/reactive/controller/Info2ControllerTest.java index 2a37a6c58..f6a0da748 100644 --- a/spring-boot-extension-tests/easyexcel-spring-boot-test/easyexcel-spring-boot-test-webflux/src/test/java/com/livk/excel/reactive/controller/Info2ControllerTest.java +++ b/spring-boot-extension-tests/easyexcel-spring-boot-test/easyexcel-spring-boot-test-webflux/src/test/java/com/livk/excel/reactive/controller/Info2ControllerTest.java @@ -49,13 +49,13 @@ class Info2ControllerTest { static MultipartBodyBuilder builder = new MultipartBodyBuilder(); + @Autowired WebTestClient client; @BeforeAll public static void before() { - builder.part("file", new ClassPathResource("outFile.xls")) - .filename("file"); + builder.part("file", new ClassPathResource("outFile.xls")).filename("file"); } @Test @@ -69,8 +69,10 @@ void uploadAndDownload() { .expectBody(Resource.class) .value(resource -> { try { - FileUtils.download(resource.getInputStream(), "./infoUploadDownLoad" + ResponseExcel.Suffix.XLSM.getName()); - } catch (IOException e) { + FileUtils.download(resource.getInputStream(), + "./infoUploadDownLoad" + ResponseExcel.Suffix.XLSM.getName()); + } + catch (IOException e) { throw new RuntimeException(e); } }); @@ -93,8 +95,10 @@ void download() { .expectBody(Resource.class) .value(resource -> { try { - FileUtils.download(resource.getInputStream(), "./infoDownload" + ResponseExcel.Suffix.XLSM.getName()); - } catch (IOException e) { + FileUtils.download(resource.getInputStream(), + "./infoDownload" + ResponseExcel.Suffix.XLSM.getName()); + } + catch (IOException e) { throw new RuntimeException(e); } }); @@ -102,4 +106,5 @@ void download() { assertTrue(outFile.exists()); assertTrue(outFile.delete()); } + } diff --git a/spring-boot-extension-tests/easyexcel-spring-boot-test/easyexcel-spring-boot-test-webflux/src/test/java/com/livk/excel/reactive/controller/InfoControllerTest.java b/spring-boot-extension-tests/easyexcel-spring-boot-test/easyexcel-spring-boot-test-webflux/src/test/java/com/livk/excel/reactive/controller/InfoControllerTest.java index 25106ea79..c00daccae 100644 --- a/spring-boot-extension-tests/easyexcel-spring-boot-test/easyexcel-spring-boot-test-webflux/src/test/java/com/livk/excel/reactive/controller/InfoControllerTest.java +++ b/spring-boot-extension-tests/easyexcel-spring-boot-test/easyexcel-spring-boot-test-webflux/src/test/java/com/livk/excel/reactive/controller/InfoControllerTest.java @@ -47,13 +47,13 @@ class InfoControllerTest { static MultipartBodyBuilder builder = new MultipartBodyBuilder(); + @Autowired WebTestClient client; @BeforeAll public static void before() { - builder.part("file", new ClassPathResource("outFile.xls")) - .filename("file"); + builder.part("file", new ClassPathResource("outFile.xls")).filename("file"); } @Test @@ -91,8 +91,10 @@ void uploadDownLoadMono() { .expectBody(Resource.class) .value(resource -> { try { - FileUtils.download(resource.getInputStream(), "./uploadDownLoad" + ResponseExcel.Suffix.XLS.getName()); - } catch (IOException e) { + FileUtils.download(resource.getInputStream(), + "./uploadDownLoad" + ResponseExcel.Suffix.XLS.getName()); + } + catch (IOException e) { throw new RuntimeException(e); } }); @@ -112,8 +114,10 @@ void testUploadDownLoadMono() { .expectBody(Resource.class) .value(resource -> { try { - FileUtils.download(resource.getInputStream(), "./uploadDownLoadMono" + ResponseExcel.Suffix.XLS.getName()); - } catch (IOException e) { + FileUtils.download(resource.getInputStream(), + "./uploadDownLoadMono" + ResponseExcel.Suffix.XLS.getName()); + } + catch (IOException e) { throw new RuntimeException(e); } }); @@ -133,8 +137,10 @@ void uploadDownLoadFlux() { .expectBody(Resource.class) .value(resource -> { try { - FileUtils.download(resource.getInputStream(), "./uploadDownLoadFlux" + ResponseExcel.Suffix.XLS.getName()); - } catch (IOException e) { + FileUtils.download(resource.getInputStream(), + "./uploadDownLoadFlux" + ResponseExcel.Suffix.XLS.getName()); + } + catch (IOException e) { throw new RuntimeException(e); } }); @@ -142,4 +148,5 @@ void uploadDownLoadFlux() { assertTrue(outFile.exists()); assertTrue(outFile.delete()); } + } diff --git a/spring-boot-extension-tests/easyexcel-spring-boot-test/easyexcel-spring-boot-test-webmvc/src/main/java/com/livk/excel/mvc/controller/Info2Controller.java b/spring-boot-extension-tests/easyexcel-spring-boot-test/easyexcel-spring-boot-test-webmvc/src/main/java/com/livk/excel/mvc/controller/Info2Controller.java index c5fda6a26..524ea8ff5 100644 --- a/spring-boot-extension-tests/easyexcel-spring-boot-test/easyexcel-spring-boot-test-webmvc/src/main/java/com/livk/excel/mvc/controller/Info2Controller.java +++ b/spring-boot-extension-tests/easyexcel-spring-boot-test/easyexcel-spring-boot-test-webmvc/src/main/java/com/livk/excel/mvc/controller/Info2Controller.java @@ -44,7 +44,8 @@ public class Info2Controller { @RequestExcel @PostMapping("uploadAndDownload") public Map> uploadAndDownload(@ExcelParam Map> mapData) { - return mapData.values().stream() + return mapData.values() + .stream() .flatMap(Collection::stream) .collect(Collectors.groupingBy(info -> String.valueOf(Long.parseLong(info.getPhone()) % 10))); } @@ -54,4 +55,5 @@ public Map> download(@RequestBody List dataExcels) { return dataExcels.stream() .collect(Collectors.groupingBy(info -> String.valueOf(Long.parseLong(info.getPhone()) % 10))); } + } diff --git a/spring-boot-extension-tests/easyexcel-spring-boot-test/easyexcel-spring-boot-test-webmvc/src/main/java/com/livk/excel/mvc/controller/InfoController.java b/spring-boot-extension-tests/easyexcel-spring-boot-test/easyexcel-spring-boot-test-webmvc/src/main/java/com/livk/excel/mvc/controller/InfoController.java index 41bb19450..e3efc45de 100644 --- a/spring-boot-extension-tests/easyexcel-spring-boot-test/easyexcel-spring-boot-test-webmvc/src/main/java/com/livk/excel/mvc/controller/InfoController.java +++ b/spring-boot-extension-tests/easyexcel-spring-boot-test/easyexcel-spring-boot-test-webmvc/src/main/java/com/livk/excel/mvc/controller/InfoController.java @@ -54,13 +54,13 @@ public class InfoController { @RequestExcel(parse = InfoExcelListener.class) @PostMapping("upload") public HttpEntity upload(@ExcelParam List dataExcels, - @RequestParam(defaultValue = "false") Boolean async, - @RequestParam(defaultValue = "1") Integer multiple) { + @RequestParam(defaultValue = "false") Boolean async, @RequestParam(defaultValue = "1") Integer multiple) { List infos = this.multiple(dataExcels, multiple); log.info("size:{},async:{},multiple:{}", infos.size(), async, multiple); if (async) { infoService.insertBatchMultithreading(infos); - } else { + } + else { infoService.insertBatch(infos); } return ResponseEntity.ok(Boolean.TRUE); @@ -94,4 +94,5 @@ public Map> download(@RequestBody List dataExcels) { return dataExcels.stream() .collect(Collectors.groupingBy(info -> String.valueOf(Long.parseLong(info.getPhone()) % 10))); } + } diff --git a/spring-boot-extension-tests/easyexcel-spring-boot-test/easyexcel-spring-boot-test-webmvc/src/main/java/com/livk/excel/mvc/service/impl/InfoServiceImpl.java b/spring-boot-extension-tests/easyexcel-spring-boot-test/easyexcel-spring-boot-test-webmvc/src/main/java/com/livk/excel/mvc/service/impl/InfoServiceImpl.java index 62ef7445e..2762e81f2 100644 --- a/spring-boot-extension-tests/easyexcel-spring-boot-test/easyexcel-spring-boot-test-webmvc/src/main/java/com/livk/excel/mvc/service/impl/InfoServiceImpl.java +++ b/spring-boot-extension-tests/easyexcel-spring-boot-test/easyexcel-spring-boot-test-webmvc/src/main/java/com/livk/excel/mvc/service/impl/InfoServiceImpl.java @@ -55,7 +55,8 @@ public void insertBatch(List records) { for (List infos : partition) { try { infoMapper.insertBatch(infos); - } catch (Exception e) { + } + catch (Exception e) { log.error("msg:{}", e.getMessage(), e); sqlSession.rollback(); break; @@ -72,24 +73,23 @@ public void insertBatch(List records) { } public void insertBatchMultithreading(List records) { - ThreadPoolExecutor executor = new ThreadPoolExecutor(10, 20, - 0L, TimeUnit.MILLISECONDS, - new LinkedBlockingQueue<>()); + ThreadPoolExecutor executor = new ThreadPoolExecutor(10, 20, 0L, TimeUnit.MILLISECONDS, + new LinkedBlockingQueue<>()); SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, false); InfoMapper infoMapper = sqlSession.getMapper(InfoMapper.class); List> partition = Lists.partition(records, (int) Math.pow(1000, 2)); - List> callables = partition.stream() - .map((Function, Callable>) infos -> { - List> lists = Lists.partition(infos, 1000); - for (List list : lists) { - try { - infoMapper.insertBatch(list); - } catch (Exception e) { - return () -> 0; - } + List> callables = partition.stream().map((Function, Callable>) infos -> { + List> lists = Lists.partition(infos, 1000); + for (List list : lists) { + try { + infoMapper.insertBatch(list); + } + catch (Exception e) { + return () -> 0; } - return () -> 1; - }).toList(); + } + return () -> 1; + }).toList(); try { List> futures = executor.invokeAll(callables); for (Future future : futures) { @@ -98,11 +98,13 @@ public void insertBatchMultithreading(List records) { break; } } - } catch (InterruptedException | ExecutionException e) { + } + catch (InterruptedException | ExecutionException e) { throw new RuntimeException(e); } sqlSession.commit(); sqlSession.clearCache(); sqlSession.close(); } + } diff --git a/spring-boot-extension-tests/easyexcel-spring-boot-test/easyexcel-spring-boot-test-webmvc/src/test/java/com/livk/excel/mvc/controller/Info2ControllerTest.java b/spring-boot-extension-tests/easyexcel-spring-boot-test/easyexcel-spring-boot-test-webmvc/src/test/java/com/livk/excel/mvc/controller/Info2ControllerTest.java index b7b5b394a..d1b0be109 100644 --- a/spring-boot-extension-tests/easyexcel-spring-boot-test/easyexcel-spring-boot-test-webmvc/src/test/java/com/livk/excel/mvc/controller/Info2ControllerTest.java +++ b/spring-boot-extension-tests/easyexcel-spring-boot-test/easyexcel-spring-boot-test-webmvc/src/test/java/com/livk/excel/mvc/controller/Info2ControllerTest.java @@ -50,11 +50,8 @@ * @author livk */ @AutoConfigureMockMvc -@SpringBootTest({ - "spring.datasource.driver-class-name=org.h2.Driver", - "spring.datasource.url=jdbc:h2:mem:test", - "spring.sql.init.mode=never" -}) +@SpringBootTest({ "spring.datasource.driver-class-name=org.h2.Driver", "spring.datasource.url=jdbc:h2:mem:test", + "spring.sql.init.mode=never" }) class Info2ControllerTest { @Autowired @@ -62,15 +59,15 @@ class Info2ControllerTest { ClassPathResource resource = new ClassPathResource("outFile.xls"); - MockMultipartFile file = new MockMultipartFile("file", "outFile.xls", MediaType.MULTIPART_FORM_DATA_VALUE, resource.getInputStream()); + MockMultipartFile file = new MockMultipartFile("file", "outFile.xls", MediaType.MULTIPART_FORM_DATA_VALUE, + resource.getInputStream()); Info2ControllerTest() throws IOException { } @Test void uploadAndDownload() throws Exception { - mockMvc.perform(multipart(POST, "/info/uploadAndDownload") - .file(file)) + mockMvc.perform(multipart(POST, "/info/uploadAndDownload").file(file)) .andExpect(status().isOk()) .andDo(result -> { ByteArrayInputStream in = new ByteArrayInputStream(result.getResponse().getContentAsByteArray()); @@ -86,7 +83,8 @@ void download() throws Exception { List infos = LongStream.rangeClosed(1, 100) .mapToObj(i -> new Info(i, String.valueOf(13_000_000_000L + i))) .toList(); - mockMvc.perform(MockMvcRequestBuilders.post("/info/download") + mockMvc + .perform(MockMvcRequestBuilders.post("/info/download") .contentType(MediaType.APPLICATION_JSON) .content(JsonMapperUtils.writeValueAsString(infos))) .andExpect(status().isOk()) @@ -98,4 +96,5 @@ void download() throws Exception { assertTrue(outFile.exists()); assertTrue(outFile.delete()); } + } diff --git a/spring-boot-extension-tests/easyexcel-spring-boot-test/easyexcel-spring-boot-test-webmvc/src/test/java/com/livk/excel/mvc/controller/InfoControllerTest.java b/spring-boot-extension-tests/easyexcel-spring-boot-test/easyexcel-spring-boot-test-webmvc/src/test/java/com/livk/excel/mvc/controller/InfoControllerTest.java index 424c341d8..183fbb4c0 100644 --- a/spring-boot-extension-tests/easyexcel-spring-boot-test/easyexcel-spring-boot-test-webmvc/src/test/java/com/livk/excel/mvc/controller/InfoControllerTest.java +++ b/spring-boot-extension-tests/easyexcel-spring-boot-test/easyexcel-spring-boot-test-webmvc/src/test/java/com/livk/excel/mvc/controller/InfoControllerTest.java @@ -46,11 +46,8 @@ * @author livk */ @AutoConfigureMockMvc -@SpringBootTest({ - "spring.datasource.driver-class-name=org.h2.Driver", - "spring.datasource.url=jdbc:h2:mem:test", - "spring.sql.init.mode=never" -}) +@SpringBootTest({ "spring.datasource.driver-class-name=org.h2.Driver", "spring.datasource.url=jdbc:h2:mem:test", + "spring.sql.init.mode=never" }) class InfoControllerTest { @Autowired @@ -58,30 +55,26 @@ class InfoControllerTest { ClassPathResource resource = new ClassPathResource("outFile.xls"); - MockMultipartFile file = new MockMultipartFile("file", "outFile.xls", MediaType.MULTIPART_FORM_DATA_VALUE, resource.getInputStream()); + MockMultipartFile file = new MockMultipartFile("file", "outFile.xls", MediaType.MULTIPART_FORM_DATA_VALUE, + resource.getInputStream()); InfoControllerTest() throws IOException { } @Test void uploadList() throws Exception { - mockMvc.perform(multipart(POST, "/uploadList") - .file(file)) - .andDo(print()) - .andExpect(status().isOk()); + mockMvc.perform(multipart(POST, "/uploadList").file(file)).andDo(print()).andExpect(status().isOk()); } @Test void uploadAndDownload() throws Exception { - mockMvc.perform(multipart(POST, "/uploadAndDownload") - .file(file)) - .andExpect(status().isOk()) - .andDo(result -> { - ByteArrayInputStream in = new ByteArrayInputStream(result.getResponse().getContentAsByteArray()); - FileUtils.download(in, "./uploadAndDownloadMock" + ResponseExcel.Suffix.XLSM.getName()); - }); + mockMvc.perform(multipart(POST, "/uploadAndDownload").file(file)).andExpect(status().isOk()).andDo(result -> { + ByteArrayInputStream in = new ByteArrayInputStream(result.getResponse().getContentAsByteArray()); + FileUtils.download(in, "./uploadAndDownloadMock" + ResponseExcel.Suffix.XLSM.getName()); + }); File outFile = new File("./uploadAndDownloadMock" + ResponseExcel.Suffix.XLSM.getName()); assertTrue(outFile.exists()); assertTrue(outFile.delete()); } + } diff --git a/spring-boot-extension-tests/http-spring-boot-test/src/main/java/com/livk/http/HttpInterfaceApp.java b/spring-boot-extension-tests/http-spring-boot-test/src/main/java/com/livk/http/HttpInterfaceApp.java index 54ed70669..f8843b0b4 100644 --- a/spring-boot-extension-tests/http-spring-boot-test/src/main/java/com/livk/http/HttpInterfaceApp.java +++ b/spring-boot-extension-tests/http-spring-boot-test/src/main/java/com/livk/http/HttpInterfaceApp.java @@ -29,4 +29,5 @@ public class HttpInterfaceApp { public static void main(String[] args) { SpringLauncher.run(args); } + } diff --git a/spring-boot-extension-tests/http-spring-boot-test/src/test/java/com/livk/http/controller/HttpControllerTest.java b/spring-boot-extension-tests/http-spring-boot-test/src/test/java/com/livk/http/controller/HttpControllerTest.java index f999e5770..132662548 100644 --- a/spring-boot-extension-tests/http-spring-boot-test/src/test/java/com/livk/http/controller/HttpControllerTest.java +++ b/spring-boot-extension-tests/http-spring-boot-test/src/test/java/com/livk/http/controller/HttpControllerTest.java @@ -38,9 +38,8 @@ * @author livk */ @AutoConfigureMockMvc -@SpringBootTest(value = { - "logging.level.org.springframework.web.reactive.function.client.WebClient = debug" -}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) +@SpringBootTest(value = { "logging.level.org.springframework.web.reactive.function.client.WebClient = debug" }, + webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) class HttpControllerTest { @Autowired @@ -55,4 +54,5 @@ void getTest() throws Exception { .andExpect(jsonPath("spring-version", SpringVersion.getVersion()).exists()) .andExpect(jsonPath("java-version", System.getProperty("java.version")).exists()); } + } diff --git a/spring-boot-extension-tests/ip2region-spring-boot-test/ip2region-spring-boot-test-webmvc/src/main/java/com/livk/ip2region/mvc/MvcIp2RegionApp.java b/spring-boot-extension-tests/ip2region-spring-boot-test/ip2region-spring-boot-test-webmvc/src/main/java/com/livk/ip2region/mvc/MvcIp2RegionApp.java index 8fa9eedee..a9ed3b763 100644 --- a/spring-boot-extension-tests/ip2region-spring-boot-test/ip2region-spring-boot-test-webmvc/src/main/java/com/livk/ip2region/mvc/MvcIp2RegionApp.java +++ b/spring-boot-extension-tests/ip2region-spring-boot-test/ip2region-spring-boot-test-webmvc/src/main/java/com/livk/ip2region/mvc/MvcIp2RegionApp.java @@ -25,7 +25,9 @@ */ @SpringBootApplication public class MvcIp2RegionApp { + public static void main(String[] args) { SpringLauncher.run(args); } + } diff --git a/spring-boot-extension-tests/ip2region-spring-boot-test/ip2region-spring-boot-test-webmvc/src/main/java/com/livk/ip2region/mvc/controller/Ip2RegionController.java b/spring-boot-extension-tests/ip2region-spring-boot-test/ip2region-spring-boot-test-webmvc/src/main/java/com/livk/ip2region/mvc/controller/Ip2RegionController.java index ae3e11baa..b3a2f9569 100644 --- a/spring-boot-extension-tests/ip2region-spring-boot-test/ip2region-spring-boot-test-webmvc/src/main/java/com/livk/ip2region/mvc/controller/Ip2RegionController.java +++ b/spring-boot-extension-tests/ip2region-spring-boot-test/ip2region-spring-boot-test-webmvc/src/main/java/com/livk/ip2region/mvc/controller/Ip2RegionController.java @@ -51,4 +51,5 @@ public HttpEntity> post(@RequestIp IpInfo ipInfo) { log.info("ip:{}", RequestIpContextHolder.get()); return ResponseEntity.ok(List.of(ipInfo, requestIpInfo.currentIpInfo())); } + } diff --git a/spring-boot-extension-tests/ip2region-spring-boot-test/ip2region-spring-boot-test-webmvc/src/test/java/com/livk/ip2region/mvc/controller/Ip2RegionControllerTest.java b/spring-boot-extension-tests/ip2region-spring-boot-test/ip2region-spring-boot-test-webmvc/src/test/java/com/livk/ip2region/mvc/controller/Ip2RegionControllerTest.java index f68b68c8e..6e57537e2 100644 --- a/spring-boot-extension-tests/ip2region-spring-boot-test/ip2region-spring-boot-test-webmvc/src/test/java/com/livk/ip2region/mvc/controller/Ip2RegionControllerTest.java +++ b/spring-boot-extension-tests/ip2region-spring-boot-test/ip2region-spring-boot-test-webmvc/src/test/java/com/livk/ip2region/mvc/controller/Ip2RegionControllerTest.java @@ -51,4 +51,5 @@ void post() throws Exception { .andExpect(jsonPath("*.city", "内网IP").exists()) .andExpect(jsonPath("*.operator", "内网IP").exists()); } + } diff --git a/spring-boot-extension-tests/ip2region-spring-boot-test/ip2region-spring-boot-test-webmvc/src/test/java/com/livk/ip2region/mvc/support/Ip2RegionSearchTest.java b/spring-boot-extension-tests/ip2region-spring-boot-test/ip2region-spring-boot-test-webmvc/src/test/java/com/livk/ip2region/mvc/support/Ip2RegionSearchTest.java index 0ae4c2a72..ba16ba75c 100644 --- a/spring-boot-extension-tests/ip2region-spring-boot-test/ip2region-spring-boot-test-webmvc/src/test/java/com/livk/ip2region/mvc/support/Ip2RegionSearchTest.java +++ b/spring-boot-extension-tests/ip2region-spring-boot-test/ip2region-spring-boot-test-webmvc/src/test/java/com/livk/ip2region/mvc/support/Ip2RegionSearchTest.java @@ -69,5 +69,5 @@ void searchAsJson() { assertEquals("保定市", jsonNode.get("city").asText()); assertEquals("联通", jsonNode.get("operator").asText()); } -} +} diff --git a/spring-boot-extension-tests/limit-spring-boot-test/redisson-limit-spring-boot-test/src/main/java/com/livk/redisson/limit/RedissonLimitApp.java b/spring-boot-extension-tests/limit-spring-boot-test/redisson-limit-spring-boot-test/src/main/java/com/livk/redisson/limit/RedissonLimitApp.java index 4678416c2..772de14ba 100644 --- a/spring-boot-extension-tests/limit-spring-boot-test/redisson-limit-spring-boot-test/src/main/java/com/livk/redisson/limit/RedissonLimitApp.java +++ b/spring-boot-extension-tests/limit-spring-boot-test/redisson-limit-spring-boot-test/src/main/java/com/livk/redisson/limit/RedissonLimitApp.java @@ -27,7 +27,9 @@ @EnableLimit @SpringBootApplication public class RedissonLimitApp { + public static void main(String[] args) { SpringLauncher.run(args); } + } diff --git a/spring-boot-extension-tests/limit-spring-boot-test/redisson-limit-spring-boot-test/src/main/java/com/livk/redisson/limit/controller/ErrorHandler.java b/spring-boot-extension-tests/limit-spring-boot-test/redisson-limit-spring-boot-test/src/main/java/com/livk/redisson/limit/controller/ErrorHandler.java index ca168ad9e..874d86c8c 100644 --- a/spring-boot-extension-tests/limit-spring-boot-test/redisson-limit-spring-boot-test/src/main/java/com/livk/redisson/limit/controller/ErrorHandler.java +++ b/spring-boot-extension-tests/limit-spring-boot-test/redisson-limit-spring-boot-test/src/main/java/com/livk/redisson/limit/controller/ErrorHandler.java @@ -34,4 +34,5 @@ public class ErrorHandler { public HttpEntity handleLimitException(LimitException e) { return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage()); } + } diff --git a/spring-boot-extension-tests/limit-spring-boot-test/redisson-limit-spring-boot-test/src/test/java/com/livk/redisson/limit/controller/RateLimiterControllerTest.java b/spring-boot-extension-tests/limit-spring-boot-test/redisson-limit-spring-boot-test/src/test/java/com/livk/redisson/limit/controller/RateLimiterControllerTest.java index a0d28372b..a2eb88360 100644 --- a/spring-boot-extension-tests/limit-spring-boot-test/redisson-limit-spring-boot-test/src/test/java/com/livk/redisson/limit/controller/RateLimiterControllerTest.java +++ b/spring-boot-extension-tests/limit-spring-boot-test/redisson-limit-spring-boot-test/src/test/java/com/livk/redisson/limit/controller/RateLimiterControllerTest.java @@ -52,4 +52,5 @@ void rate() throws Exception { .andDo(print()) .andReturn(); } + } diff --git a/spring-boot-extension-tests/lock-spring-boot-test/curator-lock-spring-boot-test/src/main/java/com/livk/curator/lock/CuratorLockExample.java b/spring-boot-extension-tests/lock-spring-boot-test/curator-lock-spring-boot-test/src/main/java/com/livk/curator/lock/CuratorLockExample.java index 79b806b2d..7dcb9f617 100644 --- a/spring-boot-extension-tests/lock-spring-boot-test/curator-lock-spring-boot-test/src/main/java/com/livk/curator/lock/CuratorLockExample.java +++ b/spring-boot-extension-tests/lock-spring-boot-test/curator-lock-spring-boot-test/src/main/java/com/livk/curator/lock/CuratorLockExample.java @@ -29,7 +29,9 @@ */ @SpringBootApplication public class CuratorLockExample { + public static void main(String[] args) { SpringLauncher.run(args); } + } diff --git a/spring-boot-extension-tests/lock-spring-boot-test/curator-lock-spring-boot-test/src/main/java/com/livk/curator/lock/ShopController.java b/spring-boot-extension-tests/lock-spring-boot-test/curator-lock-spring-boot-test/src/main/java/com/livk/curator/lock/ShopController.java index e6e2ac710..d419acd3d 100644 --- a/spring-boot-extension-tests/lock-spring-boot-test/curator-lock-spring-boot-test/src/main/java/com/livk/curator/lock/ShopController.java +++ b/spring-boot-extension-tests/lock-spring-boot-test/curator-lock-spring-boot-test/src/main/java/com/livk/curator/lock/ShopController.java @@ -35,8 +35,11 @@ @RestController @RequestMapping("shop") public class ShopController { + private Integer num = 500; + private int buyCount = 0; + private int buySucCount = 0; @PostMapping("/buy/distributed") @@ -48,7 +51,8 @@ public HttpEntity> buyLocal(@RequestParam(defaultValue = "2" buySucCount++; Map msg = Map.of("购买成功数量", count, "总计购买次数", buyCount, "购买成功次数", buySucCount); return ResponseEntity.ok(Map.of("code", "200", "msg", msg)); - } else { + } + else { return ResponseEntity.ok(Map.of("code", "500", "msg", "数量超出库存!")); } } @@ -65,4 +69,5 @@ public HttpEntity> result() { Map local = Map.of("num", num, "buyCount", buyCount, "buySucCount", buySucCount); return ResponseEntity.ok(Map.of("curator", local)); } + } diff --git a/spring-boot-extension-tests/lock-spring-boot-test/curator-lock-spring-boot-test/src/test/java/com/livk/curator/lock/ShopControllerTest.java b/spring-boot-extension-tests/lock-spring-boot-test/curator-lock-spring-boot-test/src/test/java/com/livk/curator/lock/ShopControllerTest.java index 80c40d93b..ed4fecc4b 100644 --- a/spring-boot-extension-tests/lock-spring-boot-test/curator-lock-spring-boot-test/src/test/java/com/livk/curator/lock/ShopControllerTest.java +++ b/spring-boot-extension-tests/lock-spring-boot-test/curator-lock-spring-boot-test/src/test/java/com/livk/curator/lock/ShopControllerTest.java @@ -43,10 +43,10 @@ @SpringBootTest @AutoConfigureMockMvc class ShopControllerTest { + @Autowired MockMvc mockMvc; - @Order(1) @Test void testBuyLocal() throws InterruptedException { @@ -55,10 +55,10 @@ void testBuyLocal() throws InterruptedException { for (int i = 0; i < 10; i++) { service.submit(() -> { try { - mockMvc.perform(post("/shop/buy/distributed")) - .andExpect(status().isOk()); + mockMvc.perform(post("/shop/buy/distributed")).andExpect(status().isOk()); countDownLatch.countDown(); - } catch (Exception e) { + } + catch (Exception e) { throw new RuntimeException(e); } }); @@ -77,6 +77,8 @@ void testResult() throws Exception { .andExpect(jsonPath("curator.buySucCount", 10).exists()) .andExpect(jsonPath("curator.num", 480).exists()); } + } -//Generated with love by TestMe :) Please report issues and submit feature requests at: http://weirddev.com/forum#!/testme +// Generated with love by TestMe :) Please report issues and submit feature requests at: +// http://weirddev.com/forum#!/testme diff --git a/spring-boot-extension-tests/lock-spring-boot-test/local-lock-spring-boot-test/src/main/java/com/livk/local/lock/LocalLockExample.java b/spring-boot-extension-tests/lock-spring-boot-test/local-lock-spring-boot-test/src/main/java/com/livk/local/lock/LocalLockExample.java index efe346ee7..c0e51b8e0 100644 --- a/spring-boot-extension-tests/lock-spring-boot-test/local-lock-spring-boot-test/src/main/java/com/livk/local/lock/LocalLockExample.java +++ b/spring-boot-extension-tests/lock-spring-boot-test/local-lock-spring-boot-test/src/main/java/com/livk/local/lock/LocalLockExample.java @@ -29,7 +29,9 @@ */ @SpringBootApplication public class LocalLockExample { + public static void main(String[] args) { SpringLauncher.run(args); } + } diff --git a/spring-boot-extension-tests/lock-spring-boot-test/local-lock-spring-boot-test/src/main/java/com/livk/local/lock/ShopController.java b/spring-boot-extension-tests/lock-spring-boot-test/local-lock-spring-boot-test/src/main/java/com/livk/local/lock/ShopController.java index 0387c6d27..450b4027a 100644 --- a/spring-boot-extension-tests/lock-spring-boot-test/local-lock-spring-boot-test/src/main/java/com/livk/local/lock/ShopController.java +++ b/spring-boot-extension-tests/lock-spring-boot-test/local-lock-spring-boot-test/src/main/java/com/livk/local/lock/ShopController.java @@ -35,8 +35,11 @@ @RestController @RequestMapping("shop") public class ShopController { + private Integer num = 500; + private int buyCount = 0; + private int buySucCount = 0; @PostMapping("/buy/local") @@ -48,7 +51,8 @@ public HttpEntity> buyLocal(@RequestParam(defaultValue = "2" buySucCount++; Map msg = Map.of("购买成功数量", count, "总计购买次数", buyCount, "购买成功次数", buySucCount); return ResponseEntity.ok(Map.of("code", "200", "msg", msg)); - } else { + } + else { return ResponseEntity.ok(Map.of("code", "500", "msg", "数量超出库存!")); } } @@ -65,4 +69,5 @@ public HttpEntity> result() { Map local = Map.of("num", num, "buyCount", buyCount, "buySucCount", buySucCount); return ResponseEntity.ok(Map.of("local", local)); } + } diff --git a/spring-boot-extension-tests/lock-spring-boot-test/local-lock-spring-boot-test/src/test/java/com/livk/local/lock/ShopControllerTest.java b/spring-boot-extension-tests/lock-spring-boot-test/local-lock-spring-boot-test/src/test/java/com/livk/local/lock/ShopControllerTest.java index eef8b65a6..b475ecb1e 100644 --- a/spring-boot-extension-tests/lock-spring-boot-test/local-lock-spring-boot-test/src/test/java/com/livk/local/lock/ShopControllerTest.java +++ b/spring-boot-extension-tests/lock-spring-boot-test/local-lock-spring-boot-test/src/test/java/com/livk/local/lock/ShopControllerTest.java @@ -43,6 +43,7 @@ @SpringBootTest @AutoConfigureMockMvc class ShopControllerTest { + @Autowired MockMvc mockMvc; @@ -54,10 +55,10 @@ void testBuyLocal() throws InterruptedException { for (int i = 0; i < 500; i++) { service.submit(() -> { try { - mockMvc.perform(post("/shop/buy/local")) - .andExpect(status().isOk()); + mockMvc.perform(post("/shop/buy/local")).andExpect(status().isOk()); countDownLatch.countDown(); - } catch (Exception e) { + } + catch (Exception e) { throw new RuntimeException(e); } }); @@ -76,6 +77,8 @@ void testResult() throws Exception { .andExpect(jsonPath("local.buySucCount", 250).exists()) .andExpect(jsonPath("local.num", 0).exists()); } + } -//Generated with love by TestMe :) Please report issues and submit feature requests at: http://weirddev.com/forum#!/testme +// Generated with love by TestMe :) Please report issues and submit feature requests at: +// http://weirddev.com/forum#!/testme diff --git a/spring-boot-extension-tests/lock-spring-boot-test/redisson-lock-spring-boot-test/src/main/java/com/livk/redisson/lock/RedissonLockExample.java b/spring-boot-extension-tests/lock-spring-boot-test/redisson-lock-spring-boot-test/src/main/java/com/livk/redisson/lock/RedissonLockExample.java index 70f1ebfdb..2857708a3 100644 --- a/spring-boot-extension-tests/lock-spring-boot-test/redisson-lock-spring-boot-test/src/main/java/com/livk/redisson/lock/RedissonLockExample.java +++ b/spring-boot-extension-tests/lock-spring-boot-test/redisson-lock-spring-boot-test/src/main/java/com/livk/redisson/lock/RedissonLockExample.java @@ -29,7 +29,9 @@ */ @SpringBootApplication public class RedissonLockExample { + public static void main(String[] args) { SpringLauncher.run(args); } + } diff --git a/spring-boot-extension-tests/lock-spring-boot-test/redisson-lock-spring-boot-test/src/main/java/com/livk/redisson/lock/ShopController.java b/spring-boot-extension-tests/lock-spring-boot-test/redisson-lock-spring-boot-test/src/main/java/com/livk/redisson/lock/ShopController.java index 22e1fd850..c226a5408 100644 --- a/spring-boot-extension-tests/lock-spring-boot-test/redisson-lock-spring-boot-test/src/main/java/com/livk/redisson/lock/ShopController.java +++ b/spring-boot-extension-tests/lock-spring-boot-test/redisson-lock-spring-boot-test/src/main/java/com/livk/redisson/lock/ShopController.java @@ -45,6 +45,7 @@ public class ShopController { private final HashOperations forHash; + private final RedisTemplate redisTemplate; public ShopController(RedisTemplate redisTemplate) { @@ -65,7 +66,9 @@ public void init() { @OnLock(key = "shop:lock", scope = LockScope.DISTRIBUTED_LOCK) public HttpEntity> buyDistributed(@RequestParam(defaultValue = "2") Integer count) { RedisScript redisScript = RedisScript.of(new ClassPathResource("script/buy.lua"), Long.class); - Long result = redisTemplate.execute(redisScript, RedisSerializer.string(), new GenericToStringSerializer<>(Long.class), List.of("shop", "num", "buySucCount", "buyCount"), String.valueOf(count)); + Long result = redisTemplate.execute(redisScript, RedisSerializer.string(), + new GenericToStringSerializer<>(Long.class), List.of("shop", "num", "buySucCount", "buyCount"), + String.valueOf(count)); if (result != null && result == 1) { return ResponseEntity.ok(Map.of("code", "200", "msg", "购买成功,数量:" + count)); } @@ -77,4 +80,5 @@ public HttpEntity> result() { Map distributed = forHash.entries("shop"); return ResponseEntity.ok(Map.of("redisson", distributed)); } + } diff --git a/spring-boot-extension-tests/lock-spring-boot-test/redisson-lock-spring-boot-test/src/test/java/com/livk/redisson/lock/ShopControllerTest.java b/spring-boot-extension-tests/lock-spring-boot-test/redisson-lock-spring-boot-test/src/test/java/com/livk/redisson/lock/ShopControllerTest.java index eed6b20c7..9ae8f1fbf 100644 --- a/spring-boot-extension-tests/lock-spring-boot-test/redisson-lock-spring-boot-test/src/test/java/com/livk/redisson/lock/ShopControllerTest.java +++ b/spring-boot-extension-tests/lock-spring-boot-test/redisson-lock-spring-boot-test/src/test/java/com/livk/redisson/lock/ShopControllerTest.java @@ -43,10 +43,10 @@ @SpringBootTest @AutoConfigureMockMvc class ShopControllerTest { + @Autowired MockMvc mockMvc; - @Order(1) @Test void testBuyLocal() throws InterruptedException { @@ -55,10 +55,10 @@ void testBuyLocal() throws InterruptedException { for (int i = 0; i < 10; i++) { service.submit(() -> { try { - mockMvc.perform(post("/shop/buy/distributed")) - .andExpect(status().isOk()); + mockMvc.perform(post("/shop/buy/distributed")).andExpect(status().isOk()); countDownLatch.countDown(); - } catch (Exception e) { + } + catch (Exception e) { throw new RuntimeException(e); } }); @@ -77,6 +77,8 @@ void testResult() throws Exception { .andExpect(jsonPath("redisson.buySucCount", 10).exists()) .andExpect(jsonPath("redisson.num", 480).exists()); } + } -//Generated with love by TestMe :) Please report issues and submit feature requests at: http://weirddev.com/forum#!/testme +// Generated with love by TestMe :) Please report issues and submit feature requests at: +// http://weirddev.com/forum#!/testme diff --git a/spring-boot-extension-tests/mapstruct-spring-boot-test/src/main/java/com/livk/mapstruct/controller/UserController.java b/spring-boot-extension-tests/mapstruct-spring-boot-test/src/main/java/com/livk/mapstruct/controller/UserController.java index 6a6e58b85..609bbdd01 100644 --- a/spring-boot-extension-tests/mapstruct-spring-boot-test/src/main/java/com/livk/mapstruct/controller/UserController.java +++ b/spring-boot-extension-tests/mapstruct-spring-boot-test/src/main/java/com/livk/mapstruct/controller/UserController.java @@ -47,9 +47,9 @@ public class UserController { public static final List USERS = List.of( - new User().setId(1).setUsername("livk1").setPassword("123456").setType(1).setCreateTime(new Date()), - new User().setId(2).setUsername("livk2").setPassword("123456").setType(2).setCreateTime(new Date()), - new User().setId(3).setUsername("livk3").setPassword("123456").setType(3).setCreateTime(new Date())); + new User().setId(1).setUsername("livk1").setPassword("123456").setType(1).setCreateTime(new Date()), + new User().setId(2).setUsername("livk2").setPassword("123456").setType(2).setCreateTime(new Date()), + new User().setId(3).setUsername("livk3").setPassword("123456").setType(3).setCreateTime(new Date())); // 自定义双向转换 private final MapstructService service; @@ -59,19 +59,18 @@ public class UserController { @GetMapping public HttpEntity>> list() { - List userVOS = USERS.stream().map(user -> conversionService.convert(user, UserVO.class)) - .filter(Objects::nonNull).toList(); - return ResponseEntity - .ok(Map.of("spring", userVOS, - "customize", service.convert(USERS, UserVO.class).toList())); + List userVOS = USERS.stream() + .map(user -> conversionService.convert(user, UserVO.class)) + .filter(Objects::nonNull) + .toList(); + return ResponseEntity.ok(Map.of("spring", userVOS, "customize", service.convert(USERS, UserVO.class).toList())); } @GetMapping("/{id}") public HttpEntity> getById(@PathVariable Integer id) { User u = USERS.stream().filter(user -> user.getId().equals(id)).findFirst().orElse(new User()); UserVO userVOSpring = conversionService.convert(u, UserVO.class); - return ResponseEntity.ok(Map.of("customize", service.convert(u, UserVO.class), - "spring", userVOSpring)); + return ResponseEntity.ok(Map.of("customize", service.convert(u, UserVO.class), "spring", userVOSpring)); } } diff --git a/spring-boot-extension-tests/mapstruct-spring-boot-test/src/main/java/com/livk/mapstruct/converter/UserVOSpringConverter.java b/spring-boot-extension-tests/mapstruct-spring-boot-test/src/main/java/com/livk/mapstruct/converter/UserVOSpringConverter.java index c351fbab3..f0ceb64ac 100644 --- a/spring-boot-extension-tests/mapstruct-spring-boot-test/src/main/java/com/livk/mapstruct/converter/UserVOSpringConverter.java +++ b/spring-boot-extension-tests/mapstruct-spring-boot-test/src/main/java/com/livk/mapstruct/converter/UserVOSpringConverter.java @@ -36,11 +36,11 @@ @Mapper(componentModel = MappingConstants.ComponentModel.SPRING) public interface UserVOSpringConverter extends Converter { - @Mapping(target = "password", ignore = true) @Mapping(target = "id", ignore = true) @Mapping(target = "createTime", source = "createTime", dateFormat = DateUtils.YMD_HMS) @Mapping(target = "type", source = "type", numberFormat = "#") @Override User convert(@Nullable UserVO source); + } diff --git a/spring-boot-extension-tests/mapstruct-spring-boot-test/src/test/java/com/livk/mapstruct/controller/UserControllerTest.java b/spring-boot-extension-tests/mapstruct-spring-boot-test/src/test/java/com/livk/mapstruct/controller/UserControllerTest.java index 396031d24..254b1c357 100644 --- a/spring-boot-extension-tests/mapstruct-spring-boot-test/src/test/java/com/livk/mapstruct/controller/UserControllerTest.java +++ b/spring-boot-extension-tests/mapstruct-spring-boot-test/src/test/java/com/livk/mapstruct/controller/UserControllerTest.java @@ -69,6 +69,8 @@ void testGetById() throws Exception { .andExpect(jsonPath("spring.createTime").exists()); } } + } -//Generated with love by TestMe :) Please report issues and submit feature requests at: http://weirddev.com/forum#!/testme +// Generated with love by TestMe :) Please report issues and submit feature requests at: +// http://weirddev.com/forum#!/testme diff --git a/spring-boot-extension-tests/mybatis-plugins-spring-boot-test/mybatis-inject-monitor-spring-boot-test/src/main/java/com/livk/mybatisplugins/SqlTimeOutHandler.java b/spring-boot-extension-tests/mybatis-plugins-spring-boot-test/mybatis-inject-monitor-spring-boot-test/src/main/java/com/livk/mybatisplugins/SqlTimeOutHandler.java index adc06c52a..e70ee97b0 100644 --- a/spring-boot-extension-tests/mybatis-plugins-spring-boot-test/mybatis-inject-monitor-spring-boot-test/src/main/java/com/livk/mybatisplugins/SqlTimeOutHandler.java +++ b/spring-boot-extension-tests/mybatis-plugins-spring-boot-test/mybatis-inject-monitor-spring-boot-test/src/main/java/com/livk/mybatisplugins/SqlTimeOutHandler.java @@ -39,4 +39,5 @@ public void onApplicationEvent(MonitorSQLTimeOutEvent event) { MonitorSQLInfo info = event.info(); log.error("{SQL超时 SQL:[{}],Time:[{}ms],result:[{}]}", info.sql(), info.timeout(), info.result()); } + } diff --git a/spring-boot-extension-tests/mybatis-plugins-spring-boot-test/mybatis-inject-monitor-spring-boot-test/src/main/java/com/livk/mybatisplugins/controller/UserController.java b/spring-boot-extension-tests/mybatis-plugins-spring-boot-test/mybatis-inject-monitor-spring-boot-test/src/main/java/com/livk/mybatisplugins/controller/UserController.java index 2c23d0bda..a5d72c405 100644 --- a/spring-boot-extension-tests/mybatis-plugins-spring-boot-test/mybatis-inject-monitor-spring-boot-test/src/main/java/com/livk/mybatisplugins/controller/UserController.java +++ b/spring-boot-extension-tests/mybatis-plugins-spring-boot-test/mybatis-inject-monitor-spring-boot-test/src/main/java/com/livk/mybatisplugins/controller/UserController.java @@ -48,8 +48,7 @@ public HttpEntity getById(@PathVariable Integer id) { } @PutMapping("{id}") - public HttpEntity updateById(@PathVariable Integer id, - @RequestBody User user) { + public HttpEntity updateById(@PathVariable Integer id, @RequestBody User user) { user.setId(id); return ResponseEntity.ok(userService.updateById(user)); } @@ -66,7 +65,7 @@ public HttpEntity deleteById(@PathVariable Integer id) { @GetMapping public HttpEntity> page(@RequestParam(defaultValue = "1") Integer pageNum, - @RequestParam(defaultValue = "10") Integer pageSize) { + @RequestParam(defaultValue = "10") Integer pageSize) { try (Page page = PageHelper.startPage(pageNum, pageSize) .countColumn(BeanLambdaFunc.fieldName(User::getId)) .doSelectPage(userService::list)) { @@ -74,4 +73,5 @@ public HttpEntity> page(@RequestParam(defaultValue = "1") Integer return ResponseEntity.ok(result); } } + } diff --git a/spring-boot-extension-tests/mybatis-plugins-spring-boot-test/mybatis-inject-monitor-spring-boot-test/src/main/java/com/livk/mybatisplugins/entity/PageInfo.java b/spring-boot-extension-tests/mybatis-plugins-spring-boot-test/mybatis-inject-monitor-spring-boot-test/src/main/java/com/livk/mybatisplugins/entity/PageInfo.java index cd36b09dc..0996e80e2 100644 --- a/spring-boot-extension-tests/mybatis-plugins-spring-boot-test/mybatis-inject-monitor-spring-boot-test/src/main/java/com/livk/mybatisplugins/entity/PageInfo.java +++ b/spring-boot-extension-tests/mybatis-plugins-spring-boot-test/mybatis-inject-monitor-spring-boot-test/src/main/java/com/livk/mybatisplugins/entity/PageInfo.java @@ -51,18 +51,22 @@ public class PageInfo implements Serializable { @Serial private static final long serialVersionUID = 1L; + /** * 总数 */ private final long total; + /** * 当前分页数据 */ private final List list; + /** * 页数 */ private int pageNum; + /** * 数量 */ @@ -70,7 +74,6 @@ public class PageInfo implements Serializable { /** * {@link Page} - * * @param list list or page */ public PageInfo(List list) { @@ -79,10 +82,9 @@ public PageInfo(List list) { /** * 构建分页实体,同时使用{@link Function}转换list - * - * @param list the list + * @param list the list * @param function the function - * @param r + * @param r */ public PageInfo(List list, Function, List> function) { if (list instanceof Page page) { @@ -90,7 +92,8 @@ public PageInfo(List list, Function, List> function) { this.pageNum = page.getPageNum(); this.pageSize = page.getPageSize(); this.total = page.getTotal(); - } else { + } + else { this.total = list.size(); this.list = function.apply(list); } @@ -98,11 +101,10 @@ public PageInfo(List list, Function, List> function) { /** * 用于Jackson反序列化构建 - * - * @param list the list - * @param pageNum the page num + * @param list the list + * @param pageNum the page num * @param pageSize the page size - * @param total the total + * @param total the total */ PageInfo(List list, int pageNum, int pageSize, long total) { this.list = list; @@ -114,7 +116,8 @@ public PageInfo(List list, Function, List> function) { /** * {@link PageInfo} 反序列化器 */ - static class PageInfoJsonDeserializer extends StdScalarDeserializer> implements ContextualDeserializer { + static class PageInfoJsonDeserializer extends StdScalarDeserializer> + implements ContextualDeserializer { private JavaType javaType; @@ -145,5 +148,7 @@ public JsonDeserializer createContextual(DeserializationContext context, Bean javaType = bindings.getBoundType(0); return this; } + } + } diff --git a/spring-boot-extension-tests/mybatis-plugins-spring-boot-test/mybatis-inject-monitor-spring-boot-test/src/main/java/com/livk/mybatisplugins/entity/User.java b/spring-boot-extension-tests/mybatis-plugins-spring-boot-test/mybatis-inject-monitor-spring-boot-test/src/main/java/com/livk/mybatisplugins/entity/User.java index 7a7179a75..13fb37788 100644 --- a/spring-boot-extension-tests/mybatis-plugins-spring-boot-test/mybatis-inject-monitor-spring-boot-test/src/main/java/com/livk/mybatisplugins/entity/User.java +++ b/spring-boot-extension-tests/mybatis-plugins-spring-boot-test/mybatis-inject-monitor-spring-boot-test/src/main/java/com/livk/mybatisplugins/entity/User.java @@ -58,4 +58,5 @@ public class User implements Serializable { @JsonFormat(pattern = DateUtils.YMD_HMS, timezone = "GMT+8") @SqlFunction(fill = SqlFill.INSERT_UPDATE, time = FunctionType.DATE) private Date updateTime; + } diff --git a/spring-boot-extension-tests/mybatis-plugins-spring-boot-test/mybatis-inject-monitor-spring-boot-test/src/main/java/com/livk/mybatisplugins/service/UserService.java b/spring-boot-extension-tests/mybatis-plugins-spring-boot-test/mybatis-inject-monitor-spring-boot-test/src/main/java/com/livk/mybatisplugins/service/UserService.java index 031ff3674..b0ca1b844 100644 --- a/spring-boot-extension-tests/mybatis-plugins-spring-boot-test/mybatis-inject-monitor-spring-boot-test/src/main/java/com/livk/mybatisplugins/service/UserService.java +++ b/spring-boot-extension-tests/mybatis-plugins-spring-boot-test/mybatis-inject-monitor-spring-boot-test/src/main/java/com/livk/mybatisplugins/service/UserService.java @@ -29,6 +29,7 @@ * @author livk */ public interface UserService { + User getById(Integer id); boolean updateById(User user); @@ -38,4 +39,5 @@ public interface UserService { boolean deleteById(Integer id); List list(); + } diff --git a/spring-boot-extension-tests/mybatis-plugins-spring-boot-test/mybatis-inject-monitor-spring-boot-test/src/main/java/com/livk/mybatisplugins/service/impl/UserServiceImpl.java b/spring-boot-extension-tests/mybatis-plugins-spring-boot-test/mybatis-inject-monitor-spring-boot-test/src/main/java/com/livk/mybatisplugins/service/impl/UserServiceImpl.java index 2e2823911..f3a7e6ac7 100644 --- a/spring-boot-extension-tests/mybatis-plugins-spring-boot-test/mybatis-inject-monitor-spring-boot-test/src/main/java/com/livk/mybatisplugins/service/impl/UserServiceImpl.java +++ b/spring-boot-extension-tests/mybatis-plugins-spring-boot-test/mybatis-inject-monitor-spring-boot-test/src/main/java/com/livk/mybatisplugins/service/impl/UserServiceImpl.java @@ -62,4 +62,5 @@ public boolean deleteById(Integer id) { public List list() { return userMapper.list(); } + } diff --git a/spring-boot-extension-tests/mybatis-plugins-spring-boot-test/mybatis-inject-monitor-spring-boot-test/src/test/java/com/livk/mybatisplugins/controller/UserControllerTest.java b/spring-boot-extension-tests/mybatis-plugins-spring-boot-test/mybatis-inject-monitor-spring-boot-test/src/test/java/com/livk/mybatisplugins/controller/UserControllerTest.java index bd61350d1..6bf97d3a3 100644 --- a/spring-boot-extension-tests/mybatis-plugins-spring-boot-test/mybatis-inject-monitor-spring-boot-test/src/test/java/com/livk/mybatisplugins/controller/UserControllerTest.java +++ b/spring-boot-extension-tests/mybatis-plugins-spring-boot-test/mybatis-inject-monitor-spring-boot-test/src/test/java/com/livk/mybatisplugins/controller/UserControllerTest.java @@ -42,14 +42,11 @@ * @author livk */ @TestMethodOrder(MethodOrderer.OrderAnnotation.class) -@SpringBootTest({ - "spring.datasource.driver-class-name=org.h2.Driver", - "spring.datasource.url=jdbc:h2:mem:test", - "spring.sql.init.platform=h2", - "spring.sql.init.mode=embedded" -}) +@SpringBootTest({ "spring.datasource.driver-class-name=org.h2.Driver", "spring.datasource.url=jdbc:h2:mem:test", + "spring.sql.init.platform=h2", "spring.sql.init.mode=embedded" }) @AutoConfigureMockMvc class UserControllerTest { + @Autowired MockMvc mockMvc; @@ -57,7 +54,6 @@ class UserControllerTest { ObjectMapper mapper = JsonMapper.builder().build(); - @Order(3) @Test void testGetById() throws Exception { @@ -72,8 +68,8 @@ void testGetById() throws Exception { void testUpdateById() throws Exception { User user = new User(); user.setUsername("livk https"); - mockMvc.perform(put("/user/{id}", id) - .contentType(MediaType.APPLICATION_JSON) + mockMvc + .perform(put("/user/{id}", id).contentType(MediaType.APPLICATION_JSON) .content(mapper.writeValueAsString(user))) .andExpect(status().isOk()) .andDo(print()) @@ -86,9 +82,7 @@ void testSave() throws Exception { User user = new User(); user.setId(id); user.setUsername("livk"); - mockMvc.perform(post("/user") - .contentType(MediaType.APPLICATION_JSON) - .content(mapper.writeValueAsString(user))) + mockMvc.perform(post("/user").contentType(MediaType.APPLICATION_JSON).content(mapper.writeValueAsString(user))) .andExpect(status().isOk()) .andDo(print()) .andExpect(content().string("true")); @@ -113,6 +107,8 @@ void testList() throws Exception { .andExpect(jsonPath("pageNum", 1).exists()) .andExpect(jsonPath("pageSize", 10).exists()); } + } -//Generated with love by TestMe :) Please report issues and submit feature requests at: http://weirddev.com/forum#!/testme +// Generated with love by TestMe :) Please report issues and submit feature requests at: +// http://weirddev.com/forum#!/testme diff --git a/spring-boot-extension-tests/mybatis-plugins-spring-boot-test/mybatis-typehandler-mysql-spring-boot-test/src/main/java/com/livk/mysql/json/controller/UserController.java b/spring-boot-extension-tests/mybatis-plugins-spring-boot-test/mybatis-typehandler-mysql-spring-boot-test/src/main/java/com/livk/mysql/json/controller/UserController.java index 5f1c737ea..e3e258cff 100644 --- a/spring-boot-extension-tests/mybatis-plugins-spring-boot-test/mybatis-typehandler-mysql-spring-boot-test/src/main/java/com/livk/mysql/json/controller/UserController.java +++ b/spring-boot-extension-tests/mybatis-plugins-spring-boot-test/mybatis-typehandler-mysql-spring-boot-test/src/main/java/com/livk/mysql/json/controller/UserController.java @@ -45,9 +45,9 @@ public class UserController { @PostMapping("user") public HttpEntity save() { String json = """ - { - "mark": "livk" - }"""; + { + "mark": "livk" + }"""; User user = new User(); user.setUsername("admin"); user.setPassword("admin"); diff --git a/spring-boot-extension-tests/mybatis-plugins-spring-boot-test/mybatis-typehandler-mysql-spring-boot-test/src/main/java/com/livk/mysql/json/mapper/UserMapper.java b/spring-boot-extension-tests/mybatis-plugins-spring-boot-test/mybatis-typehandler-mysql-spring-boot-test/src/main/java/com/livk/mysql/json/mapper/UserMapper.java index 6ce9ba5db..17264cfad 100644 --- a/spring-boot-extension-tests/mybatis-plugins-spring-boot-test/mybatis-typehandler-mysql-spring-boot-test/src/main/java/com/livk/mysql/json/mapper/UserMapper.java +++ b/spring-boot-extension-tests/mybatis-plugins-spring-boot-test/mybatis-typehandler-mysql-spring-boot-test/src/main/java/com/livk/mysql/json/mapper/UserMapper.java @@ -39,4 +39,5 @@ public interface UserMapper { @Select("select * from user") List selectList(); + } diff --git a/spring-boot-extension-tests/mybatis-plugins-spring-boot-test/mybatis-typehandler-mysql-spring-boot-test/src/test/java/com/livk/mysql/json/controller/UserControllerTest.java b/spring-boot-extension-tests/mybatis-plugins-spring-boot-test/mybatis-typehandler-mysql-spring-boot-test/src/test/java/com/livk/mysql/json/controller/UserControllerTest.java index d5bb85dc3..0bee86caa 100644 --- a/spring-boot-extension-tests/mybatis-plugins-spring-boot-test/mybatis-typehandler-mysql-spring-boot-test/src/test/java/com/livk/mysql/json/controller/UserControllerTest.java +++ b/spring-boot-extension-tests/mybatis-plugins-spring-boot-test/mybatis-typehandler-mysql-spring-boot-test/src/test/java/com/livk/mysql/json/controller/UserControllerTest.java @@ -44,26 +44,23 @@ @AutoConfigureMockMvc @TestMethodOrder(MethodOrderer.OrderAnnotation.class) class UserControllerTest { + @Autowired MockMvc mockMvc; - @Order(1) @Test void testSave() throws Exception { - mockMvc.perform(post("/user")) - .andDo(print()) - .andExpect(status().isOk()) - .andExpect(content().string("true")); + mockMvc.perform(post("/user")).andDo(print()).andExpect(status().isOk()).andExpect(content().string("true")); } @Order(2) @Test void testUsers() throws Exception { - mockMvc.perform(get("/user")) - .andDo(print()) - .andExpect(status().isOk()); + mockMvc.perform(get("/user")).andDo(print()).andExpect(status().isOk()); } + } -//Generated with love by TestMe :) Please report issues and submit feature requests at: http://weirddev.com/forum#!/testme +// Generated with love by TestMe :) Please report issues and submit feature requests at: +// http://weirddev.com/forum#!/testme diff --git a/spring-boot-extension-tests/mybatis-plugins-spring-boot-test/mybatis-typehandler-postgresql-spring-boot-test/src/main/java/com/livk/postgres/json/controller/UserController.java b/spring-boot-extension-tests/mybatis-plugins-spring-boot-test/mybatis-typehandler-postgresql-spring-boot-test/src/main/java/com/livk/postgres/json/controller/UserController.java index 260e6176e..d0f5cb715 100644 --- a/spring-boot-extension-tests/mybatis-plugins-spring-boot-test/mybatis-typehandler-postgresql-spring-boot-test/src/main/java/com/livk/postgres/json/controller/UserController.java +++ b/spring-boot-extension-tests/mybatis-plugins-spring-boot-test/mybatis-typehandler-postgresql-spring-boot-test/src/main/java/com/livk/postgres/json/controller/UserController.java @@ -46,9 +46,9 @@ public class UserController { @PostMapping("user") public HttpEntity save() { String json = """ - { - "mark": "livk" - }"""; + { + "mark": "livk" + }"""; User user = new User(); user.setUsername("admin"); user.setPassword("admin"); diff --git a/spring-boot-extension-tests/mybatis-plugins-spring-boot-test/mybatis-typehandler-postgresql-spring-boot-test/src/main/java/com/livk/postgres/json/mapper/UserMapper.java b/spring-boot-extension-tests/mybatis-plugins-spring-boot-test/mybatis-typehandler-postgresql-spring-boot-test/src/main/java/com/livk/postgres/json/mapper/UserMapper.java index 6ad1e8742..248a5b2ce 100644 --- a/spring-boot-extension-tests/mybatis-plugins-spring-boot-test/mybatis-typehandler-postgresql-spring-boot-test/src/main/java/com/livk/postgres/json/mapper/UserMapper.java +++ b/spring-boot-extension-tests/mybatis-plugins-spring-boot-test/mybatis-typehandler-postgresql-spring-boot-test/src/main/java/com/livk/postgres/json/mapper/UserMapper.java @@ -39,4 +39,5 @@ public interface UserMapper { @Select("select * from \"user\"") List selectList(); + } diff --git a/spring-boot-extension-tests/mybatis-plugins-spring-boot-test/mybatis-typehandler-postgresql-spring-boot-test/src/test/java/com/livk/postgres/json/controller/UserControllerTest.java b/spring-boot-extension-tests/mybatis-plugins-spring-boot-test/mybatis-typehandler-postgresql-spring-boot-test/src/test/java/com/livk/postgres/json/controller/UserControllerTest.java index e29911472..3ec10abba 100644 --- a/spring-boot-extension-tests/mybatis-plugins-spring-boot-test/mybatis-typehandler-postgresql-spring-boot-test/src/test/java/com/livk/postgres/json/controller/UserControllerTest.java +++ b/spring-boot-extension-tests/mybatis-plugins-spring-boot-test/mybatis-typehandler-postgresql-spring-boot-test/src/test/java/com/livk/postgres/json/controller/UserControllerTest.java @@ -44,24 +44,20 @@ @AutoConfigureMockMvc @TestMethodOrder(MethodOrderer.OrderAnnotation.class) class UserControllerTest { + @Autowired MockMvc mockMvc; - @Order(1) @Test void testSave() throws Exception { - mockMvc.perform(post("/user")) - .andDo(print()) - .andExpect(status().isOk()) - .andExpect(content().string("true")); + mockMvc.perform(post("/user")).andDo(print()).andExpect(status().isOk()).andExpect(content().string("true")); } @Order(2) @Test void testUsers() throws Exception { - mockMvc.perform(get("/user")) - .andDo(print()) - .andExpect(status().isOk()); + mockMvc.perform(get("/user")).andDo(print()).andExpect(status().isOk()); } + } diff --git a/spring-boot-extension-tests/oss-spring-boot-test/oss-aliyun-spring-boot-test/src/main/java/com/livk/oss/aliyun/OssAliyunApp.java b/spring-boot-extension-tests/oss-spring-boot-test/oss-aliyun-spring-boot-test/src/main/java/com/livk/oss/aliyun/OssAliyunApp.java index 2033a44e3..ad5b5e8ed 100644 --- a/spring-boot-extension-tests/oss-spring-boot-test/oss-aliyun-spring-boot-test/src/main/java/com/livk/oss/aliyun/OssAliyunApp.java +++ b/spring-boot-extension-tests/oss-spring-boot-test/oss-aliyun-spring-boot-test/src/main/java/com/livk/oss/aliyun/OssAliyunApp.java @@ -25,7 +25,9 @@ */ @SpringBootApplication public class OssAliyunApp { + public static void main(String[] args) { SpringLauncher.run(args); } + } diff --git a/spring-boot-extension-tests/oss-spring-boot-test/oss-aliyun-spring-boot-test/src/main/java/com/livk/oss/aliyun/controller/OssController.java b/spring-boot-extension-tests/oss-spring-boot-test/oss-aliyun-spring-boot-test/src/main/java/com/livk/oss/aliyun/controller/OssController.java index 50a2d1938..25f4bc0a7 100644 --- a/spring-boot-extension-tests/oss-spring-boot-test/oss-aliyun-spring-boot-test/src/main/java/com/livk/oss/aliyun/controller/OssController.java +++ b/spring-boot-extension-tests/oss-spring-boot-test/oss-aliyun-spring-boot-test/src/main/java/com/livk/oss/aliyun/controller/OssController.java @@ -62,4 +62,5 @@ public HttpEntity test() throws IOException { String url = ossTemplate.getExternalLink("livk-cloud", "test.jpg"); return ResponseEntity.ok(url); } + } diff --git a/spring-boot-extension-tests/oss-spring-boot-test/oss-aliyun-spring-boot-test/src/test/java/com/livk/oss/aliyun/controller/OssControllerTest.java b/spring-boot-extension-tests/oss-spring-boot-test/oss-aliyun-spring-boot-test/src/test/java/com/livk/oss/aliyun/controller/OssControllerTest.java index 0543059b2..11367c49f 100644 --- a/spring-boot-extension-tests/oss-spring-boot-test/oss-aliyun-spring-boot-test/src/test/java/com/livk/oss/aliyun/controller/OssControllerTest.java +++ b/spring-boot-extension-tests/oss-spring-boot-test/oss-aliyun-spring-boot-test/src/test/java/com/livk/oss/aliyun/controller/OssControllerTest.java @@ -41,10 +41,10 @@ @SpringBootTest @AutoConfigureMockMvc class OssControllerTest { + @Autowired MockMvc mockMvc; - @Test void test() throws Exception { String url = mockMvc.perform(get("/oss/test")) @@ -60,5 +60,5 @@ void test() throws Exception { assertTrue(file.exists()); assertTrue(file.delete()); } -} +} diff --git a/spring-boot-extension-tests/oss-spring-boot-test/oss-minio-spring-boot-test/src/main/java/com/livk/oss/minio/OssMinioApp.java b/spring-boot-extension-tests/oss-spring-boot-test/oss-minio-spring-boot-test/src/main/java/com/livk/oss/minio/OssMinioApp.java index 9501249ce..8cc68e94d 100644 --- a/spring-boot-extension-tests/oss-spring-boot-test/oss-minio-spring-boot-test/src/main/java/com/livk/oss/minio/OssMinioApp.java +++ b/spring-boot-extension-tests/oss-spring-boot-test/oss-minio-spring-boot-test/src/main/java/com/livk/oss/minio/OssMinioApp.java @@ -25,7 +25,9 @@ */ @SpringBootApplication public class OssMinioApp { + public static void main(String[] args) { SpringLauncher.run(args); } + } diff --git a/spring-boot-extension-tests/oss-spring-boot-test/oss-minio-spring-boot-test/src/main/java/com/livk/oss/minio/controller/OssController.java b/spring-boot-extension-tests/oss-spring-boot-test/oss-minio-spring-boot-test/src/main/java/com/livk/oss/minio/controller/OssController.java index 3f8a56430..6075088c6 100644 --- a/spring-boot-extension-tests/oss-spring-boot-test/oss-minio-spring-boot-test/src/main/java/com/livk/oss/minio/controller/OssController.java +++ b/spring-boot-extension-tests/oss-spring-boot-test/oss-minio-spring-boot-test/src/main/java/com/livk/oss/minio/controller/OssController.java @@ -60,4 +60,5 @@ public HttpEntity test() throws IOException { String url = ossTemplate.getExternalLink("test", "test.jpg"); return ResponseEntity.ok(url); } + } diff --git a/spring-boot-extension-tests/oss-spring-boot-test/oss-minio-spring-boot-test/src/test/java/com/livk/oss/minio/controller/OssControllerTest.java b/spring-boot-extension-tests/oss-spring-boot-test/oss-minio-spring-boot-test/src/test/java/com/livk/oss/minio/controller/OssControllerTest.java index 57c0c2c18..0c9a35bb4 100644 --- a/spring-boot-extension-tests/oss-spring-boot-test/oss-minio-spring-boot-test/src/test/java/com/livk/oss/minio/controller/OssControllerTest.java +++ b/spring-boot-extension-tests/oss-spring-boot-test/oss-minio-spring-boot-test/src/test/java/com/livk/oss/minio/controller/OssControllerTest.java @@ -39,10 +39,10 @@ @SpringBootTest @AutoConfigureMockMvc class OssControllerTest { + @Autowired MockMvc mockMvc; - @Test void test() throws Exception { String url = mockMvc.perform(get("/oss/test")) @@ -58,5 +58,5 @@ void test() throws Exception { assertTrue(file.exists()); assertTrue(file.delete()); } -} +} diff --git a/spring-boot-extension-tests/qrcode-spring-boot-test/qrcode-spring-boot-test-webflux/src/main/java/com/livk/qrcode/webflux/QRCodeWebfluxExample.java b/spring-boot-extension-tests/qrcode-spring-boot-test/qrcode-spring-boot-test-webflux/src/main/java/com/livk/qrcode/webflux/QRCodeWebfluxExample.java index 7179bd355..82ba538db 100644 --- a/spring-boot-extension-tests/qrcode-spring-boot-test/qrcode-spring-boot-test-webflux/src/main/java/com/livk/qrcode/webflux/QRCodeWebfluxExample.java +++ b/spring-boot-extension-tests/qrcode-spring-boot-test/qrcode-spring-boot-test-webflux/src/main/java/com/livk/qrcode/webflux/QRCodeWebfluxExample.java @@ -29,7 +29,9 @@ */ @SpringBootApplication public class QRCodeWebfluxExample { + public static void main(String[] args) { SpringLauncher.run(args); } + } diff --git a/spring-boot-extension-tests/qrcode-spring-boot-test/qrcode-spring-boot-test-webflux/src/main/java/com/livk/qrcode/webflux/controller/QRCode2Controller.java b/spring-boot-extension-tests/qrcode-spring-boot-test/qrcode-spring-boot-test-webflux/src/main/java/com/livk/qrcode/webflux/controller/QRCode2Controller.java index f46f2abcf..c1a2016a7 100644 --- a/spring-boot-extension-tests/qrcode-spring-boot-test/qrcode-spring-boot-test-webflux/src/main/java/com/livk/qrcode/webflux/controller/QRCode2Controller.java +++ b/spring-boot-extension-tests/qrcode-spring-boot-test/qrcode-spring-boot-test-webflux/src/main/java/com/livk/qrcode/webflux/controller/QRCode2Controller.java @@ -58,4 +58,5 @@ public Map json(@RequestBody JsonNode node) { public Mono> jsonMono(@RequestBody JsonNode node) { return Mono.just(JsonMapperUtils.convertValueMap(node, String.class, String.class)); } + } diff --git a/spring-boot-extension-tests/qrcode-spring-boot-test/qrcode-spring-boot-test-webflux/src/main/java/com/livk/qrcode/webflux/controller/QRCodeController.java b/spring-boot-extension-tests/qrcode-spring-boot-test/qrcode-spring-boot-test-webflux/src/main/java/com/livk/qrcode/webflux/controller/QRCodeController.java index 536412c41..2f4182d61 100644 --- a/spring-boot-extension-tests/qrcode-spring-boot-test/qrcode-spring-boot-test-webflux/src/main/java/com/livk/qrcode/webflux/controller/QRCodeController.java +++ b/spring-boot-extension-tests/qrcode-spring-boot-test/qrcode-spring-boot-test-webflux/src/main/java/com/livk/qrcode/webflux/controller/QRCodeController.java @@ -73,4 +73,5 @@ public Map json(@RequestBody JsonNode node) { public Mono> jsonMono(@RequestBody JsonNode node) { return Mono.just(JsonMapperUtils.convertValueMap(node, String.class, String.class)); } + } diff --git a/spring-boot-extension-tests/qrcode-spring-boot-test/qrcode-spring-boot-test-webflux/src/test/java/com/livk/qrcode/webflux/controller/QRCode2ControllerTest.java b/spring-boot-extension-tests/qrcode-spring-boot-test/qrcode-spring-boot-test-webflux/src/test/java/com/livk/qrcode/webflux/controller/QRCode2ControllerTest.java index 6f42f9886..7b7af7732 100644 --- a/spring-boot-extension-tests/qrcode-spring-boot-test/qrcode-spring-boot-test-webflux/src/test/java/com/livk/qrcode/webflux/controller/QRCode2ControllerTest.java +++ b/spring-boot-extension-tests/qrcode-spring-boot-test/qrcode-spring-boot-test-webflux/src/test/java/com/livk/qrcode/webflux/controller/QRCode2ControllerTest.java @@ -58,9 +58,7 @@ class QRCode2ControllerTest { @Test void text() throws IOException { client.get() - .uri(uriBuilder -> uriBuilder.path("/qrcode2") - .queryParam("text", text) - .build()) + .uri(uriBuilder -> uriBuilder.path("/qrcode2").queryParam("text", text).build()) .exchange() .expectStatus() .isOk() @@ -68,7 +66,8 @@ void text() throws IOException { .value(resource -> { try { FileUtils.download(resource.getInputStream(), "./text." + PicType.JPG.name().toLowerCase()); - } catch (IOException e) { + } + catch (IOException e) { throw new RuntimeException(e); } }); @@ -83,9 +82,7 @@ void text() throws IOException { @Test void textMono() throws IOException { client.get() - .uri(uriBuilder -> uriBuilder.path("/qrcode2/mono") - .queryParam("text", text) - .build()) + .uri(uriBuilder -> uriBuilder.path("/qrcode2/mono").queryParam("text", text).build()) .exchange() .expectStatus() .isOk() @@ -93,7 +90,8 @@ void textMono() throws IOException { .value(resource -> { try { FileUtils.download(resource.getInputStream(), "./textMono." + PicType.JPG.name().toLowerCase()); - } catch (IOException e) { + } + catch (IOException e) { throw new RuntimeException(e); } }); @@ -118,7 +116,8 @@ void json() throws IOException { .value(resource -> { try { FileUtils.download(resource.getInputStream(), "./json." + PicType.JPG.name().toLowerCase()); - } catch (IOException e) { + } + catch (IOException e) { throw new RuntimeException(e); } }); @@ -143,7 +142,8 @@ void jsonMono() throws IOException { .value(resource -> { try { FileUtils.download(resource.getInputStream(), "./jsonMono." + PicType.JPG.name().toLowerCase()); - } catch (IOException e) { + } + catch (IOException e) { throw new RuntimeException(e); } }); @@ -154,4 +154,5 @@ void jsonMono() throws IOException { assertTrue(outFile.exists()); assertTrue(outFile.delete()); } + } diff --git a/spring-boot-extension-tests/qrcode-spring-boot-test/qrcode-spring-boot-test-webflux/src/test/java/com/livk/qrcode/webflux/controller/QRCodeControllerTest.java b/spring-boot-extension-tests/qrcode-spring-boot-test/qrcode-spring-boot-test-webflux/src/test/java/com/livk/qrcode/webflux/controller/QRCodeControllerTest.java index 7195980cc..a98a57c07 100644 --- a/spring-boot-extension-tests/qrcode-spring-boot-test/qrcode-spring-boot-test-webflux/src/test/java/com/livk/qrcode/webflux/controller/QRCodeControllerTest.java +++ b/spring-boot-extension-tests/qrcode-spring-boot-test/qrcode-spring-boot-test-webflux/src/test/java/com/livk/qrcode/webflux/controller/QRCodeControllerTest.java @@ -58,9 +58,7 @@ class QRCodeControllerTest { @Test void text() throws IOException { client.get() - .uri(uriBuilder -> uriBuilder.path("/qrcode") - .queryParam("text", text) - .build()) + .uri(uriBuilder -> uriBuilder.path("/qrcode").queryParam("text", text).build()) .exchange() .expectStatus() .isOk() @@ -68,7 +66,8 @@ void text() throws IOException { .value(resource -> { try { FileUtils.download(resource.getInputStream(), "./text." + PicType.JPG.name().toLowerCase()); - } catch (IOException e) { + } + catch (IOException e) { throw new RuntimeException(e); } }); @@ -83,9 +82,7 @@ void text() throws IOException { @Test void textMono() throws IOException { client.get() - .uri(uriBuilder -> uriBuilder.path("/qrcode/mono") - .queryParam("text", text) - .build()) + .uri(uriBuilder -> uriBuilder.path("/qrcode/mono").queryParam("text", text).build()) .exchange() .expectStatus() .isOk() @@ -93,7 +90,8 @@ void textMono() throws IOException { .value(resource -> { try { FileUtils.download(resource.getInputStream(), "./textMono." + PicType.JPG.name().toLowerCase()); - } catch (IOException e) { + } + catch (IOException e) { throw new RuntimeException(e); } }); @@ -108,9 +106,7 @@ void textMono() throws IOException { @Test void textCode() throws IOException { client.get() - .uri(uriBuilder -> uriBuilder.path("/qrcode/entity") - .queryParam("text", text) - .build()) + .uri(uriBuilder -> uriBuilder.path("/qrcode/entity").queryParam("text", text).build()) .exchange() .expectStatus() .isOk() @@ -118,7 +114,8 @@ void textCode() throws IOException { .value(resource -> { try { FileUtils.download(resource.getInputStream(), "./text." + PicType.JPG.name().toLowerCase()); - } catch (IOException e) { + } + catch (IOException e) { throw new RuntimeException(e); } }); @@ -143,7 +140,8 @@ void json() throws IOException { .value(resource -> { try { FileUtils.download(resource.getInputStream(), "./json." + PicType.JPG.name().toLowerCase()); - } catch (IOException e) { + } + catch (IOException e) { throw new RuntimeException(e); } }); @@ -168,7 +166,8 @@ void jsonMono() throws IOException { .value(resource -> { try { FileUtils.download(resource.getInputStream(), "./jsonMono." + PicType.JPG.name().toLowerCase()); - } catch (IOException e) { + } + catch (IOException e) { throw new RuntimeException(e); } }); @@ -193,7 +192,8 @@ void jsonCode() throws IOException { .value(resource -> { try { FileUtils.download(resource.getInputStream(), "./json." + PicType.JPG.name().toLowerCase()); - } catch (IOException e) { + } + catch (IOException e) { throw new RuntimeException(e); } }); @@ -204,4 +204,5 @@ void jsonCode() throws IOException { assertTrue(outFile.exists()); assertTrue(outFile.delete()); } + } diff --git a/spring-boot-extension-tests/qrcode-spring-boot-test/qrcode-spring-boot-test-webmvc/src/main/java/com/livk/qrcode/mvc/QRCodeMvcExample.java b/spring-boot-extension-tests/qrcode-spring-boot-test/qrcode-spring-boot-test-webmvc/src/main/java/com/livk/qrcode/mvc/QRCodeMvcExample.java index 09ec4081a..238bf5066 100644 --- a/spring-boot-extension-tests/qrcode-spring-boot-test/qrcode-spring-boot-test-webmvc/src/main/java/com/livk/qrcode/mvc/QRCodeMvcExample.java +++ b/spring-boot-extension-tests/qrcode-spring-boot-test/qrcode-spring-boot-test-webmvc/src/main/java/com/livk/qrcode/mvc/QRCodeMvcExample.java @@ -29,7 +29,9 @@ */ @SpringBootApplication public class QRCodeMvcExample { + public static void main(String[] args) { SpringLauncher.run(args); } + } diff --git a/spring-boot-extension-tests/qrcode-spring-boot-test/qrcode-spring-boot-test-webmvc/src/main/java/com/livk/qrcode/mvc/controller/QRCode2Controller.java b/spring-boot-extension-tests/qrcode-spring-boot-test/qrcode-spring-boot-test-webmvc/src/main/java/com/livk/qrcode/mvc/controller/QRCode2Controller.java index ac7de8dec..b11102992 100644 --- a/spring-boot-extension-tests/qrcode-spring-boot-test/qrcode-spring-boot-test-webmvc/src/main/java/com/livk/qrcode/mvc/controller/QRCode2Controller.java +++ b/spring-boot-extension-tests/qrcode-spring-boot-test/qrcode-spring-boot-test-webmvc/src/main/java/com/livk/qrcode/mvc/controller/QRCode2Controller.java @@ -47,4 +47,5 @@ public String text(String text) { public Map json(@RequestBody JsonNode node) { return JsonMapperUtils.convertValueMap(node, String.class, String.class); } + } diff --git a/spring-boot-extension-tests/qrcode-spring-boot-test/qrcode-spring-boot-test-webmvc/src/main/java/com/livk/qrcode/mvc/controller/QRCodeController.java b/spring-boot-extension-tests/qrcode-spring-boot-test/qrcode-spring-boot-test-webmvc/src/main/java/com/livk/qrcode/mvc/controller/QRCodeController.java index 8f4daf252..de650870e 100644 --- a/spring-boot-extension-tests/qrcode-spring-boot-test/qrcode-spring-boot-test-webmvc/src/main/java/com/livk/qrcode/mvc/controller/QRCodeController.java +++ b/spring-boot-extension-tests/qrcode-spring-boot-test/qrcode-spring-boot-test-webmvc/src/main/java/com/livk/qrcode/mvc/controller/QRCodeController.java @@ -60,4 +60,5 @@ public QRCodeEntity> jsonCode(@RequestBody JsonNode node) { Map map = JsonMapperUtils.convertValueMap(node, String.class, String.class); return QRCodeEntity.builder(map).build(); } + } diff --git a/spring-boot-extension-tests/qrcode-spring-boot-test/qrcode-spring-boot-test-webmvc/src/test/java/com/livk/qrcode/mvc/controller/QRCode2ControllerTest.java b/spring-boot-extension-tests/qrcode-spring-boot-test/qrcode-spring-boot-test-webmvc/src/test/java/com/livk/qrcode/mvc/controller/QRCode2ControllerTest.java index 7a8cf005a..54cde565c 100644 --- a/spring-boot-extension-tests/qrcode-spring-boot-test/qrcode-spring-boot-test-webmvc/src/test/java/com/livk/qrcode/mvc/controller/QRCode2ControllerTest.java +++ b/spring-boot-extension-tests/qrcode-spring-boot-test/qrcode-spring-boot-test-webmvc/src/test/java/com/livk/qrcode/mvc/controller/QRCode2ControllerTest.java @@ -56,13 +56,10 @@ class QRCode2ControllerTest { @Test void text() throws Exception { String text = "Hello World!"; - mockMvc.perform(get("/qrcode2") - .param("text", text)) - .andExpect(status().isOk()) - .andDo(result -> { - ByteArrayInputStream in = new ByteArrayInputStream(result.getResponse().getContentAsByteArray()); - FileUtils.download(in, "./text." + PicType.JPG.name().toLowerCase()); - }); + mockMvc.perform(get("/qrcode2").param("text", text)).andExpect(status().isOk()).andDo(result -> { + ByteArrayInputStream in = new ByteArrayInputStream(result.getResponse().getContentAsByteArray()); + FileUtils.download(in, "./text." + PicType.JPG.name().toLowerCase()); + }); File outFile = new File("text." + PicType.JPG.name().toLowerCase()); try (FileInputStream inputStream = new FileInputStream(outFile)) { assertEquals(text, QRCodeUtils.parseQRCode(inputStream)); @@ -74,9 +71,7 @@ void text() throws Exception { @Test void json() throws Exception { String json = JsonMapperUtils.writeValueAsString(Map.of("username", "root", "password", "root")); - mockMvc.perform(post("/qrcode2/json") - .contentType(MediaType.APPLICATION_JSON) - .content(json)) + mockMvc.perform(post("/qrcode2/json").contentType(MediaType.APPLICATION_JSON).content(json)) .andExpect(status().isOk()) .andDo(result -> { ByteArrayInputStream in = new ByteArrayInputStream(result.getResponse().getContentAsByteArray()); @@ -89,4 +84,5 @@ void json() throws Exception { assertTrue(outFile.exists()); assertTrue(outFile.delete()); } + } diff --git a/spring-boot-extension-tests/qrcode-spring-boot-test/qrcode-spring-boot-test-webmvc/src/test/java/com/livk/qrcode/mvc/controller/QRCodeControllerTest.java b/spring-boot-extension-tests/qrcode-spring-boot-test/qrcode-spring-boot-test-webmvc/src/test/java/com/livk/qrcode/mvc/controller/QRCodeControllerTest.java index 8f5602487..bfd1b67f0 100644 --- a/spring-boot-extension-tests/qrcode-spring-boot-test/qrcode-spring-boot-test-webmvc/src/test/java/com/livk/qrcode/mvc/controller/QRCodeControllerTest.java +++ b/spring-boot-extension-tests/qrcode-spring-boot-test/qrcode-spring-boot-test-webmvc/src/test/java/com/livk/qrcode/mvc/controller/QRCodeControllerTest.java @@ -56,13 +56,10 @@ class QRCodeControllerTest { @Test void text() throws Exception { String text = "Hello World!"; - mockMvc.perform(get("/qrcode") - .param("text", text)) - .andExpect(status().isOk()) - .andDo(result -> { - ByteArrayInputStream in = new ByteArrayInputStream(result.getResponse().getContentAsByteArray()); - FileUtils.download(in, "./text." + PicType.JPG.name().toLowerCase()); - }); + mockMvc.perform(get("/qrcode").param("text", text)).andExpect(status().isOk()).andDo(result -> { + ByteArrayInputStream in = new ByteArrayInputStream(result.getResponse().getContentAsByteArray()); + FileUtils.download(in, "./text." + PicType.JPG.name().toLowerCase()); + }); File outFile = new File("text." + PicType.JPG.name().toLowerCase()); try (FileInputStream inputStream = new FileInputStream(outFile)) { assertEquals(text, QRCodeUtils.parseQRCode(inputStream)); @@ -74,9 +71,7 @@ void text() throws Exception { @Test void json() throws Exception { String json = JsonMapperUtils.writeValueAsString(Map.of("username", "root", "password", "root")); - mockMvc.perform(post("/qrcode/json") - .contentType(MediaType.APPLICATION_JSON) - .content(json)) + mockMvc.perform(post("/qrcode/json").contentType(MediaType.APPLICATION_JSON).content(json)) .andExpect(status().isOk()) .andDo(result -> { ByteArrayInputStream in = new ByteArrayInputStream(result.getResponse().getContentAsByteArray()); @@ -93,13 +88,10 @@ void json() throws Exception { @Test void textCode() throws Exception { String text = "Hello World!"; - mockMvc.perform(get("/qrcode/entity") - .param("text", text)) - .andExpect(status().isOk()) - .andDo(result -> { - ByteArrayInputStream in = new ByteArrayInputStream(result.getResponse().getContentAsByteArray()); - FileUtils.download(in, "./text." + PicType.JPG.name().toLowerCase()); - }); + mockMvc.perform(get("/qrcode/entity").param("text", text)).andExpect(status().isOk()).andDo(result -> { + ByteArrayInputStream in = new ByteArrayInputStream(result.getResponse().getContentAsByteArray()); + FileUtils.download(in, "./text." + PicType.JPG.name().toLowerCase()); + }); File outFile = new File("text." + PicType.JPG.name().toLowerCase()); try (FileInputStream inputStream = new FileInputStream(outFile)) { assertEquals(text, QRCodeUtils.parseQRCode(inputStream)); @@ -111,9 +103,7 @@ void textCode() throws Exception { @Test void jsonCode() throws Exception { String json = JsonMapperUtils.writeValueAsString(Map.of("username", "root", "password", "root")); - mockMvc.perform(post("/qrcode/entity/json") - .contentType(MediaType.APPLICATION_JSON) - .content(json)) + mockMvc.perform(post("/qrcode/entity/json").contentType(MediaType.APPLICATION_JSON).content(json)) .andExpect(status().isOk()) .andDo(result -> { ByteArrayInputStream in = new ByteArrayInputStream(result.getResponse().getContentAsByteArray()); @@ -126,4 +116,5 @@ void jsonCode() throws Exception { assertTrue(outFile.exists()); assertTrue(outFile.delete()); } + } diff --git a/spring-boot-extension-tests/redis-spring-boot-test/redisearch-spring-boot-test/redisearch-spring-boot-test-webflux/src/main/java/com/livk/redisearch/webflux/RediSearchApp.java b/spring-boot-extension-tests/redis-spring-boot-test/redisearch-spring-boot-test/redisearch-spring-boot-test-webflux/src/main/java/com/livk/redisearch/webflux/RediSearchApp.java index 92c8ef647..db298842e 100644 --- a/spring-boot-extension-tests/redis-spring-boot-test/redisearch-spring-boot-test/redisearch-spring-boot-test-webflux/src/main/java/com/livk/redisearch/webflux/RediSearchApp.java +++ b/spring-boot-extension-tests/redis-spring-boot-test/redisearch-spring-boot-test/redisearch-spring-boot-test-webflux/src/main/java/com/livk/redisearch/webflux/RediSearchApp.java @@ -44,6 +44,7 @@ @Slf4j @SpringBootApplication public class RediSearchApp { + public static void main(String[] args) { SpringLauncher.run(args); } @@ -56,16 +57,14 @@ public ApplicationRunner applicationRunner(StatefulRedisModulesConnection> list(@RequestParam(defaultValue = "*") String q .map(document -> JsonMapperUtils.convertValue(document, Student.class)); return ResponseEntity.ok(flux); } + } diff --git a/spring-boot-extension-tests/redis-spring-boot-test/redisearch-spring-boot-test/redisearch-spring-boot-test-webflux/src/main/java/com/livk/redisearch/webflux/entity/Student.java b/spring-boot-extension-tests/redis-spring-boot-test/redisearch-spring-boot-test/redisearch-spring-boot-test-webflux/src/main/java/com/livk/redisearch/webflux/entity/Student.java index 2248ef35d..c826bf0d3 100644 --- a/spring-boot-extension-tests/redis-spring-boot-test/redisearch-spring-boot-test/redisearch-spring-boot-test-webflux/src/main/java/com/livk/redisearch/webflux/entity/Student.java +++ b/spring-boot-extension-tests/redis-spring-boot-test/redisearch-spring-boot-test/redisearch-spring-boot-test-webflux/src/main/java/com/livk/redisearch/webflux/entity/Student.java @@ -38,10 +38,14 @@ public class Student { @JsonProperty("name") private String name; + @JsonProperty("sex") private String sex; + @JsonProperty("desc") private String desc; + @JsonProperty("class") private String classX; + } diff --git a/spring-boot-extension-tests/redis-spring-boot-test/redisearch-spring-boot-test/redisearch-spring-boot-test-webflux/src/test/java/com/livk/redisearch/webflux/controller/StudentControllerTest.java b/spring-boot-extension-tests/redis-spring-boot-test/redisearch-spring-boot-test/redisearch-spring-boot-test-webflux/src/test/java/com/livk/redisearch/webflux/controller/StudentControllerTest.java index 42f358f9c..3910738e0 100644 --- a/spring-boot-extension-tests/redis-spring-boot-test/redisearch-spring-boot-test/redisearch-spring-boot-test-webflux/src/test/java/com/livk/redisearch/webflux/controller/StudentControllerTest.java +++ b/spring-boot-extension-tests/redis-spring-boot-test/redisearch-spring-boot-test/redisearch-spring-boot-test-webflux/src/test/java/com/livk/redisearch/webflux/controller/StudentControllerTest.java @@ -35,10 +35,10 @@ @SpringBootTest @AutoConfigureWebTestClient class StudentControllerTest { + @Autowired WebTestClient client; - @Test void testList() { client.get() @@ -50,10 +50,9 @@ void testList() { .contentType(MediaType.APPLICATION_JSON) .expectBodyList(Student.class) .value(students -> { - List result = students.stream() - .map(Student::getName).toList(); - List list = List.of("livk-0", "livk-1", "livk-2", "livk-3", - "livk-4", "livk-5", "livk-6", "livk-7", "livk-8", "livk-9"); + List result = students.stream().map(Student::getName).toList(); + List list = List.of("livk-0", "livk-1", "livk-2", "livk-3", "livk-4", "livk-5", "livk-6", + "livk-7", "livk-8", "livk-9"); assertLinesMatch(list, result); }); @@ -68,16 +67,13 @@ void testList() { .contentType(MediaType.APPLICATION_JSON) .expectBodyList(Student.class) .value(students -> { - List result = students.stream() - .map(Student::getName).toList(); + List result = students.stream().map(Student::getName).toList(); List list = List.of("livk-0"); assertLinesMatch(list, result); }); client.get() - .uri(uriBuilder -> uriBuilder.path("/student") - .queryParam("query", "livk") - .build()) + .uri(uriBuilder -> uriBuilder.path("/student").queryParam("query", "livk").build()) .exchange() .expectStatus() .isOk() @@ -85,17 +81,14 @@ void testList() { .contentType(MediaType.APPLICATION_JSON) .expectBodyList(Student.class) .value(students -> { - List result = students.stream() - .map(Student::getName).toList(); - List list = List.of("livk-0", "livk-1", "livk-2", "livk-3", - "livk-4", "livk-5", "livk-6", "livk-7", "livk-8", "livk-9"); + List result = students.stream().map(Student::getName).toList(); + List list = List.of("livk-0", "livk-1", "livk-2", "livk-3", "livk-4", "livk-5", "livk-6", + "livk-7", "livk-8", "livk-9"); assertLinesMatch(list, result); }); client.get() - .uri(uriBuilder -> uriBuilder.path("/student") - .queryParam("query", "女") - .build()) + .uri(uriBuilder -> uriBuilder.path("/student").queryParam("query", "女").build()) .exchange() .expectStatus() .isOk() @@ -105,9 +98,7 @@ void testList() { .value(System.out::println); client.get() - .uri(uriBuilder -> uriBuilder.path("/student") - .queryParam("query", "是一个学生") - .build()) + .uri(uriBuilder -> uriBuilder.path("/student").queryParam("query", "是一个学生").build()) .exchange() .expectStatus() .isOk() @@ -116,4 +107,5 @@ void testList() { .expectBodyList(Student.class) .value(System.out::println); } + } diff --git a/spring-boot-extension-tests/redis-spring-boot-test/redisearch-spring-boot-test/redisearch-spring-boot-test-webmvc/src/main/java/com/livk/redisearch/mvc/RediSearchApp.java b/spring-boot-extension-tests/redis-spring-boot-test/redisearch-spring-boot-test/redisearch-spring-boot-test-webmvc/src/main/java/com/livk/redisearch/mvc/RediSearchApp.java index 227864823..9479abd1f 100644 --- a/spring-boot-extension-tests/redis-spring-boot-test/redisearch-spring-boot-test/redisearch-spring-boot-test-webmvc/src/main/java/com/livk/redisearch/mvc/RediSearchApp.java +++ b/spring-boot-extension-tests/redis-spring-boot-test/redisearch-spring-boot-test/redisearch-spring-boot-test-webmvc/src/main/java/com/livk/redisearch/mvc/RediSearchApp.java @@ -44,6 +44,7 @@ @Slf4j @SpringBootApplication public class RediSearchApp { + public static void main(String[] args) { SpringLauncher.run(args); } @@ -56,16 +57,14 @@ public ApplicationRunner applicationRunner(StatefulRedisModulesConnection> list(@RequestParam(defaultValue = "*") String q .toList(); return ResponseEntity.ok(studentList); } + } diff --git a/spring-boot-extension-tests/redis-spring-boot-test/redisearch-spring-boot-test/redisearch-spring-boot-test-webmvc/src/main/java/com/livk/redisearch/mvc/entity/Student.java b/spring-boot-extension-tests/redis-spring-boot-test/redisearch-spring-boot-test/redisearch-spring-boot-test-webmvc/src/main/java/com/livk/redisearch/mvc/entity/Student.java index eacb70f44..dc250b603 100644 --- a/spring-boot-extension-tests/redis-spring-boot-test/redisearch-spring-boot-test/redisearch-spring-boot-test-webmvc/src/main/java/com/livk/redisearch/mvc/entity/Student.java +++ b/spring-boot-extension-tests/redis-spring-boot-test/redisearch-spring-boot-test/redisearch-spring-boot-test-webmvc/src/main/java/com/livk/redisearch/mvc/entity/Student.java @@ -38,10 +38,14 @@ public class Student { @JsonProperty("name") private String name; + @JsonProperty("sex") private String sex; + @JsonProperty("desc") private String desc; + @JsonProperty("class") private String classX; + } diff --git a/spring-boot-extension-tests/redis-spring-boot-test/redisearch-spring-boot-test/redisearch-spring-boot-test-webmvc/src/test/java/com/livk/redisearch/mvc/controller/StudentControllerTest.java b/spring-boot-extension-tests/redis-spring-boot-test/redisearch-spring-boot-test/redisearch-spring-boot-test-webmvc/src/test/java/com/livk/redisearch/mvc/controller/StudentControllerTest.java index f811154de..5a9492de8 100644 --- a/spring-boot-extension-tests/redis-spring-boot-test/redisearch-spring-boot-test/redisearch-spring-boot-test-webmvc/src/test/java/com/livk/redisearch/mvc/controller/StudentControllerTest.java +++ b/spring-boot-extension-tests/redis-spring-boot-test/redisearch-spring-boot-test/redisearch-spring-boot-test-webmvc/src/test/java/com/livk/redisearch/mvc/controller/StudentControllerTest.java @@ -38,41 +38,34 @@ @SpringBootTest @AutoConfigureMockMvc class StudentControllerTest { + @Autowired MockMvc mockMvc; - @Test void testList() throws Exception { mockMvc.perform(get("/student")) .andExpect(status().isOk()) .andDo(print()) - .andExpect(jsonPath("[0:9].name", - "livk-0", "livk-1", "livk-2", "livk-3", "livk-4", "livk-5", "livk-6", "livk-7", "livk-8", "livk-9").exists()); + .andExpect(jsonPath("[0:9].name", "livk-0", "livk-1", "livk-2", "livk-3", "livk-4", "livk-5", "livk-6", + "livk-7", "livk-8", "livk-9") + .exists()); - mockMvc.perform(get("/student") - .param("query", "@class:{1班}")) + mockMvc.perform(get("/student").param("query", "@class:{1班}")) .andExpect(status().isOk()) .andDo(print()) .andExpect(jsonPath("[0].name", "livk-0").exists()); - mockMvc.perform(get("/student") - .param("query", "livk")) + mockMvc.perform(get("/student").param("query", "livk")) .andExpect(status().isOk()) .andDo(print()) - .andExpect(jsonPath("[0:9].name", - "livk-0", "livk-1", "livk-2", "livk-3", "livk-4", "livk-5", "livk-6", "livk-7", "livk-8", "livk-9").exists()); + .andExpect(jsonPath("[0:9].name", "livk-0", "livk-1", "livk-2", "livk-3", "livk-4", "livk-5", "livk-6", + "livk-7", "livk-8", "livk-9") + .exists()); - mockMvc.perform(get("/student") - .param("query", "女")) - .andExpect(status().isOk()) - .andDo(print()); + mockMvc.perform(get("/student").param("query", "女")).andExpect(status().isOk()).andDo(print()); - mockMvc.perform(get("/student") - .param("query", "是一个学生")) - .andExpect(status().isOk()) - .andDo(print()); + mockMvc.perform(get("/student").param("query", "是一个学生")).andExpect(status().isOk()).andDo(print()); } -} - +} diff --git a/spring-boot-extension-tests/redis-spring-boot-test/redisson-spring-boot-test/src/main/java/com/livk/redisson/schedule/ScheduleController.java b/spring-boot-extension-tests/redis-spring-boot-test/redisson-spring-boot-test/src/main/java/com/livk/redisson/schedule/ScheduleController.java index bbcc3fd47..4c49337f3 100644 --- a/spring-boot-extension-tests/redis-spring-boot-test/redisson-spring-boot-test/src/main/java/com/livk/redisson/schedule/ScheduleController.java +++ b/spring-boot-extension-tests/redis-spring-boot-test/redisson-spring-boot-test/src/main/java/com/livk/redisson/schedule/ScheduleController.java @@ -43,4 +43,5 @@ public HttpEntity handler() { scheduleHandler.start(); return ResponseEntity.ok("ok"); } + } diff --git a/spring-boot-extension-tests/redis-spring-boot-test/redisson-spring-boot-test/src/main/java/com/livk/redisson/schedule/ScheduleHandler.java b/spring-boot-extension-tests/redis-spring-boot-test/redisson-spring-boot-test/src/main/java/com/livk/redisson/schedule/ScheduleHandler.java index b85bfefc3..f24f010e3 100644 --- a/spring-boot-extension-tests/redis-spring-boot-test/redisson-spring-boot-test/src/main/java/com/livk/redisson/schedule/ScheduleHandler.java +++ b/spring-boot-extension-tests/redis-spring-boot-test/redisson-spring-boot-test/src/main/java/com/livk/redisson/schedule/ScheduleHandler.java @@ -49,10 +49,12 @@ public void start() { log.info("time:{}", System.currentTimeMillis()); try { Thread.sleep(100L); - } catch (InterruptedException e) { + } + catch (InterruptedException e) { throw new RuntimeException(e); } }, 0, 1, TimeUnit.SECONDS); log.info("TaskId:{}", future.getTaskId()); } + } diff --git a/spring-boot-extension-tests/redis-spring-boot-test/redisson-spring-boot-test/src/test/java/com/livk/redisson/schedule/ScheduleHandlerTest.java b/spring-boot-extension-tests/redis-spring-boot-test/redisson-spring-boot-test/src/test/java/com/livk/redisson/schedule/ScheduleHandlerTest.java index 147b4fac5..9e7a3ecd7 100644 --- a/spring-boot-extension-tests/redis-spring-boot-test/redisson-spring-boot-test/src/test/java/com/livk/redisson/schedule/ScheduleHandlerTest.java +++ b/spring-boot-extension-tests/redis-spring-boot-test/redisson-spring-boot-test/src/test/java/com/livk/redisson/schedule/ScheduleHandlerTest.java @@ -38,4 +38,5 @@ class ScheduleHandlerTest { void start() { scheduleHandler.start(); } + } diff --git a/spring-boot-extension-tests/useragent-spring-boot-test/browscap-spring-boot-test-webflux/src/main/java/com/livk/browscap/webflux/BrowscapWebApp.java b/spring-boot-extension-tests/useragent-spring-boot-test/browscap-spring-boot-test-webflux/src/main/java/com/livk/browscap/webflux/BrowscapWebApp.java index aac47f869..d11c80201 100644 --- a/spring-boot-extension-tests/useragent-spring-boot-test/browscap-spring-boot-test-webflux/src/main/java/com/livk/browscap/webflux/BrowscapWebApp.java +++ b/spring-boot-extension-tests/useragent-spring-boot-test/browscap-spring-boot-test-webflux/src/main/java/com/livk/browscap/webflux/BrowscapWebApp.java @@ -29,7 +29,9 @@ */ @SpringBootApplication public class BrowscapWebApp { + public static void main(String[] args) { SpringLauncher.run(args); } + } diff --git a/spring-boot-extension-tests/useragent-spring-boot-test/browscap-spring-boot-test-webflux/src/main/java/com/livk/browscap/webflux/controller/UserAgentController.java b/spring-boot-extension-tests/useragent-spring-boot-test/browscap-spring-boot-test-webflux/src/main/java/com/livk/browscap/webflux/controller/UserAgentController.java index 077884d7f..ae5c9e035 100644 --- a/spring-boot-extension-tests/useragent-spring-boot-test/browscap-spring-boot-test-webflux/src/main/java/com/livk/browscap/webflux/controller/UserAgentController.java +++ b/spring-boot-extension-tests/useragent-spring-boot-test/browscap-spring-boot-test-webflux/src/main/java/com/livk/browscap/webflux/controller/UserAgentController.java @@ -50,4 +50,5 @@ public Mono>> get(@UserAgentInfo Mono UUID.randomUUID().toString(), Function.identity())) .map(ResponseEntity::ok); } + } diff --git a/spring-boot-extension-tests/useragent-spring-boot-test/browscap-spring-boot-test-webflux/src/test/java/com/livk/browscap/webflux/controller/UserAgentControllerTest.java b/spring-boot-extension-tests/useragent-spring-boot-test/browscap-spring-boot-test-webflux/src/test/java/com/livk/browscap/webflux/controller/UserAgentControllerTest.java index 6c88592df..20ecc47d5 100644 --- a/spring-boot-extension-tests/useragent-spring-boot-test/browscap-spring-boot-test-webflux/src/test/java/com/livk/browscap/webflux/controller/UserAgentControllerTest.java +++ b/spring-boot-extension-tests/useragent-spring-boot-test/browscap-spring-boot-test-webflux/src/test/java/com/livk/browscap/webflux/controller/UserAgentControllerTest.java @@ -51,4 +51,5 @@ void getTest() { .expectBody(JsonNode.class) .value(System.out::println); } + } diff --git a/spring-boot-extension-tests/useragent-spring-boot-test/browscap-spring-boot-test-webmvc/src/main/java/com/livk/browscap/mvc/BrowscapWebApp.java b/spring-boot-extension-tests/useragent-spring-boot-test/browscap-spring-boot-test-webmvc/src/main/java/com/livk/browscap/mvc/BrowscapWebApp.java index 369e7d731..59a6010ee 100644 --- a/spring-boot-extension-tests/useragent-spring-boot-test/browscap-spring-boot-test-webmvc/src/main/java/com/livk/browscap/mvc/BrowscapWebApp.java +++ b/spring-boot-extension-tests/useragent-spring-boot-test/browscap-spring-boot-test-webmvc/src/main/java/com/livk/browscap/mvc/BrowscapWebApp.java @@ -29,7 +29,9 @@ */ @SpringBootApplication public class BrowscapWebApp { + public static void main(String[] args) { SpringLauncher.run(args); } + } diff --git a/spring-boot-extension-tests/useragent-spring-boot-test/browscap-spring-boot-test-webmvc/src/main/java/com/livk/browscap/mvc/controller/UserAgentController.java b/spring-boot-extension-tests/useragent-spring-boot-test/browscap-spring-boot-test-webmvc/src/main/java/com/livk/browscap/mvc/controller/UserAgentController.java index 5a6ed0264..7fcdbebdb 100644 --- a/spring-boot-extension-tests/useragent-spring-boot-test/browscap-spring-boot-test-webmvc/src/main/java/com/livk/browscap/mvc/controller/UserAgentController.java +++ b/spring-boot-extension-tests/useragent-spring-boot-test/browscap-spring-boot-test-webmvc/src/main/java/com/livk/browscap/mvc/controller/UserAgentController.java @@ -42,8 +42,9 @@ public class UserAgentController { @GetMapping public HttpEntity> get(@UserAgentInfo UserAgent userAgent) { - Map map = Map.of(UUID.randomUUID().toString(), userAgent, - UUID.randomUUID().toString(), UserAgentContextHolder.getUserAgentContext()); + Map map = Map.of(UUID.randomUUID().toString(), userAgent, UUID.randomUUID().toString(), + UserAgentContextHolder.getUserAgentContext()); return ResponseEntity.ok(map); } + } diff --git a/spring-boot-extension-tests/useragent-spring-boot-test/browscap-spring-boot-test-webmvc/src/test/java/com/livk/browscap/mvc/controller/UserAgentControllerTest.java b/spring-boot-extension-tests/useragent-spring-boot-test/browscap-spring-boot-test-webmvc/src/test/java/com/livk/browscap/mvc/controller/UserAgentControllerTest.java index b8035249c..7a8ba7611 100644 --- a/spring-boot-extension-tests/useragent-spring-boot-test/browscap-spring-boot-test-webmvc/src/test/java/com/livk/browscap/mvc/controller/UserAgentControllerTest.java +++ b/spring-boot-extension-tests/useragent-spring-boot-test/browscap-spring-boot-test-webmvc/src/test/java/com/livk/browscap/mvc/controller/UserAgentControllerTest.java @@ -43,8 +43,7 @@ class UserAgentControllerTest { @Test void getTest() throws Exception { - mockMvc.perform(get("/user-agent")) - .andExpect(status().isOk()) - .andDo(print()); + mockMvc.perform(get("/user-agent")).andExpect(status().isOk()).andDo(print()); } + } diff --git a/spring-boot-extension-tests/useragent-spring-boot-test/yauaa-spring-boot-test-webflux/src/main/java/com/livk/yauaa/webflux/YauaaWebApp.java b/spring-boot-extension-tests/useragent-spring-boot-test/yauaa-spring-boot-test-webflux/src/main/java/com/livk/yauaa/webflux/YauaaWebApp.java index dc05d532a..4fb8c0884 100644 --- a/spring-boot-extension-tests/useragent-spring-boot-test/yauaa-spring-boot-test-webflux/src/main/java/com/livk/yauaa/webflux/YauaaWebApp.java +++ b/spring-boot-extension-tests/useragent-spring-boot-test/yauaa-spring-boot-test-webflux/src/main/java/com/livk/yauaa/webflux/YauaaWebApp.java @@ -29,7 +29,9 @@ */ @SpringBootApplication public class YauaaWebApp { + public static void main(String[] args) { SpringLauncher.run(args); } + } diff --git a/spring-boot-extension-tests/useragent-spring-boot-test/yauaa-spring-boot-test-webflux/src/main/java/com/livk/yauaa/webflux/controller/UserAgentController.java b/spring-boot-extension-tests/useragent-spring-boot-test/yauaa-spring-boot-test-webflux/src/main/java/com/livk/yauaa/webflux/controller/UserAgentController.java index 83c1db447..af2498f81 100644 --- a/spring-boot-extension-tests/useragent-spring-boot-test/yauaa-spring-boot-test-webflux/src/main/java/com/livk/yauaa/webflux/controller/UserAgentController.java +++ b/spring-boot-extension-tests/useragent-spring-boot-test/yauaa-spring-boot-test-webflux/src/main/java/com/livk/yauaa/webflux/controller/UserAgentController.java @@ -50,4 +50,5 @@ public Mono>> get(@UserAgentInfo Mono UUID.randomUUID().toString(), Function.identity())) .map(ResponseEntity::ok); } + } diff --git a/spring-boot-extension-tests/useragent-spring-boot-test/yauaa-spring-boot-test-webflux/src/test/java/com/livk/yauaa/webflux/controller/UserAgentControllerTest.java b/spring-boot-extension-tests/useragent-spring-boot-test/yauaa-spring-boot-test-webflux/src/test/java/com/livk/yauaa/webflux/controller/UserAgentControllerTest.java index ebe0a9470..7d306c78f 100644 --- a/spring-boot-extension-tests/useragent-spring-boot-test/yauaa-spring-boot-test-webflux/src/test/java/com/livk/yauaa/webflux/controller/UserAgentControllerTest.java +++ b/spring-boot-extension-tests/useragent-spring-boot-test/yauaa-spring-boot-test-webflux/src/test/java/com/livk/yauaa/webflux/controller/UserAgentControllerTest.java @@ -51,4 +51,5 @@ void getTest() { .expectBody(JsonNode.class) .value(System.out::println); } + } diff --git a/spring-boot-extension-tests/useragent-spring-boot-test/yauaa-spring-boot-test-webmvc/src/main/java/com/livk/yauaa/webflux/YauaaWebApp.java b/spring-boot-extension-tests/useragent-spring-boot-test/yauaa-spring-boot-test-webmvc/src/main/java/com/livk/yauaa/webflux/YauaaWebApp.java index dc05d532a..4fb8c0884 100644 --- a/spring-boot-extension-tests/useragent-spring-boot-test/yauaa-spring-boot-test-webmvc/src/main/java/com/livk/yauaa/webflux/YauaaWebApp.java +++ b/spring-boot-extension-tests/useragent-spring-boot-test/yauaa-spring-boot-test-webmvc/src/main/java/com/livk/yauaa/webflux/YauaaWebApp.java @@ -29,7 +29,9 @@ */ @SpringBootApplication public class YauaaWebApp { + public static void main(String[] args) { SpringLauncher.run(args); } + } diff --git a/spring-boot-extension-tests/useragent-spring-boot-test/yauaa-spring-boot-test-webmvc/src/main/java/com/livk/yauaa/webflux/controller/UserAgentController.java b/spring-boot-extension-tests/useragent-spring-boot-test/yauaa-spring-boot-test-webmvc/src/main/java/com/livk/yauaa/webflux/controller/UserAgentController.java index 1e7d5210c..835932fb6 100644 --- a/spring-boot-extension-tests/useragent-spring-boot-test/yauaa-spring-boot-test-webmvc/src/main/java/com/livk/yauaa/webflux/controller/UserAgentController.java +++ b/spring-boot-extension-tests/useragent-spring-boot-test/yauaa-spring-boot-test-webmvc/src/main/java/com/livk/yauaa/webflux/controller/UserAgentController.java @@ -42,8 +42,9 @@ public class UserAgentController { @GetMapping public HttpEntity> get(@UserAgentInfo UserAgent userAgent) { - Map map = Map.of(UUID.randomUUID().toString(), userAgent, - UUID.randomUUID().toString(), UserAgentContextHolder.getUserAgentContext()); + Map map = Map.of(UUID.randomUUID().toString(), userAgent, UUID.randomUUID().toString(), + UserAgentContextHolder.getUserAgentContext()); return ResponseEntity.ok(map); } + } diff --git a/spring-boot-extension-tests/useragent-spring-boot-test/yauaa-spring-boot-test-webmvc/src/test/java/com/livk/yauaa/webflux/controller/UserAgentControllerTest.java b/spring-boot-extension-tests/useragent-spring-boot-test/yauaa-spring-boot-test-webmvc/src/test/java/com/livk/yauaa/webflux/controller/UserAgentControllerTest.java index d9a07197a..ad27b0618 100644 --- a/spring-boot-extension-tests/useragent-spring-boot-test/yauaa-spring-boot-test-webmvc/src/test/java/com/livk/yauaa/webflux/controller/UserAgentControllerTest.java +++ b/spring-boot-extension-tests/useragent-spring-boot-test/yauaa-spring-boot-test-webmvc/src/test/java/com/livk/yauaa/webflux/controller/UserAgentControllerTest.java @@ -43,8 +43,7 @@ class UserAgentControllerTest { @Test void getTest() throws Exception { - mockMvc.perform(get("/user-agent")) - .andExpect(status().isOk()) - .andDo(print()); + mockMvc.perform(get("/user-agent")).andExpect(status().isOk()).andDo(print()); } + } diff --git a/spring-extension-commons/src/main/java/com/livk/commons/SpringLauncher.java b/spring-extension-commons/src/main/java/com/livk/commons/SpringLauncher.java index 965f0031b..103a7ff63 100644 --- a/spring-extension-commons/src/main/java/com/livk/commons/SpringLauncher.java +++ b/spring-extension-commons/src/main/java/com/livk/commons/SpringLauncher.java @@ -51,7 +51,6 @@ public class SpringLauncher { * Springboot主启动 *

* 自动推导当前类Class - * * @param args main方法参数 * @return ConfigurableApplicationContext */ @@ -63,20 +62,19 @@ public static ConfigurableApplicationContext run(String[] args) { .map(ClassUtils::resolveClassName) .filter(type -> type.isAnnotationPresent(SpringBootApplication.class)) .findFirst() - .orElseThrow(() -> new AnnotationConfigurationException(" 缺少@" + SpringBootApplication.class.getName() + "注解")); + .orElseThrow( + () -> new AnnotationConfigurationException(" 缺少@" + SpringBootApplication.class.getName() + "注解")); return run(mainClass, args); } /** * Springboot主启动 - * * @param targetClass 主启动类class - * @param args main方法参数 + * @param args main方法参数 * @return ConfigurableApplicationContext */ public static ConfigurableApplicationContext run(Class targetClass, String[] args) { - application = new SpringApplicationBuilder(targetClass) - .banner(CloudBanner.create()) + application = new SpringApplicationBuilder(targetClass).banner(CloudBanner.create()) .bannerMode(Banner.Mode.CONSOLE) .build(args); return application.run(args); @@ -84,7 +82,6 @@ public static ConfigurableApplicationContext run(Class targetClass, String[] /** * 获取当前包版本 - * * @return the version */ public static String getVersion() { @@ -94,7 +91,6 @@ public static String getVersion() { /** * 获取到SpringApplication - * * @return SpringApplication */ public static SpringApplication application() { @@ -103,24 +99,24 @@ public static SpringApplication application() { @NoArgsConstructor(staticName = "create") private static class CloudBanner implements Banner { + private static final String banner = """ - ██ ██ ██ ██████ ██ ██ - ░██ ░░ ░██ ██░░░░██ ░██ ░██ - ░██ ██ ██ ██░██ ██ ██ ░░ ░██ ██████ ██ ██ ░██ - ░██ ░██░██ ░██░██ ██ ░██ ░██ ██░░░░██░██ ░██ ██████ - ░██ ░██░░██ ░██ ░████ ░██ ░██░██ ░██░██ ░██ ██░░░██ - ░██ ░██ ░░████ ░██░██ ░░██ ██ ░██░██ ░██░██ ░██░██ ░██ - ░████████░██ ░░██ ░██░░██ ░░██████ ███░░██████ ░░██████░░██████ - ░░░░░░░░ ░░ ░░ ░░ ░░ ░░░░░░ ░░░ ░░░░░░ ░░░░░░ ░░░░░░ - """; + ██ ██ ██ ██████ ██ ██ + ░██ ░░ ░██ ██░░░░██ ░██ ░██ + ░██ ██ ██ ██░██ ██ ██ ░░ ░██ ██████ ██ ██ ░██ + ░██ ░██░██ ░██░██ ██ ░██ ░██ ██░░░░██░██ ░██ ██████ + ░██ ░██░░██ ░██ ░████ ░██ ░██░██ ░██░██ ░██ ██░░░██ + ░██ ░██ ░░████ ░██░██ ░░██ ██ ░██░██ ░██░██ ░██░██ ░██ + ░████████░██ ░░██ ░██░░██ ░░██████ ███░░██████ ░░██████░░██████ + ░░░░░░░░ ░░ ░░ ░░ ░░ ░░░░░░ ░░░ ░░░░░░ ░░░░░░ ░░░░░░ + """; @Override public void printBanner(Environment environment, Class sourceClass, PrintStream out) { if (environment.getProperty("spring.banner.enabled", Boolean.class, true)) { out.println(banner); int max = banner.lines().mapToInt(String::length).max().orElse(0); - new Format(max, out) - .println(" Spring Version: " + SpringVersion.getVersion() + " ") + new Format(max, out).println(" Spring Version: " + SpringVersion.getVersion() + " ") .println(" Spring Boot Version: " + SpringBootVersion.getVersion() + " ") .println(" Spring Boot Extension Version: " + getVersion() + " ") .println(" Current Time: " + DateUtils.format(LocalDateTime.now(), DateUtils.YMD_HMS) + " ") @@ -129,17 +125,19 @@ public void printBanner(Environment environment, Class sourceClass, PrintStre .flush(); } } + } private static class Format { private final static char ch = '*'; + private final int n; + private final PrintStream out; /** * 构建Format - * * @param max the max * @param out the out */ @@ -149,9 +147,7 @@ private static class Format { } /** - * 输出字符串 - * 前后使用*补全 - * + * 输出字符串 前后使用*补全 * @param str the str * @return the format */ @@ -174,5 +170,7 @@ public Format println(String str) { public void flush() { out.flush(); } + } + } diff --git a/spring-extension-commons/src/main/java/com/livk/commons/aop/AnnotationAbstractPointcutAdvisor.java b/spring-extension-commons/src/main/java/com/livk/commons/aop/AnnotationAbstractPointcutAdvisor.java index 5405b9654..568982642 100644 --- a/spring-extension-commons/src/main/java/com/livk/commons/aop/AnnotationAbstractPointcutAdvisor.java +++ b/spring-extension-commons/src/main/java/com/livk/commons/aop/AnnotationAbstractPointcutAdvisor.java @@ -35,14 +35,14 @@ * @author livk */ public abstract class AnnotationAbstractPointcutAdvisor extends AbstractPointcutAdvisor - implements IntroductionInterceptor { + implements IntroductionInterceptor { /** * 切点注解类型 */ @SuppressWarnings("unchecked") - protected final Class annotationType = (Class) GenericTypeResolver.resolveTypeArgument(this.getClass(), AnnotationAbstractPointcutAdvisor.class); - + protected final Class annotationType = (Class) GenericTypeResolver.resolveTypeArgument(this.getClass(), + AnnotationAbstractPointcutAdvisor.class); @NonNull @Override @@ -57,7 +57,6 @@ public Object invoke(@NonNull MethodInvocation invocation) throws Throwable { /** * 执行拦截的方法 - * * @param invocation 方法相关信息 * @param annotation 注解信息 * @return 方法返回结果 @@ -75,4 +74,5 @@ public boolean implementsInterface(@NonNull Class intf) { public Advice getAdvice() { return this; } + } diff --git a/spring-extension-commons/src/main/java/com/livk/commons/aop/AnnotationAbstractPointcutTypeAdvisor.java b/spring-extension-commons/src/main/java/com/livk/commons/aop/AnnotationAbstractPointcutTypeAdvisor.java index a26b7edef..80521dc15 100644 --- a/spring-extension-commons/src/main/java/com/livk/commons/aop/AnnotationAbstractPointcutTypeAdvisor.java +++ b/spring-extension-commons/src/main/java/com/livk/commons/aop/AnnotationAbstractPointcutTypeAdvisor.java @@ -30,7 +30,8 @@ * @see AnnotationPointcutType * @see AnnotationAbstractPointcutAdvisor */ -public abstract class AnnotationAbstractPointcutTypeAdvisor extends AnnotationAbstractPointcutAdvisor { +public abstract class AnnotationAbstractPointcutTypeAdvisor + extends AnnotationAbstractPointcutAdvisor { @NonNull @Override @@ -39,11 +40,13 @@ public Pointcut getPointcut() { } /** - *

用于指定不同的切点类型,默认为{@link AnnotationPointcutType#AUTO}

- * + *

+ * 用于指定不同的切点类型,默认为{@link AnnotationPointcutType#AUTO} + *

* @return the annotation pointcut type */ protected AnnotationPointcutType pointcutType() { return AnnotationPointcutType.AUTO; } + } diff --git a/spring-extension-commons/src/main/java/com/livk/commons/aop/AnnotationAutoPointcut.java b/spring-extension-commons/src/main/java/com/livk/commons/aop/AnnotationAutoPointcut.java index 26296f6b3..9cfc48cc2 100644 --- a/spring-extension-commons/src/main/java/com/livk/commons/aop/AnnotationAutoPointcut.java +++ b/spring-extension-commons/src/main/java/com/livk/commons/aop/AnnotationAutoPointcut.java @@ -31,9 +31,9 @@ interface AnnotationAutoPointcut { /** * 根据注解获取到切点 - * * @param annotationType 注解类信息 * @return 切点 */ Pointcut getPointcut(Class annotationType); + } diff --git a/spring-extension-commons/src/main/java/com/livk/commons/aop/AnnotationClassOrMethodPointcut.java b/spring-extension-commons/src/main/java/com/livk/commons/aop/AnnotationClassOrMethodPointcut.java index 337963198..faf6e455f 100644 --- a/spring-extension-commons/src/main/java/com/livk/commons/aop/AnnotationClassOrMethodPointcut.java +++ b/spring-extension-commons/src/main/java/com/livk/commons/aop/AnnotationClassOrMethodPointcut.java @@ -31,8 +31,13 @@ import java.util.concurrent.atomic.AtomicBoolean; /** - *

类注解或者方法注解的切点

- *

参考 {@see org.springframework.retry.annotation.RetryConfiguration.AnnotationClassOrMethodPointcut}

+ *

+ * 类注解或者方法注解的切点 + *

+ *

+ * 参考 + * {@see org.springframework.retry.annotation.RetryConfiguration.AnnotationClassOrMethodPointcut} + *

* * @author livk */ @@ -44,7 +49,6 @@ public class AnnotationClassOrMethodPointcut extends StaticMethodMatcherPointcut * 构造方法 *

* 用于类或者方法切点 - * * @param annotationType 注解类型 */ public AnnotationClassOrMethodPointcut(Class annotationType) { @@ -76,7 +80,6 @@ private static final class AnnotationClassOrMethodFilter extends AnnotationClass * 构造方法 *

* 用于匹配的ClassFilter - * * @param annotationType 注解类型 */ AnnotationClassOrMethodFilter(Class annotationType) { @@ -97,7 +100,6 @@ private static class AnnotationMethodsResolver { /** * 构造方法 - * * @param annotationType 注解类型 */ public AnnotationMethodsResolver(Class annotationType) { @@ -106,7 +108,6 @@ public AnnotationMethodsResolver(Class annotationType) { /** * 判断类是否包含注解 - * * @param clazz 类信息 * @return boolean */ @@ -125,4 +126,5 @@ public boolean hasAnnotatedMethods(Class clazz) { } } + } diff --git a/spring-extension-commons/src/main/java/com/livk/commons/aop/AnnotationPointcutType.java b/spring-extension-commons/src/main/java/com/livk/commons/aop/AnnotationPointcutType.java index 7bb0eab02..921e5da62 100644 --- a/spring-extension-commons/src/main/java/com/livk/commons/aop/AnnotationPointcutType.java +++ b/spring-extension-commons/src/main/java/com/livk/commons/aop/AnnotationPointcutType.java @@ -28,8 +28,12 @@ import java.util.HashSet; /** - *

{@link AnnotationAutoPointcut} 的泛型实现

- *

用于便捷的获取各种切点

+ *

+ * {@link AnnotationAutoPointcut} 的泛型实现 + *

+ *

+ * 用于便捷的获取各种切点 + *

* * @author livk * @see AnnotationAutoPointcut @@ -47,7 +51,6 @@ public enum AnnotationPointcutType implements AnnotationAutoPointcut { */ METHOD(AnnotationMatchingPointcut::forMethodAnnotation), - /** * 用于指定类级别或方法级别的切点 */ @@ -63,20 +66,24 @@ public enum AnnotationPointcutType implements AnnotationAutoPointcut { HashSet elementTypeHashSet = Sets.newHashSet(target.value()); if (elementTypeHashSet.contains(ElementType.TYPE) && elementTypeHashSet.contains(ElementType.METHOD)) { return TYPE_OR_METHOD.annotationAutoPointcut.getPointcut(annotationType); - } else if (elementTypeHashSet.contains(ElementType.TYPE)) { + } + else if (elementTypeHashSet.contains(ElementType.TYPE)) { return TYPE.annotationAutoPointcut.getPointcut(annotationType); - } else if (elementTypeHashSet.contains(ElementType.METHOD)) { + } + else if (elementTypeHashSet.contains(ElementType.METHOD)) { return METHOD.annotationAutoPointcut.getPointcut(annotationType); - } else { - throw new IllegalArgumentException("annotation:" + annotationType + " Missing " + Target.class + " TYPE or METHOD information"); + } + else { + throw new IllegalArgumentException( + "annotation:" + annotationType + " Missing " + Target.class + " TYPE or METHOD information"); } }); private final AnnotationAutoPointcut annotationAutoPointcut; - @Override public Pointcut getPointcut(Class annotationType) { return annotationAutoPointcut.getPointcut(annotationType); } + } diff --git a/spring-extension-commons/src/main/java/com/livk/commons/beans/BeanLambdaDescriptor.java b/spring-extension-commons/src/main/java/com/livk/commons/beans/BeanLambdaDescriptor.java index 656d67707..8aebacae6 100644 --- a/spring-extension-commons/src/main/java/com/livk/commons/beans/BeanLambdaDescriptor.java +++ b/spring-extension-commons/src/main/java/com/livk/commons/beans/BeanLambdaDescriptor.java @@ -57,8 +57,7 @@ private BeanLambdaDescriptor(Class type, String methodName) { * 静态构建根据{@link BeanLambdaDescriptor} *

* 使用缓存避免无效加载 - * - * @param 相关泛型 + * @param 相关泛型 * @param function BeanLambdaFunc表达式 * @return BeanLambdaDescriptor */ @@ -69,7 +68,8 @@ public static BeanLambdaDescriptor create(BeanLambdaFunc function) { SerializedLambda serializedLambda = (SerializedLambda) writeReplace.invoke(function); String className = ClassUtils.convertResourcePathToClassName(serializedLambda.getImplClass()); Class type = ClassUtils.resolveClassName(className); - return cache.computeIfAbsent(Pair.of(type, serializedLambda.getImplMethodName()), pair -> new BeanLambdaDescriptor(pair.key(), pair.value())); + return cache.computeIfAbsent(Pair.of(type, serializedLambda.getImplMethodName()), + pair -> new BeanLambdaDescriptor(pair.key(), pair.value())); } private void initField() { @@ -98,4 +98,5 @@ public Field getField() { public Method getMethod() { return ReflectionUtils.findMethod(type, methodName); } + } diff --git a/spring-extension-commons/src/main/java/com/livk/commons/beans/BeanLambdaFunc.java b/spring-extension-commons/src/main/java/com/livk/commons/beans/BeanLambdaFunc.java index 8045eefe7..56a688347 100644 --- a/spring-extension-commons/src/main/java/com/livk/commons/beans/BeanLambdaFunc.java +++ b/spring-extension-commons/src/main/java/com/livk/commons/beans/BeanLambdaFunc.java @@ -35,8 +35,7 @@ public interface BeanLambdaFunc extends Function, Serializable { /** * 获取方法名称 - * - * @param 相关泛型 + * @param 相关泛型 * @param function BeanLambdaFunc表达式 * @return methodName */ @@ -46,8 +45,7 @@ static String methodName(BeanLambdaFunc function) { /** * 获取方法 - * - * @param 相关泛型 + * @param 相关泛型 * @param function BeanLambdaFunc表达式 * @return method */ @@ -57,8 +55,7 @@ static Method method(BeanLambdaFunc function) { /** * 获取字段名称 - * - * @param 相关泛型 + * @param 相关泛型 * @param function BeanLambdaFunc表达式 * @return fieldName */ @@ -69,8 +66,7 @@ static String fieldName(BeanLambdaFunc function) { /** * 获取字段 - * - * @param 相关泛型 + * @param 相关泛型 * @param function BeanLambdaFunc表达式 * @return field */ @@ -78,4 +74,5 @@ static String fieldName(BeanLambdaFunc function) { static Field field(BeanLambdaFunc function) { return BeanLambdaDescriptor.create(function).getField(); } + } diff --git a/spring-extension-commons/src/main/java/com/livk/commons/beans/GenericWrapper.java b/spring-extension-commons/src/main/java/com/livk/commons/beans/GenericWrapper.java index ba6fb4e41..d682b4867 100644 --- a/spring-extension-commons/src/main/java/com/livk/commons/beans/GenericWrapper.java +++ b/spring-extension-commons/src/main/java/com/livk/commons/beans/GenericWrapper.java @@ -29,8 +29,7 @@ public interface GenericWrapper extends Wrapper { /** * 构建一个GenericWrapper包装器 - * - * @param 相关泛型 + * @param 相关泛型 * @param delegate the value * @return the delegating wrapper */ @@ -46,8 +45,8 @@ default boolean isWrapperFor(Class type) { /** * 解析成泛型相关实例 - * * @return 带有泛型的相关实例 */ T unwrap(); + } diff --git a/spring-extension-commons/src/main/java/com/livk/commons/beans/Wrapper.java b/spring-extension-commons/src/main/java/com/livk/commons/beans/Wrapper.java index dd495396b..dc003bee8 100644 --- a/spring-extension-commons/src/main/java/com/livk/commons/beans/Wrapper.java +++ b/spring-extension-commons/src/main/java/com/livk/commons/beans/Wrapper.java @@ -26,8 +26,7 @@ public interface Wrapper { * 根据类型获取相关实例 *

* 如果无法进行转换则抛出异常{@link ClassCastException} - * - * @param 相关泛型 + * @param 相关泛型 * @param type 类信息 * @return 相关实例 */ @@ -40,7 +39,6 @@ default T unwrap(Class type) { /** * 判断是否可以进行转换 - * * @param type 类信息 * @return bool */ @@ -48,8 +46,8 @@ default T unwrap(Class type) { /** * 解析获取相关实例 - * * @return 相关实例 */ Object unwrap(); + } diff --git a/spring-extension-commons/src/main/java/com/livk/commons/cglib/AbstractClassGenerator.java b/spring-extension-commons/src/main/java/com/livk/commons/cglib/AbstractClassGenerator.java index acff78677..9225dad00 100644 --- a/spring-extension-commons/src/main/java/com/livk/commons/cglib/AbstractClassGenerator.java +++ b/spring-extension-commons/src/main/java/com/livk/commons/cglib/AbstractClassGenerator.java @@ -38,14 +38,21 @@ abstract class AbstractClassGenerator implements ClassGenerator { private static final ThreadLocal> CURRENT = new ThreadLocal<>(); - private static final boolean DEFAULT_USE_CACHE = - Boolean.parseBoolean(System.getProperty("cglib.useCache", "true")); - // See https://github.com/oracle/graal/blob/master/sdk/src/org.graalvm.nativeimage/src/org/graalvm/nativeimage/ImageInfo.java + + private static final boolean DEFAULT_USE_CACHE = Boolean.parseBoolean(System.getProperty("cglib.useCache", "true")); + + // See + // https://github.com/oracle/graal/blob/master/sdk/src/org.graalvm.nativeimage/src/org/graalvm/nativeimage/ImageInfo.java private static final boolean imageCode = (System.getProperty("org.graalvm.nativeimage.imagecode") != null); + private static volatile Map CACHE = new WeakHashMap<>(); + private final Source source; + private GeneratorStrategy strategy = DefaultGeneratorStrategy.INSTANCE; + private NamingPolicy namingPolicy = DefaultNamingPolicy.INSTANCE; + private ClassLoader classLoader; private Class contextClass; @@ -60,10 +67,8 @@ abstract class AbstractClassGenerator implements ClassGenerator { private boolean attemptLoad; - /** * Instantiates a new Abstract class generator. - * * @param source the source */ protected AbstractClassGenerator(Source source) { @@ -71,9 +76,8 @@ protected AbstractClassGenerator(Source source) { } /** - * Used internally by CGLIB. Returns the AbstractClassGenerator - * that is being used to generate a class in the current thread. - * + * Used internally by CGLIB. Returns the AbstractClassGenerator that is + * being used to generate a class in the current thread. * @return the current */ public static AbstractClassGenerator getCurrent() { @@ -82,7 +86,6 @@ public static AbstractClassGenerator getCurrent() { /** * Wrap cached class t. - * * @param klass the klass * @return the t */ @@ -93,7 +96,6 @@ protected T wrapCachedClass(Class klass) { /** * Unwrap cached value object. - * * @param cached the cached * @return the object */ @@ -103,7 +105,6 @@ protected Object unwrapCachedValue(Object cached) { /** * Sets name prefix. - * * @param namePrefix the name prefix */ protected void setNamePrefix(String namePrefix) { @@ -112,7 +113,6 @@ protected void setNamePrefix(String namePrefix) { /** * Gets class name. - * * @return the class name */ final protected String getClassName() { @@ -129,17 +129,15 @@ private String generateClassName(Predicate nameTestPredicate) { /** * Sets context class. - * * @param contextClass the context class */ -// SPRING PATCH BEGIN + // SPRING PATCH BEGIN public void setContextClass(Class contextClass) { this.contextClass = contextClass; } /** * Gets naming policy. - * * @return the naming policy * @see #setNamingPolicy #setNamingPolicy */ @@ -149,7 +147,6 @@ public NamingPolicy getNamingPolicy() { /** * Override the default naming policy. - * * @param namingPolicy the custom policy, or null to use the default * @see DefaultNamingPolicy */ @@ -163,7 +160,6 @@ public void setNamingPolicy(NamingPolicy namingPolicy) { /** * Gets use cache. - * * @return the use cache * @see #setUseCache #setUseCache */ @@ -172,9 +168,8 @@ public boolean getUseCache() { } /** - * Whether use and update the static cache of generated classes - * for a class with the same properties. Default is true. - * + * Whether use and update the static cache of generated classes for a class with the + * same properties. Default is true. * @param useCache the use cache */ public void setUseCache(boolean useCache) { @@ -183,7 +178,6 @@ public void setUseCache(boolean useCache) { /** * Gets attempt load. - * * @return the attempt load */ public boolean getAttemptLoad() { @@ -192,9 +186,8 @@ public boolean getAttemptLoad() { /** * If set, CGLIB will attempt to load classes from the specified - * ClassLoader before generating them. Because generated - * class names are not guaranteed to be unique, the default is false. - * + * ClassLoader before generating them. Because generated class names are + * not guaranteed to be unique, the default is false. * @param attemptLoad the attempt load */ public void setAttemptLoad(boolean attemptLoad) { @@ -203,7 +196,6 @@ public void setAttemptLoad(boolean attemptLoad) { /** * Gets strategy. - * * @return the strategy * @see #setStrategy #setStrategy */ @@ -212,9 +204,8 @@ public GeneratorStrategy getStrategy() { } /** - * Set the strategy to use to create the bytecode from this generator. - * By default an instance of {@link DefaultGeneratorStrategy} is used. - * + * Set the strategy to use to create the bytecode from this generator. By default an + * instance of {@link DefaultGeneratorStrategy} is used. * @param strategy the strategy */ public void setStrategy(GeneratorStrategy strategy) { @@ -226,7 +217,6 @@ public void setStrategy(GeneratorStrategy strategy) { /** * Gets class loader. - * * @return the class loader */ public ClassLoader getClassLoader() { @@ -247,14 +237,15 @@ public ClassLoader getClassLoader() { } /** - * Set the ClassLoader in which the class will be generated. - * Concrete subclasses of AbstractClassGenerator (such as Enhancer) + * Set the ClassLoader in which the class will be generated. Concrete + * subclasses of AbstractClassGenerator (such as Enhancer) * will try to choose an appropriate default if this is unset. *

- * Classes are cached per-ClassLoader using a WeakHashMap, to allow - * the generated classes to be removed when the associated loader is garbage collected. - * - * @param classLoader the loader to generate the new class with, or null to use the default + * Classes are cached per-ClassLoader using a WeakHashMap, + * to allow the generated classes to be removed when the associated loader is garbage + * collected. + * @param classLoader the loader to generate the new class with, or null to use the + * default */ public void setClassLoader(ClassLoader classLoader) { this.classLoader = classLoader; @@ -262,7 +253,6 @@ public void setClassLoader(ClassLoader classLoader) { /** * Gets default class loader. - * * @return the default class loader */ abstract protected ClassLoader getDefaultClassLoader(); @@ -270,10 +260,9 @@ public void setClassLoader(ClassLoader classLoader) { /** * Returns the protection domain to use when defining the class. *

- * Default implementation returns null for using a default protection domain. Sub-classes may - * override to use a more specific protection domain. + * Default implementation returns null for using a default protection + * domain. Sub-classes may override to use a more specific protection domain. *

- * * @return the protection domain (null for using a default) */ protected ProtectionDomain getProtectionDomain() { @@ -282,7 +271,6 @@ protected ProtectionDomain getProtectionDomain() { /** * Create object. - * * @param key the key * @return the object */ @@ -309,16 +297,17 @@ protected Object create(Object key) { return firstInstance(clazz); } return nextInstance(obj); - } catch (RuntimeException | Error ex) { + } + catch (RuntimeException | Error ex) { throw ex; - } catch (Exception ex) { + } + catch (Exception ex) { throw new CodeGenerationException(ex); } } /** * Generate class. - * * @param data the data * @return the class */ @@ -329,9 +318,9 @@ protected Class generate(ClassLoaderData data) { try { ClassLoader classLoader = data.getClassLoader(); if (classLoader == null) { - throw new IllegalStateException("ClassLoader is null while trying to define class " + - getClassName() + ". It seems that the loader has been expired from a weak reference somehow. " + - "Please file an issue at cglib's issue tracker."); + throw new IllegalStateException("ClassLoader is null while trying to define class " + getClassName() + + ". It seems that the loader has been expired from a weak reference somehow. " + + "Please file an issue at cglib's issue tracker."); } synchronized (classLoader) { String name = generateClassName(data.getUniqueNamePredicate()); @@ -346,14 +335,15 @@ protected Class generate(ClassLoaderData data) { } // SPRING PATCH END return gen; - } catch (ClassNotFoundException e) { + } + catch (ClassNotFoundException e) { // ignore } } // SPRING PATCH BEGIN if (imageCode) { - throw new UnsupportedOperationException("CGLIB runtime enhancement not supported on native image. " + - "Make sure to include a pre-generated class on the classpath instead: " + getClassName()); + throw new UnsupportedOperationException("CGLIB runtime enhancement not supported on native image. " + + "Make sure to include a pre-generated class on the classpath instead: " + getClassName()); } // SPRING PATCH END byte[] b = strategy.generate(this); @@ -365,18 +355,20 @@ protected Class generate(ClassLoaderData data) { // SPRING PATCH END } return gen; - } catch (RuntimeException | Error ex) { + } + catch (RuntimeException | Error ex) { throw ex; - } catch (Exception ex) { + } + catch (Exception ex) { throw new CodeGenerationException(ex); - } finally { + } + finally { CURRENT.set(save); } } /** * First instance object. - * * @param type the type * @return the object * @throws Exception the exception @@ -385,7 +377,6 @@ protected Class generate(ClassLoaderData data) { /** * Next instance object. - * * @param instance the instance * @return the object * @throws Exception the exception @@ -398,28 +389,38 @@ protected Class generate(ClassLoaderData data) { protected static class ClassLoaderData { private static final Function, Object> GET_KEY = gen -> gen.key; + private final Set reservedClassNames = new HashSet<>(); + /** - * {@link AbstractClassGenerator} here holds "cache key" (e.g. {@link org.springframework.cglib.proxy.Enhancer} - * configuration), and the value is the generated class plus some additional values - * (see {@link #unwrapCachedValue(Object)}. - *

The generated classes can be reused as long as their classloader is reachable.

- *

Note: the only way to access a class is to find it through generatedClasses cache, thus - * the key should not expire as long as the class itself is alive (its classloader is alive).

+ * {@link AbstractClassGenerator} here holds "cache key" (e.g. + * {@link org.springframework.cglib.proxy.Enhancer} configuration), and the value + * is the generated class plus some additional values (see + * {@link #unwrapCachedValue(Object)}. + *

+ * The generated classes can be reused as long as their classloader is reachable. + *

+ *

+ * Note: the only way to access a class is to find it through generatedClasses + * cache, thus the key should not expire as long as the class itself is alive (its + * classloader is alive). + *

*/ private final LoadingCache, Object, Object> generatedClasses; + /** - * Note: ClassLoaderData object is stored as a value of {@code WeakHashMap} thus - * this classLoader reference should be weak otherwise it would make classLoader strongly reachable - * and alive forever. - * Reference queue is not required since the cleanup is handled by {@link WeakHashMap}. + * Note: ClassLoaderData object is stored as a value of + * {@code WeakHashMap} thus this classLoader reference should be + * weak otherwise it would make classLoader strongly reachable and alive forever. + * Reference queue is not required since the cleanup is handled by + * {@link WeakHashMap}. */ private final WeakReference classLoader; + private final Predicate uniqueNamePredicate = this.reservedClassNames::contains; /** * Instantiates a new Class loader data. - * * @param classLoader the class loader */ public ClassLoaderData(ClassLoader classLoader) { @@ -436,7 +437,6 @@ public ClassLoaderData(ClassLoader classLoader) { /** * Gets class loader. - * * @return the class loader */ public ClassLoader getClassLoader() { @@ -445,7 +445,6 @@ public ClassLoader getClassLoader() { /** * Reserve name. - * * @param name the name */ public void reserveName(String name) { @@ -454,7 +453,6 @@ public void reserveName(String name) { /** * Gets unique name predicate. - * * @return the unique name predicate */ public Predicate getUniqueNamePredicate() { @@ -463,19 +461,20 @@ public Predicate getUniqueNamePredicate() { /** * Get object. - * - * @param gen the gen + * @param gen the gen * @param useCache the use cache * @return the object */ public Object get(AbstractClassGenerator gen, boolean useCache) { if (!useCache) { return gen.generate(ClassLoaderData.this); - } else { + } + else { Object cachedValue = generatedClasses.get(gen); return gen.unwrapCachedValue(cachedValue); } } + } /** @@ -490,12 +489,12 @@ protected static class Source { /** * Instantiates a new Source. - * * @param name the name */ public Source(String name) { this.name = name; } + } } diff --git a/spring-extension-commons/src/main/java/com/livk/commons/cglib/BeanMap.java b/spring-extension-commons/src/main/java/com/livk/commons/cglib/BeanMap.java index dae6060f8..b343e2dcb 100644 --- a/spring-extension-commons/src/main/java/com/livk/commons/cglib/BeanMap.java +++ b/spring-extension-commons/src/main/java/com/livk/commons/cglib/BeanMap.java @@ -25,29 +25,37 @@ import java.util.*; /** - *

The type Bean map.

- *

根据{@link org.springframework.cglib.beans.BeanMap} 调整

- *

依赖于spring-core

+ *

+ * The type Bean map. + *

+ *

+ * 根据{@link org.springframework.cglib.beans.BeanMap} 调整 + *

+ *

+ * 依赖于spring-core + *

* * @author livk * @see org.springframework.cglib.beans.BeanMap */ public abstract class BeanMap implements Map { + /** - * Limit the properties reflected in the key set of the map - * to readable properties. + * Limit the properties reflected in the key set of the map to readable properties. * - * @see org.springframework.cglib.beans.BeanMap.Generator#setRequire org.springframework.cglib.beans.BeanMap.Generator#setRequire + * @see org.springframework.cglib.beans.BeanMap.Generator#setRequire + * org.springframework.cglib.beans.BeanMap.Generator#setRequire */ public static final int REQUIRE_GETTER = 1; /** - * Limit the properties reflected in the key set of the map - * to writable properties. + * Limit the properties reflected in the key set of the map to writable properties. * - * @see org.springframework.cglib.beans.BeanMap.Generator#setRequire org.springframework.cglib.beans.BeanMap.Generator#setRequire + * @see org.springframework.cglib.beans.BeanMap.Generator#setRequire + * org.springframework.cglib.beans.BeanMap.Generator#setRequire */ public static final int REQUIRE_SETTER = 2; + /** * The Bean. */ @@ -61,7 +69,6 @@ protected BeanMap() { /** * Instantiates a new Bean map. - * * @param bean the bean */ protected BeanMap(Object bean) { @@ -69,11 +76,10 @@ protected BeanMap(Object bean) { } /** - * Helper method to create a new BeanMap. For finer - * control over the generated instance, use a new instance of - * BeanMap.Generator instead of this static method. - * - * @param the type parameter + * Helper method to create a new BeanMap. For finer control over the + * generated instance, use a new instance of BeanMap.Generator instead of + * this static method. + * @param the type parameter * @param bean the JavaBean underlying the map * @return a new BeanMap instance */ @@ -84,9 +90,8 @@ public static BeanMap create(T bean) { } /** - * Create a new BeanMap instance using the specified bean. - * This is faster than using the {@link #create} static method. - * + * Create a new BeanMap instance using the specified bean. This is faster + * than using the {@link #create} static method. * @param bean the JavaBean underlying the map * @return a new BeanMap instance */ @@ -94,7 +99,6 @@ public static BeanMap create(T bean) { /** * Get the type of a property. - * * @param name the name of the JavaBean property * @return the type of the property, or null if the property does not exist */ @@ -111,23 +115,22 @@ public Object put(String key, Object value) { } /** - * Get the property of a bean. This allows a BeanMap - * to be used statically for multiple beans--the bean instance tied to the - * map is ignored and the bean passed to this method is used instead. - * - * @param bean the bean to query; must be compatible with the type of this BeanMap - * @param key must be a String + * Get the property of a bean. This allows a BeanMap to be used + * statically for multiple beans--the bean instance tied to the map is ignored and the + * bean passed to this method is used instead. + * @param bean the bean to query; must be compatible with the type of this + * BeanMap + * @param key must be a String * @return the current value, or null if there is no matching property */ public abstract Object get(Object bean, Object key); /** - * Set the property of a bean. This allows a BeanMap - * to be used statically for multiple beans--the bean instance tied to the - * map is ignored and the bean passed to this method is used instead. - * - * @param bean the bean - * @param key must be a String + * Set the property of a bean. This allows a BeanMap to be used + * statically for multiple beans--the bean instance tied to the map is ignored and the + * bean passed to this method is used instead. + * @param bean the bean + * @param key must be a String * @param value the value * @return the old value, if there was one, or null */ @@ -135,7 +138,6 @@ public Object put(String key, Object value) { /** * Return the bean currently in use by this map. - * * @return the current JavaBean * @see #setBean #setBean */ @@ -145,7 +147,6 @@ public Object getBean() { /** * Change the underlying bean this map should use. - * * @param bean the new JavaBean * @see #getBean #getBean */ @@ -222,8 +223,7 @@ public int hashCode() { int code = 0; for (Object key : keySet()) { Object value = get(key); - code += ((key == null) ? 0 : key.hashCode()) ^ - ((value == null) ? 0 : value.hashCode()); + code += ((key == null) ? 0 : key.hashCode()) ^ ((value == null) ? 0 : value.hashCode()); } return code; } @@ -255,7 +255,7 @@ public Collection values() { public String toString() { StringBuilder sb = new StringBuilder(); sb.append('{'); - for (Iterator it = keySet().iterator(); it.hasNext(); ) { + for (Iterator it = keySet().iterator(); it.hasNext();) { Object key = it.next(); sb.append(key); sb.append('='); @@ -274,13 +274,17 @@ public String toString() { * @param the type parameter */ public static class Generator extends AbstractClassGenerator { + private static final Source SOURCE = new Source(BeanMap.class.getName()); @SuppressWarnings("unchecked") - private final BeanMapKey KEY_FACTORY = - (BeanMapKey) KeyFactory.create(BeanMapKey.class, KeyFactory.CLASS_BY_NAME); + private final BeanMapKey KEY_FACTORY = (BeanMapKey) KeyFactory.create(BeanMapKey.class, + KeyFactory.CLASS_BY_NAME); + private Object bean; + private Class beanClass; + private int require; /** @@ -291,11 +295,10 @@ public Generator() { } /** - * Set the bean that the generated map should reflect. The bean may be swapped - * out for another bean of the same type using {@link #setBean}. - * Calling this method overrides any value previously set using {@link #setBeanClass}. - * You must call either this method or {@link #setBeanClass} before {@link #create}. - * + * Set the bean that the generated map should reflect. The bean may be swapped out + * for another bean of the same type using {@link #setBean}. Calling this method + * overrides any value previously set using {@link #setBeanClass}. You must call + * either this method or {@link #setBeanClass} before {@link #create}. * @param bean the initial bean */ @SuppressWarnings("unchecked") @@ -310,9 +313,8 @@ public void setBean(Object bean) { } /** - * Set the class of the bean that the generated map should support. - * You must call either this method or {@link #setBeanClass} before {@link #create}. - * + * Set the class of the bean that the generated map should support. You must call + * either this method or {@link #setBeanClass} before {@link #create}. * @param beanClass the class of the bean */ public void setBeanClass(Class beanClass) { @@ -321,8 +323,8 @@ public void setBeanClass(Class beanClass) { /** * Limit the properties reflected by the generated map. - * - * @param require any combination of {@link #REQUIRE_GETTER} and {@link #REQUIRE_SETTER}; default is zero (any property allowed) + * @param require any combination of {@link #REQUIRE_GETTER} and + * {@link #REQUIRE_SETTER}; default is zero (any property allowed) */ public void setRequire(int require) { this.require = require; @@ -339,9 +341,8 @@ protected ProtectionDomain getProtectionDomain() { } /** - * Create a new instance of the BeanMap. An existing - * generated class will be reused if possible. - * + * Create a new instance of the BeanMap. An existing generated class + * will be reused if possible. * @return the bean map */ public BeanMap create() { @@ -373,14 +374,17 @@ protected Object nextInstance(Object instance) { * @param the type parameter */ interface BeanMapKey { + /** * New instance t. - * - * @param type the type + * @param type the type * @param require the require * @return the t */ T newInstance(Class type, int require); + } + } + } diff --git a/spring-extension-commons/src/main/java/com/livk/commons/cglib/BeanMapEmitter.java b/spring-extension-commons/src/main/java/com/livk/commons/cglib/BeanMapEmitter.java index cd905a6ef..d14d2a4a8 100644 --- a/spring-extension-commons/src/main/java/com/livk/commons/cglib/BeanMapEmitter.java +++ b/spring-extension-commons/src/main/java/com/livk/commons/cglib/BeanMapEmitter.java @@ -33,32 +33,32 @@ * @author livk */ class BeanMapEmitter extends ClassEmitter { - private static final Type BEAN_MAP = - TypeUtils.parseType("com.livk.commons.cglib.BeanMap"); - private static final Type FIXED_KEY_SET = - TypeUtils.parseType("org.springframework.cglib.beans.FixedKeySet"); - private static final Signature CSTRUCT_OBJECT = - TypeUtils.parseConstructor("Object"); - private static final Signature CSTRUCT_STRING_ARRAY = - TypeUtils.parseConstructor("String[]"); - private static final Signature BEAN_MAP_GET = - TypeUtils.parseSignature("Object get(Object, Object)"); - private static final Signature BEAN_MAP_PUT = - TypeUtils.parseSignature("Object put(Object, Object, Object)"); - private static final Signature KEY_SET = - TypeUtils.parseSignature("java.util.Set keySet()"); - private static final Signature NEW_INSTANCE = - new Signature("newInstance", BEAN_MAP, new Type[]{Constants.TYPE_OBJECT}); - private static final Signature GET_PROPERTY_TYPE = - TypeUtils.parseSignature("Class getPropertyType(String)"); + + private static final Type BEAN_MAP = TypeUtils.parseType("com.livk.commons.cglib.BeanMap"); + + private static final Type FIXED_KEY_SET = TypeUtils.parseType("org.springframework.cglib.beans.FixedKeySet"); + + private static final Signature CSTRUCT_OBJECT = TypeUtils.parseConstructor("Object"); + + private static final Signature CSTRUCT_STRING_ARRAY = TypeUtils.parseConstructor("String[]"); + + private static final Signature BEAN_MAP_GET = TypeUtils.parseSignature("Object get(Object, Object)"); + + private static final Signature BEAN_MAP_PUT = TypeUtils.parseSignature("Object put(Object, Object, Object)"); + + private static final Signature KEY_SET = TypeUtils.parseSignature("java.util.Set keySet()"); + + private static final Signature NEW_INSTANCE = new Signature("newInstance", BEAN_MAP, + new Type[] { Constants.TYPE_OBJECT }); + + private static final Signature GET_PROPERTY_TYPE = TypeUtils.parseSignature("Class getPropertyType(String)"); /** * Instantiates a new Bean map emitter. - * - * @param v the v + * @param v the v * @param className the class name - * @param type the type - * @param require the require + * @param type the type + * @param require the require */ public BeanMapEmitter(ClassVisitor v, String className, Class type, int require) { super(v); @@ -75,10 +75,10 @@ public BeanMapEmitter(ClassVisitor v, String className, Class type, int requi allProps.putAll(setters); if (require != 0) { - for (Iterator it = allProps.keySet().iterator(); it.hasNext(); ) { + for (Iterator it = allProps.keySet().iterator(); it.hasNext();) { String name = it.next(); - if ((((require & BeanMap.REQUIRE_GETTER) != 0) && !getters.containsKey(name)) || - (((require & BeanMap.REQUIRE_SETTER) != 0) && !setters.containsKey(name))) { + if ((((require & BeanMap.REQUIRE_GETTER) != 0) && !getters.containsKey(name)) + || (((require & BeanMap.REQUIRE_SETTER) != 0) && !setters.containsKey(name))) { it.remove(); getters.remove(name); setters.remove(name); @@ -152,7 +152,8 @@ public void processCase(Object key, Label end) { PropertyDescriptor pd = setters.get((String) key); if (pd.getReadMethod() == null) { e.aconst_null(); - } else { + } + else { MethodInfo read = ReflectUtils.getMethodInfo(pd.getReadMethod()); e.dup(); e.invoke(read); @@ -216,4 +217,5 @@ public void processDefault() { }); e.end_method(); } + } diff --git a/spring-extension-commons/src/main/java/com/livk/commons/expression/AbstractExpressionResolver.java b/spring-extension-commons/src/main/java/com/livk/commons/expression/AbstractExpressionResolver.java index 8e624f32b..193672f6f 100644 --- a/spring-extension-commons/src/main/java/com/livk/commons/expression/AbstractExpressionResolver.java +++ b/spring-extension-commons/src/main/java/com/livk/commons/expression/AbstractExpressionResolver.java @@ -46,7 +46,8 @@ public final T evaluate(String value, Method method, Object[] args, Class } @Override - public final T evaluate(String value, Method method, Object[] args, Map contextMap, Class returnType) { + public final T evaluate(String value, Method method, Object[] args, Map contextMap, + Class returnType) { Map map = contextFactory.merge(method, args, contextMap); return evaluate(value, map, returnType); } @@ -73,10 +74,10 @@ public final String evaluate(String value, Method method, Object[] args, Map T evaluate(String value, Context context, Class returnType) { this.expressionCache.put(value, expression); } return calculate(expression, context, returnType); - } catch (Throwable ex) { + } + catch (Throwable ex) { throw new ExpressionException("Expression parsing failed", ex); } } /** * 对表达式进行数据包装,如果有必要 - * * @param expression 表达式 * @return 包装后的表达式 string */ @@ -73,7 +73,6 @@ protected String wrapIfNecessary(String expression) { /** * 对表达式进行处理生成EXPRESSION - * * @param value 表达式 * @return EXPRESSION expression * @throws Throwable the throwable @@ -82,13 +81,13 @@ protected String wrapIfNecessary(String expression) { /** * 表达式计算 - * - * @param 泛型 + * @param 泛型 * @param expression 表达式 - * @param context 环境上下文 + * @param context 环境上下文 * @param returnType 返回类型 * @return T * @throws Throwable the throwable */ protected abstract T calculate(EXPRESSION expression, Context context, Class returnType) throws Throwable; + } diff --git a/spring-extension-commons/src/main/java/com/livk/commons/expression/Context.java b/spring-extension-commons/src/main/java/com/livk/commons/expression/Context.java index cf3bb8ebf..cd6d82ca1 100644 --- a/spring-extension-commons/src/main/java/com/livk/commons/expression/Context.java +++ b/spring-extension-commons/src/main/java/com/livk/commons/expression/Context.java @@ -43,14 +43,12 @@ public Context() { /** * Instantiates a new Context. - * * @param map the map */ public Context(Map map) { variables = Maps.newHashMap(map); } - @Override public int size() { return variables.size(); @@ -84,9 +82,8 @@ public Object put(String key, Object value) { /** * Put object. - * - * @param key the key - * @param value the value + * @param key the key + * @param value the value * @param override the override * @return the object */ @@ -111,14 +108,14 @@ public void putAll(@NonNull Map m) { /** * Put all. - * - * @param m the m + * @param m the m * @param override the override */ public void putAll(Map m, boolean override) { if (override) { variables.putAll(m); - } else { + } + else { for (Entry entry : m.entrySet()) { if (!variables.containsKey(entry.getKey())) { variables.put(entry.getKey(), entry.getValue()); @@ -149,4 +146,5 @@ public Collection values() { public Set> entrySet() { return variables.entrySet(); } + } diff --git a/spring-extension-commons/src/main/java/com/livk/commons/expression/ContextFactory.java b/spring-extension-commons/src/main/java/com/livk/commons/expression/ContextFactory.java index 1bf1e6506..5bb9c07c9 100644 --- a/spring-extension-commons/src/main/java/com/livk/commons/expression/ContextFactory.java +++ b/spring-extension-commons/src/main/java/com/livk/commons/expression/ContextFactory.java @@ -32,18 +32,16 @@ public interface ContextFactory { /** * 根据方法与参数创建上下文 - * * @param method the method - * @param args the args + * @param args the args * @return the context */ Context create(Method method, Object[] args); /** * 合并上下文 - * - * @param method the method - * @param args the args + * @param method the method + * @param args the args * @param expandMap the expand map * @return the map */ @@ -52,4 +50,5 @@ default Context merge(Method method, Object[] args, Map expandMap) { context.putAll(expandMap, false); return context; } + } diff --git a/spring-extension-commons/src/main/java/com/livk/commons/expression/ConverterExpressionResolver.java b/spring-extension-commons/src/main/java/com/livk/commons/expression/ConverterExpressionResolver.java index 7dc2a0ac8..ee9f5998c 100644 --- a/spring-extension-commons/src/main/java/com/livk/commons/expression/ConverterExpressionResolver.java +++ b/spring-extension-commons/src/main/java/com/livk/commons/expression/ConverterExpressionResolver.java @@ -40,7 +40,6 @@ protected final T calculate(E expression, Context context, Class returnTy /** * 从Context装换成框架的上下文 - * * @param context context * @return the c */ @@ -48,12 +47,12 @@ protected final T calculate(E expression, Context context, Class returnTy /** * 对表达式进行计算 - * - * @param 泛型 + * @param 泛型 * @param expression 表达式 - * @param context 上下文 + * @param context 上下文 * @param returnType 返回类型 * @return 计算结果相关实例 */ protected abstract T calculate(E expression, C context, Class returnType); + } diff --git a/spring-extension-commons/src/main/java/com/livk/commons/expression/DefaultContextFactory.java b/spring-extension-commons/src/main/java/com/livk/commons/expression/DefaultContextFactory.java index 26b9a5a20..f0356c237 100644 --- a/spring-extension-commons/src/main/java/com/livk/commons/expression/DefaultContextFactory.java +++ b/spring-extension-commons/src/main/java/com/livk/commons/expression/DefaultContextFactory.java @@ -54,4 +54,5 @@ public Context create(Method method, Object[] args) { } return new Context(map); } + } diff --git a/spring-extension-commons/src/main/java/com/livk/commons/expression/ExpressionResolver.java b/spring-extension-commons/src/main/java/com/livk/commons/expression/ExpressionResolver.java index c5ce8ecc6..e6a58e624 100644 --- a/spring-extension-commons/src/main/java/com/livk/commons/expression/ExpressionResolver.java +++ b/spring-extension-commons/src/main/java/com/livk/commons/expression/ExpressionResolver.java @@ -30,10 +30,9 @@ public interface ExpressionResolver { /** * 根据context信息将表达式解析,并转成相应的类型 - * - * @param 泛型 - * @param value 表达式 - * @param context 解析上下文环境数据 + * @param 泛型 + * @param value 表达式 + * @param context 解析上下文环境数据 * @param returnType 返回类型 * @return T */ @@ -41,9 +40,8 @@ public interface ExpressionResolver { /** * 根据Map环境信息将表达式解析,并转成相应的类型 - * - * @param 泛型 - * @param value 表达式 + * @param 泛型 + * @param value 表达式 * @param contextMap 解析上下文环境数据 * @param returnType 返回类型 * @return T @@ -52,11 +50,10 @@ public interface ExpressionResolver { /** * 根据Method将表达式解析,并转成相对应的类型 - * - * @param 泛型 - * @param value 表达式 - * @param method method - * @param args args + * @param 泛型 + * @param value 表达式 + * @param method method + * @param args args * @param returnType 返回类型 * @return T */ @@ -64,11 +61,10 @@ public interface ExpressionResolver { /** * 根据Method和Map环境信息将表达式解析,并转成相对应的类型 - * - * @param 泛型 - * @param value 表达式 - * @param method method - * @param args args + * @param 泛型 + * @param value 表达式 + * @param method method + * @param args args * @param contextMap 解析上下文环境数据 * @param returnType 返回类型 * @return T @@ -77,10 +73,9 @@ public interface ExpressionResolver { /** * 根据Method将表达式解析,并转成String - * - * @param value 表达式 + * @param value 表达式 * @param method method - * @param args args + * @param args args * @return string */ default String evaluate(String value, Method method, Object[] args) { @@ -89,8 +84,7 @@ default String evaluate(String value, Method method, Object[] args) { /** * 根据context信息将表达式解析,并转成String - * - * @param value 表达式 + * @param value 表达式 * @param context 解析上下文环境数据 * @return string */ @@ -100,8 +94,7 @@ default String evaluate(String value, Context context) { /** * 根据Map环境信息将表达式解析,并转成String - * - * @param value 表达式 + * @param value 表达式 * @param contextMap 解析上下文环境数据 * @return string */ @@ -111,14 +104,14 @@ default String evaluate(String value, Map contextMap) { /** * 根据Method和Map环境信息将表达式解析,并转成String - * - * @param value 表达式 - * @param method method - * @param args args + * @param value 表达式 + * @param method method + * @param args args * @param contextMap 解析上下文环境数据 * @return string */ default String evaluate(String value, Method method, Object[] args, Map contextMap) { return evaluate(value, method, args, contextMap, String.class); } + } diff --git a/spring-extension-commons/src/main/java/com/livk/commons/expression/aviator/AviatorExpressionResolver.java b/spring-extension-commons/src/main/java/com/livk/commons/expression/aviator/AviatorExpressionResolver.java index 0a023b2c6..aea7a807f 100644 --- a/spring-extension-commons/src/main/java/com/livk/commons/expression/aviator/AviatorExpressionResolver.java +++ b/spring-extension-commons/src/main/java/com/livk/commons/expression/aviator/AviatorExpressionResolver.java @@ -39,4 +39,5 @@ protected Expression compile(String value) { protected T calculate(Expression expression, Context context, Class returnType) { return returnType.cast(expression.execute(context)); } + } diff --git a/spring-extension-commons/src/main/java/com/livk/commons/expression/aviator/SpringContextFunctionLoader.java b/spring-extension-commons/src/main/java/com/livk/commons/expression/aviator/SpringContextFunctionLoader.java index c144bf884..506f8ac52 100644 --- a/spring-extension-commons/src/main/java/com/livk/commons/expression/aviator/SpringContextFunctionLoader.java +++ b/spring-extension-commons/src/main/java/com/livk/commons/expression/aviator/SpringContextFunctionLoader.java @@ -43,7 +43,8 @@ public class SpringContextFunctionLoader implements FunctionLoader, Initializing public AviatorFunction onFunctionNotFound(String name) { try { return this.applicationContext.getBean(name, AviatorFunction.class); - } catch (NoSuchBeanDefinitionException e) { + } + catch (NoSuchBeanDefinitionException e) { return null; } } @@ -57,4 +58,5 @@ public void afterPropertiesSet() { public void destroy() { AviatorEvaluator.removeFunctionLoader(this); } + } diff --git a/spring-extension-commons/src/main/java/com/livk/commons/expression/freemarker/FreeMarkerExpressionResolver.java b/spring-extension-commons/src/main/java/com/livk/commons/expression/freemarker/FreeMarkerExpressionResolver.java index 609bb12f7..eb26cd46a 100644 --- a/spring-extension-commons/src/main/java/com/livk/commons/expression/freemarker/FreeMarkerExpressionResolver.java +++ b/spring-extension-commons/src/main/java/com/livk/commons/expression/freemarker/FreeMarkerExpressionResolver.java @@ -35,7 +35,8 @@ @RequiredArgsConstructor public class FreeMarkerExpressionResolver extends CacheExpressionResolver