From 2380c166216d0f5e702b779b04e41b4dfc24bd6a Mon Sep 17 00:00:00 2001 From: metaxiii <16118999+metaXIII@users.noreply.github.com> Date: Fri, 24 Apr 2026 16:23:44 +0200 Subject: [PATCH] tech: add spotless integration --- .../src/main/java/com/metaxiii/fr/Main.java | 19 ++- .../test/java/com/metaxiii/fr/MainTest.java | 91 +++++----- .../test/java/com/metaxiii/fr/AppTest.java | 6 +- .../test/java/com/metaxiii/fr/AppTest.java | 7 +- .../test/java/com/metaxiii/fr/AppTest.java | 35 ++-- .../java/com/metaxiii/fr/GuavaMapsTest.java | 38 +++-- .../com/metaxiii/fr/GuavaCharMatcherTest.java | 17 +- .../fr/conversion/JsonToJavaObject.java | 2 +- .../configuration/CustomCarDeserializer.java | 3 +- .../configuration/CustomCarSerializer.java | 5 +- .../java/com/metaxiii/fr/model/Request.java | 3 +- .../fr/conversion/HandlingDateFormatTest.java | 12 +- .../conversion/JSONtoJacksonJsonNodeTest.java | 9 +- .../JavaListFromJSONArrayStringTest.java | 24 +-- .../conversion/JavaMapFromJSONStringTest.java | 11 +- .../fr/conversion/JavaObjectToJsonTest.java | 9 +- .../fr/conversion/JsonToJavaObjectTest.java | 35 ++-- .../SerializationDeserializationTest.java | 53 +++--- .../CustomCarDeserializerTest.java | 26 +-- .../CustomCarSerializerTest.java | 16 +- .../fr/enums/DistanceAsJSONCreator.java | 4 +- .../fr/enums/DistanceAsJsonValue.java | 3 +- .../config/DistanceDeserializerConfig.java | 4 +- .../config/DistanceSerializerConfig.java | 5 +- .../com/metaxiii/fr/enums/DistanceTest.java | 33 ++-- .../fr/actuator/ActuatorApplicationTests.java | 13 +- .../test/java/com/metaxiii/fr/AppTest.java | 5 +- .../test/java/com/metaxiii/fr/AppTest.java | 38 ++--- .../test/java/com/metaxiii/fr/AppTest.java | 6 +- .../FileController.java | 3 +- ...ipartBoundaryWasFoundApplicationTests.java | 3 +- .../FileControllerTest.java | 48 +++--- .../src/main/java/com/metaxiii/fr/App.java | 5 +- .../test/java/com/metaxiii/fr/AppTest.java | 20 +-- .../fr/DateTimeAndTimestampConverterTest.java | 18 +- .../src/main/java/com/metaxiii/fr/App.java | 5 +- .../test/java/com/metaxiii/fr/AppTest.java | 3 +- .../src/main/java/com/metaxiii/fr/App.java | 8 +- .../test/java/com/metaxiii/fr/AppTest.java | 23 ++- .../controller/PostController.java | 12 +- .../model/User.java | 3 +- .../service/impl/PostServiceImpl.java | 3 +- ...yDtoConversionRestApiApplicationTests.java | 3 +- .../controller/PostControllerTest.java | 20 +-- .../service/impl/PostServiceImplTest.java | 12 +- .../controller/ApiExceptionHandler.java | 5 +- .../controller/FooController.java | 2 +- .../controller/ApiExceptionHandlerTest.java | 16 +- .../controller/FooControllerTest.java | 3 +- .../test/java/com/metaxiii/fr/AppTest.java | 15 +- .../metaxiii/fr/GuavaSplitAndJoinTest.java | 18 +- .../main/java/com/metaxiii/fr/GuavaCache.java | 13 +- .../java/com/metaxiii/fr/GuavaCacheTest.java | 59 ++++--- .../test/java/com/metaxiii/fr/AppTest.java | 2 +- .../configuration/R2DBCConfiguration.java | 7 +- .../fr/hibernatereactive/entity/Product.java | 3 +- .../service/ProductServiceTest.java | 32 ++-- .../com/metaxiii/fr/model/GenericBuilder.java | 11 +- .../test/java/com/metaxiii/fr/PostTest.java | 17 +- .../src/main/java/com/metaxiii/fr/App.java | 11 +- .../test/java/com/metaxiii/fr/AppTest.java | 88 +++++----- .../src/main/java/com/metaxiii/fr/App.java | 12 +- .../metaxiii/fr/config/CustomAnnotation.java | 5 +- .../fr/config/CustomDateDeSerializer.java | 5 +- .../fr/config/CustomDateSerializer.java | 8 +- .../metaxiii/fr/enums/TypeEnumWithValue.java | 3 +- .../java/com/metaxiii/fr/model/AliasBean.java | 2 +- .../metaxiii/fr/model/BeanWithCreator.java | 3 +- .../com/metaxiii/fr/model/BeanWithIgnore.java | 5 +- .../com/metaxiii/fr/model/BeanWithInject.java | 3 +- .../com/metaxiii/fr/model/ItemWithRef.java | 3 +- .../java/com/metaxiii/fr/model/MyBean.java | 5 +- .../metaxiii/fr/model/MyBeanDuplicated.java | 5 +- .../java/com/metaxiii/fr/model/RawBean.java | 3 +- .../com/metaxiii/fr/model/UnwrappedUser.java | 3 +- .../com/metaxiii/fr/model/UserWithRef.java | 3 +- .../metaxiii/fr/model/BeanWithFilterTest.java | 5 +- .../metaxiii/fr/model/BeanWithInjectTest.java | 3 +- .../fr/model/EventWithSerializerTest.java | 6 +- .../test/java/com/metaxiii/fr/model/Zoo.java | 7 +- .../java/com/metaxiii/fr/JacksonDateTest.java | 15 +- .../fr/config/MyBeanSerializerModifier.java | 7 +- .../metaxiii/fr/config/UpperCasingWriter.java | 3 +- .../fr/controller/ItemControllerTest.java | 31 ++-- .../java/com/metaxiii/fr/model/UserTest.java | 5 +- .../EventCriteriaRepository.java | 3 +- .../EventRepository.java | 13 +- ...datetimeWithLocaldateApplicationTests.java | 9 +- .../test/java/com/metaxiii/fr/AppTest.java | 3 +- .../java/com/metaxiii/fr/MaskingTest.java | 3 +- .../src/main/java/com/metaxiii/fr/App.java | 13 +- .../test/java/com/metaxiii/fr/AppTest.java | 7 +- .../test/java/com/metaxiii/fr/AppTest.java | 20 +-- .../test/java/com/metaxiii/fr/AppTest.java | 4 +- .../src/test/java/MainTest.java | 29 ++-- ...ParameterWithInterfaceBeforeJava8Test.java | 20 +-- ...ssingMethodParameterWithInterfaceTest.java | 5 +- pom.xml | 21 +++ .../java/com/metaxiii/fr/model/HumanTest.java | 106 ++++++------ .../com/metaxiii/fr/model/SimpleMail.java | 157 +++++++++--------- .../SortingArrayListUsingStreamUnitTest.java | 82 +++++---- .../test/java/com/metaxiii/fr/AppTest.java | 4 +- .../configuration/WebSecurityConfigurer.java | 17 +- ...ControllerRestTemplateIntegrationTest.java | 13 +- ...edControllerSpringBootIntegrationTest.java | 12 +- .../fr/service/SecuredServiceTest.java | 3 +- .../fr/configuration/SecurityConfig.java | 5 +- .../fr/exception/RestExceptionHandler.java | 24 +-- .../fr/controller/BookControllerTest.java | 113 ++++++++----- .../fr/controller/SimpleControllerTest.java | 3 +- .../fr/service/impl/BookServiceImplTest.java | 47 +++--- .../springdatagetlastrecord/entity/Post.java | 3 +- .../repository/PostServiceTest.java | 3 +- .../fr/controller/TweetController.java | 33 ++-- .../fr/controller/TweetControllerTest.java | 37 +++-- .../test/java/com/metaxiii/fr/AppTest.java | 22 ++- .../test/java/com/metaxiii/fr/AppTest.java | 13 +- .../test/java/com/metaxiii/fr/AppTest.java | 3 +- .../test/java/com/metaxiii/fr/AppTest.java | 6 +- .../com/metaxiii/fr/ImageValidatorTest.java | 6 +- 120 files changed, 1083 insertions(+), 952 deletions(-) diff --git a/CompletableFuture/src/main/java/com/metaxiii/fr/Main.java b/CompletableFuture/src/main/java/com/metaxiii/fr/Main.java index 4622e464..568eb583 100644 --- a/CompletableFuture/src/main/java/com/metaxiii/fr/Main.java +++ b/CompletableFuture/src/main/java/com/metaxiii/fr/Main.java @@ -6,15 +6,16 @@ public class Main { public Future calculateAsync() { - return CompletableFuture.supplyAsync(() -> { - try { - Thread.sleep(500); // Simuler une tâche longue - return "Hello"; - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - return null; - } - }); + return CompletableFuture.supplyAsync( + () -> { + try { + Thread.sleep(500); // Simuler une tâche longue + return "Hello"; + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return null; + } + }); } public CompletableFuture compute() { diff --git a/CompletableFuture/src/test/java/com/metaxiii/fr/MainTest.java b/CompletableFuture/src/test/java/com/metaxiii/fr/MainTest.java index 8d2a142c..e9058aa7 100644 --- a/CompletableFuture/src/test/java/com/metaxiii/fr/MainTest.java +++ b/CompletableFuture/src/test/java/com/metaxiii/fr/MainTest.java @@ -34,13 +34,14 @@ void init() { @Test void whenAddingThenAcceptToFuture_thenFunctionExecutesAfterComputationIsFinished() { final var completableFuture = CompletableFuture.supplyAsync(() -> "Hello"); - final var future = completableFuture.thenAccept(s -> System.out.println("Computation returned: " + s)); + final var future = + completableFuture.thenAccept(s -> System.out.println("Computation returned: " + s)); assertDoesNotThrow(() -> future.get()); } @Test void whenAddingThenApplyAsyncToFuture_thenFunctionExecutesAfterComputationIsFinished() - throws ExecutionException, InterruptedException { + throws ExecutionException, InterruptedException { final var completableFuture = CompletableFuture.supplyAsync(() -> "Hello"); final var future = completableFuture.thenApplyAsync(s -> s + " World"); assertEquals("Hello World", future.get()); @@ -48,11 +49,13 @@ void whenAddingThenApplyAsyncToFuture_thenFunctionExecutesAfterComputationIsFini @Test void whenAddingThenApplyToFuture_thenFunctionExecutesAfterComputationIsFinished() - throws ExecutionException, InterruptedException { - final var completableFuture = CompletableFuture.supplyAsync(() -> { - await().pollDelay(5, TimeUnit.SECONDS).untilAsserted(() -> assertTrue(true)); - return "Hello"; - }); + throws ExecutionException, InterruptedException { + final var completableFuture = + CompletableFuture.supplyAsync( + () -> { + await().pollDelay(5, TimeUnit.SECONDS).untilAsserted(() -> assertTrue(true)); + return "Hello"; + }); final var future = completableFuture.thenApply(s -> s + " World"); assertEquals("Hello World", future.get()); } @@ -66,13 +69,14 @@ void whenAddingThenRunToFuture_thenFunctionExecutesAfterComputationIsFinished() @Test void whenCreatingCompletableFutureWithSupplyAsync_thenFutureReturnsValue() - throws ExecutionException, InterruptedException { + throws ExecutionException, InterruptedException { final var future = CompletableFuture.supplyAsync(() -> "Hello"); assertEquals("Hello", future.get()); } @Test - void whenFutureCombinedWithAllOfCompletes_thenAllFuturesAreDone() throws ExecutionException, InterruptedException { + void whenFutureCombinedWithAllOfCompletes_thenAllFuturesAreDone() + throws ExecutionException, InterruptedException { final var future1 = CompletableFuture.supplyAsync(() -> "Hello"); final var future2 = CompletableFuture.supplyAsync(() -> "Beautiful"); final var future3 = CompletableFuture.supplyAsync(() -> "World"); @@ -81,10 +85,10 @@ void whenFutureCombinedWithAllOfCompletes_thenAllFuturesAreDone() throws Executi assertTrue(future1.isDone()); assertTrue(future2.isDone()); assertTrue(future3.isDone()); - final var combined = Stream - .of(future1, future2, future3) - .map(CompletableFuture::join) - .collect(Collectors.joining(" ")); + final var combined = + Stream.of(future1, future2, future3) + .map(CompletableFuture::join) + .collect(Collectors.joining(" ")); assertEquals("Hello Beautiful World", combined); } @@ -92,15 +96,16 @@ void whenFutureCombinedWithAllOfCompletes_thenAllFuturesAreDone() throws Executi @ParameterizedTest @ValueSource(strings = "you") void whenFutureThrows_thenHandleMethodReceivesException(final String name) - throws ExecutionException, InterruptedException { - CompletableFuture completableFuture = CompletableFuture - .supplyAsync(() -> { - if (name == null) { - throw new RuntimeException("Computation error!"); - } - return "Hello, " + name; - }) - .handle((s, t) -> s != null ? s : "Hello, Stranger!"); + throws ExecutionException, InterruptedException { + CompletableFuture completableFuture = + CompletableFuture.supplyAsync( + () -> { + if (name == null) { + throw new RuntimeException("Computation error!"); + } + return "Hello, " + name; + }) + .handle((s, t) -> s != null ? s : "Hello, Stranger!"); if (name == null) { assertEquals("Hello, Stranger!", completableFuture.get()); } else { @@ -109,20 +114,23 @@ void whenFutureThrows_thenHandleMethodReceivesException(final String name) } @Test - void whenPassingPreviousStage_thenFunctionExecutionWithThenCompose() throws InterruptedException, ExecutionException { - CompletableFuture finalResult = main.compute().thenCompose(integer -> main.computeAnother(integer)); + void whenPassingPreviousStage_thenFunctionExecutionWithThenCompose() + throws InterruptedException, ExecutionException { + CompletableFuture finalResult = + main.compute().thenCompose(integer -> main.computeAnother(integer)); assertEquals(20, (int) finalResult.get()); } @Test - void whenPassingTransformation_thenFunctionExecutionWithThenApply() throws InterruptedException, ExecutionException { + void whenPassingTransformation_thenFunctionExecutionWithThenApply() + throws InterruptedException, ExecutionException { final var finalResult = main.compute().thenApply(s -> s + 1); assertEquals(11, finalResult.get()); } @Test void whenRunningCompletableFutureAsynchronously_thenGetMethodWaitsForResult() - throws InterruptedException, ExecutionException { + throws InterruptedException, ExecutionException { final var completableFuture = main.calculateAsync(); final var result = completableFuture.get(); assertEquals("Hello", result); @@ -130,7 +138,7 @@ void whenRunningCompletableFutureAsynchronously_thenGetMethodWaitsForResult() @Test void whenRunningCompletableFutureWithResult_thenGetMethodReturnsImmediately() - throws InterruptedException, ExecutionException { + throws InterruptedException, ExecutionException { final var completableFuture = CompletableFuture.completedFuture("Hello"); final var result = completableFuture.get(); assertEquals("Hello", result); @@ -138,26 +146,29 @@ void whenRunningCompletableFutureWithResult_thenGetMethodReturnsImmediately() @Test void whenUsingThenAcceptBoth_thenWaitForExecutionOfBothFutures() { - assertDoesNotThrow(() -> - CompletableFuture - .supplyAsync(() -> "Hello") - .thenAcceptBoth(CompletableFuture.supplyAsync(() -> " World"), (s1, s2) -> System.out.println(s1 + s2)) - ); + assertDoesNotThrow( + () -> + CompletableFuture.supplyAsync(() -> "Hello") + .thenAcceptBoth( + CompletableFuture.supplyAsync(() -> " World"), + (s1, s2) -> System.out.println(s1 + s2))); } @Test - void whenUsingThenCombine_thenWaitForExecutionOfBothFutures() throws ExecutionException, InterruptedException { - final var completableFuture = CompletableFuture - .supplyAsync(() -> "Hello") - .thenCombine(CompletableFuture.supplyAsync(() -> " World"), (s1, s2) -> s1 + s2); + void whenUsingThenCombine_thenWaitForExecutionOfBothFutures() + throws ExecutionException, InterruptedException { + final var completableFuture = + CompletableFuture.supplyAsync(() -> "Hello") + .thenCombine(CompletableFuture.supplyAsync(() -> " World"), (s1, s2) -> s1 + s2); assertEquals("Hello World", completableFuture.get()); } @Test - void whenUsingThenCompose_thenFuturesExecuteSequentially() throws ExecutionException, InterruptedException { - final var completableFuture = CompletableFuture - .supplyAsync(() -> "Hello") - .thenCompose(s -> CompletableFuture.supplyAsync(() -> s + " World")); + void whenUsingThenCompose_thenFuturesExecuteSequentially() + throws ExecutionException, InterruptedException { + final var completableFuture = + CompletableFuture.supplyAsync(() -> "Hello") + .thenCompose(s -> CompletableFuture.supplyAsync(() -> s + " World")); assertEquals("Hello World", completableFuture.get()); } } diff --git a/Extract Text Between Square Brackets/src/test/java/com/metaxiii/fr/AppTest.java b/Extract Text Between Square Brackets/src/test/java/com/metaxiii/fr/AppTest.java index e4046304..c413d114 100644 --- a/Extract Text Between Square Brackets/src/test/java/com/metaxiii/fr/AppTest.java +++ b/Extract Text Between Square Brackets/src/test/java/com/metaxiii/fr/AppTest.java @@ -15,7 +15,8 @@ class AppTest { static final String INPUT1 = "some text [THE IMPORTANT MESSAGE] something else"; static final String EXPECTED1 = "THE IMPORTANT MESSAGE"; - static final String INPUT2 = "[La La Land], [The last Emperor], and [Life of Pi] are all great movies."; + static final String INPUT2 = + "[La La Land], [The last Emperor], and [Life of Pi] are all great movies."; static final List EXPECTED2 = List.of("La La Land", "The last Emperor", "Life of Pi"); @Test @@ -90,6 +91,7 @@ void whenUsingSplitWithLimit_thenGetExpectedResult() { assertTrue(Arrays.stream(strArray).toList().containsAll(List.of("", "THE IMPORTANT MESSAGE"))); strArray = "[THE IMPORTANT MESSAGE]".split("[\\[\\]]", -1); assertEquals(3, strArray.length); - assertTrue(Arrays.stream(strArray).toList().containsAll(List.of("", "THE IMPORTANT MESSAGE", ""))); + assertTrue( + Arrays.stream(strArray).toList().containsAll(List.of("", "THE IMPORTANT MESSAGE", ""))); } } diff --git a/FloatvsDouble/src/test/java/com/metaxiii/fr/AppTest.java b/FloatvsDouble/src/test/java/com/metaxiii/fr/AppTest.java index 35e395ea..fb81405c 100644 --- a/FloatvsDouble/src/test/java/com/metaxiii/fr/AppTest.java +++ b/FloatvsDouble/src/test/java/com/metaxiii/fr/AppTest.java @@ -42,9 +42,8 @@ void givenRangeLimits_whenExceedingBounds_thenFloatUnderflowsAndDoubleHandles() void givenUnderflowScenario_whenExceedingFloatRange_thenFloatUnderflowsToZero() { float underflowValue = 1.4e-45f / 2; // Smaller than the smallest normalized float value assertEquals( - 0.0f, - underflowValue, - "Float should underflow to zero for values smaller than the smallest representable number" - ); + 0.0f, + underflowValue, + "Float should underflow to zero for values smaller than the smallest representable number"); } } diff --git a/Get the Indexes of Regex Pattern Matches in Java/src/test/java/com/metaxiii/fr/AppTest.java b/Get the Indexes of Regex Pattern Matches in Java/src/test/java/com/metaxiii/fr/AppTest.java index a6ec6d62..113f95f5 100644 --- a/Get the Indexes of Regex Pattern Matches in Java/src/test/java/com/metaxiii/fr/AppTest.java +++ b/Get the Indexes of Regex Pattern Matches in Java/src/test/java/com/metaxiii/fr/AppTest.java @@ -14,7 +14,7 @@ class AppTest { private static final String INPUT = - "This line contains , , and ."; + "This line contains , , and ."; @Test void whenCallingMatcherEnd_thenGetIndexesAfterTheMatchSequence() { @@ -43,15 +43,13 @@ void whenUsingMatcherStartAndEndWithGroupIdx_thenGetIndexesOfMatches() { result.add(matcher.group(1)); indexesOfMatches.put(matcher.start(1), matcher.end(1)); } - assertTrue(result.containsAll(List.of("the first value", "the second value", "the third value"))); assertTrue( - indexesOfMatches - .entrySet() - .stream() - .map(entry -> INPUT.substring(entry.getKey(), entry.getValue())) - .toList() - .containsAll(List.of("the first value", "the second value", "the third value")) - ); + result.containsAll(List.of("the first value", "the second value", "the third value"))); + assertTrue( + indexesOfMatches.entrySet().stream() + .map(entry -> INPUT.substring(entry.getKey(), entry.getValue())) + .toList() + .containsAll(List.of("the first value", "the second value", "the third value"))); } @Test @@ -64,15 +62,14 @@ void whenUsingMatcherStartAndEnd_thenGetIndexesOfMatches() { result.add(matcher.group()); indexesOfMatches.put(matcher.start(), matcher.end()); } - assertTrue(result.containsAll(List.of("", "", ""))); assertTrue( - indexesOfMatches - .entrySet() - .stream() - .map(entry -> INPUT.substring(entry.getKey(), entry.getValue())) - .toList() - .containsAll(List.of("", "", "")) - ); + result.containsAll( + List.of("", "", ""))); + assertTrue( + indexesOfMatches.entrySet().stream() + .map(entry -> INPUT.substring(entry.getKey(), entry.getValue())) + .toList() + .containsAll(List.of("", "", ""))); } @Test @@ -83,6 +80,8 @@ void whenUsingNorCharClass_thenGetExpectedTexts() { while (matcher.find()) { result.add(matcher.group()); } - assertTrue(result.containsAll(List.of("", "", ""))); + assertTrue( + result.containsAll( + List.of("", "", ""))); } } diff --git a/Guava - Maps/src/test/java/com/metaxiii/fr/GuavaMapsTest.java b/Guava - Maps/src/test/java/com/metaxiii/fr/GuavaMapsTest.java index 4bf92e1c..a8fec9d6 100644 --- a/Guava - Maps/src/test/java/com/metaxiii/fr/GuavaMapsTest.java +++ b/Guava - Maps/src/test/java/com/metaxiii/fr/GuavaMapsTest.java @@ -52,13 +52,13 @@ void whenCreatingClassToInstanceMap_thenCorrect() { @Test void whenCreatingImmutableMap_thenCorrect() { - final var salary = ImmutableMap - .builder() - .put("John", 1000) - .put("Jane", 1500) - .put("Adam", 2000) - .put("Tom", 2000) - .build(); + final var salary = + ImmutableMap.builder() + .put("John", 1000) + .put("Jane", 1500) + .put("Adam", 2000) + .put("Tom", 2000) + .build(); assertEquals(1000, salary.get("John")); assertEquals(2000, salary.get("Tom")); @@ -78,11 +78,12 @@ void whenCreatingTable_thenCorrect() { @Test void whenGroupingListsUsingMultimap_thenGrouped() { final var names = Lists.newArrayList("John", "Adam", "Tom"); - final var func = new Function() { - public Integer apply(final String input) { - return input.length(); - } - }; + final var func = + new Function() { + public Integer apply(final String input) { + return input.length(); + } + }; final var groups = Multimaps.index(names, func); assertTrue(groups.get(3).contains("Tom")); assertTrue(groups.get(4).containsAll(List.of("John", "Adam"))); @@ -101,12 +102,13 @@ void whenTransposingTable_thenCorrect() { @Test void whenUsingSortedMap_thenKeysAreSorted() { - final var salary = new ImmutableSortedMap.Builder(Ordering.natural()) - .put("John", 1000) - .put("Jane", 1500) - .put("Adam", 2000) - .put("Tom", 2000) - .build(); + final var salary = + new ImmutableSortedMap.Builder(Ordering.natural()) + .put("John", 1000) + .put("Jane", 1500) + .put("Adam", 2000) + .put("Tom", 2000) + .build(); assertEquals("Adam", salary.firstKey()); assertEquals(2000, Objects.requireNonNull(salary.lastEntry()).getValue().intValue()); } diff --git a/Guava CharMatcher/src/test/java/com/metaxiii/fr/GuavaCharMatcherTest.java b/Guava CharMatcher/src/test/java/com/metaxiii/fr/GuavaCharMatcherTest.java index 7e9d62da..2ffe8204 100644 --- a/Guava CharMatcher/src/test/java/com/metaxiii/fr/GuavaCharMatcherTest.java +++ b/Guava CharMatcher/src/test/java/com/metaxiii/fr/GuavaCharMatcherTest.java @@ -7,7 +7,6 @@ import com.google.common.base.Predicate; import java.nio.charset.Charset; import java.util.Objects; - import org.junit.jupiter.api.Test; class GuavaCharMatcherTest { @@ -34,12 +33,13 @@ void whenCountCharInString_thenCorrect() { void whenRemoveCharsNotInCharset_thenRemoved() { final var charset = Charset.forName("cp437"); final var encoder = charset.newEncoder(); - final var inRange = new Predicate() { - @Override - public boolean apply(final Character c) { - return encoder.canEncode(c); - } - }; + final var inRange = + new Predicate() { + @Override + public boolean apply(final Character c) { + return encoder.canEncode(c); + } + }; final var result = CharMatcher.forPredicate(inRange).retainFrom("helloは"); assertEquals("hello", result); } @@ -56,7 +56,8 @@ void whenRemoveNonASCIIChars_thenRemoved() { @Test void whenRemoveSpecialCharacters_thenRemoved() { final var input = "H:*el.lo,}12"; - final var matcher = CharMatcher.forPredicate(c -> Objects.nonNull(c) && Character.isLetterOrDigit(c)); + final var matcher = + CharMatcher.forPredicate(c -> Objects.nonNull(c) && Character.isLetterOrDigit(c)); final var result = matcher.retainFrom(input); assertEquals("Hello12", result); } diff --git a/Intro to Jackson ObjectMapper/src/main/java/com/metaxiii/fr/conversion/JsonToJavaObject.java b/Intro to Jackson ObjectMapper/src/main/java/com/metaxiii/fr/conversion/JsonToJavaObject.java index 2f09883b..198592d4 100644 --- a/Intro to Jackson ObjectMapper/src/main/java/com/metaxiii/fr/conversion/JsonToJavaObject.java +++ b/Intro to Jackson ObjectMapper/src/main/java/com/metaxiii/fr/conversion/JsonToJavaObject.java @@ -14,7 +14,7 @@ public class JsonToJavaObject { public Car processAsObject(String json) throws JsonProcessingException { ObjectMapper objectMapper = new ObjectMapper(); return objectMapper.readValue(json, Car.class); - } + } public Car processAsFile(final File file) throws IOException { ObjectMapper objectMapper = new ObjectMapper(); diff --git a/Intro to Jackson ObjectMapper/src/main/java/com/metaxiii/fr/conversion/configuration/CustomCarDeserializer.java b/Intro to Jackson ObjectMapper/src/main/java/com/metaxiii/fr/conversion/configuration/CustomCarDeserializer.java index fcb2f495..796c3195 100644 --- a/Intro to Jackson ObjectMapper/src/main/java/com/metaxiii/fr/conversion/configuration/CustomCarDeserializer.java +++ b/Intro to Jackson ObjectMapper/src/main/java/com/metaxiii/fr/conversion/configuration/CustomCarDeserializer.java @@ -19,7 +19,8 @@ public CustomCarDeserializer(Class vc) { } @Override - public Car deserialize(JsonParser parser, DeserializationContext deserializer) throws IOException { + public Car deserialize(JsonParser parser, DeserializationContext deserializer) + throws IOException { Car car = new Car(); ObjectCodec codec = parser.getCodec(); JsonNode node = codec.readTree(parser); diff --git a/Intro to Jackson ObjectMapper/src/main/java/com/metaxiii/fr/conversion/configuration/CustomCarSerializer.java b/Intro to Jackson ObjectMapper/src/main/java/com/metaxiii/fr/conversion/configuration/CustomCarSerializer.java index 79f3ceab..c815b988 100644 --- a/Intro to Jackson ObjectMapper/src/main/java/com/metaxiii/fr/conversion/configuration/CustomCarSerializer.java +++ b/Intro to Jackson ObjectMapper/src/main/java/com/metaxiii/fr/conversion/configuration/CustomCarSerializer.java @@ -17,8 +17,9 @@ public CustomCarSerializer(final Class t) { } @Override - public void serialize(final Car car, final JsonGenerator jsonGenerator, final SerializerProvider serializerProvider) - throws IOException { + public void serialize( + final Car car, final JsonGenerator jsonGenerator, final SerializerProvider serializerProvider) + throws IOException { jsonGenerator.writeStartObject(); jsonGenerator.writeStringField("car_brand", car.getType()); jsonGenerator.writeEndObject(); diff --git a/Intro to Jackson ObjectMapper/src/main/java/com/metaxiii/fr/model/Request.java b/Intro to Jackson ObjectMapper/src/main/java/com/metaxiii/fr/model/Request.java index 3c039218..6518df71 100644 --- a/Intro to Jackson ObjectMapper/src/main/java/com/metaxiii/fr/model/Request.java +++ b/Intro to Jackson ObjectMapper/src/main/java/com/metaxiii/fr/model/Request.java @@ -1,12 +1,11 @@ package com.metaxiii.fr.model; +import java.util.Date; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; -import java.util.Date; - @Getter @Setter @NoArgsConstructor diff --git a/Intro to Jackson ObjectMapper/src/test/java/com/metaxiii/fr/conversion/HandlingDateFormatTest.java b/Intro to Jackson ObjectMapper/src/test/java/com/metaxiii/fr/conversion/HandlingDateFormatTest.java index eda7be76..6be81522 100644 --- a/Intro to Jackson ObjectMapper/src/test/java/com/metaxiii/fr/conversion/HandlingDateFormatTest.java +++ b/Intro to Jackson ObjectMapper/src/test/java/com/metaxiii/fr/conversion/HandlingDateFormatTest.java @@ -11,7 +11,8 @@ class HandlingDateFormatTest { private HandlingDateFormat handlingDateFormat; - private static final String JSON = "{\"car\":{\"color\":\"Black\",\"type\":\"BMW\"},\"datePurcharsed\":\""; + private static final String JSON = + "{\"car\":{\"color\":\"Black\",\"type\":\"BMW\"},\"datePurcharsed\":\""; @BeforeEach public void init() { @@ -25,9 +26,10 @@ public void endEach() { @Test void process() { - assertDoesNotThrow(() -> { - final Car car = new Car("Black", "BMW"); - assertTrue(handlingDateFormat.process(car).contains(JSON)); - }); + assertDoesNotThrow( + () -> { + final Car car = new Car("Black", "BMW"); + assertTrue(handlingDateFormat.process(car).contains(JSON)); + }); } } diff --git a/Intro to Jackson ObjectMapper/src/test/java/com/metaxiii/fr/conversion/JSONtoJacksonJsonNodeTest.java b/Intro to Jackson ObjectMapper/src/test/java/com/metaxiii/fr/conversion/JSONtoJacksonJsonNodeTest.java index 72b06777..2ff84b56 100644 --- a/Intro to Jackson ObjectMapper/src/test/java/com/metaxiii/fr/conversion/JSONtoJacksonJsonNodeTest.java +++ b/Intro to Jackson ObjectMapper/src/test/java/com/metaxiii/fr/conversion/JSONtoJacksonJsonNodeTest.java @@ -25,9 +25,10 @@ public void endEach() { @Test void process() { - assertDoesNotThrow(() -> { - final JsonNode process = jSONtoJacksonJsonNode.process(JSON); - assertEquals("Black", process.get("color").asText()); - }); + assertDoesNotThrow( + () -> { + final JsonNode process = jSONtoJacksonJsonNode.process(JSON); + assertEquals("Black", process.get("color").asText()); + }); } } diff --git a/Intro to Jackson ObjectMapper/src/test/java/com/metaxiii/fr/conversion/JavaListFromJSONArrayStringTest.java b/Intro to Jackson ObjectMapper/src/test/java/com/metaxiii/fr/conversion/JavaListFromJSONArrayStringTest.java index 723be2da..91a939b0 100644 --- a/Intro to Jackson ObjectMapper/src/test/java/com/metaxiii/fr/conversion/JavaListFromJSONArrayStringTest.java +++ b/Intro to Jackson ObjectMapper/src/test/java/com/metaxiii/fr/conversion/JavaListFromJSONArrayStringTest.java @@ -13,7 +13,7 @@ class JavaListFromJSONArrayStringTest { private JavaListFromJSONArrayString javaListFromJSONArrayString; private static final String JSON_CAR_ARRAY = - "[{\"color\": \"Black\", \"type\": \"BMW\"}, {\"color\": \"Red\", \"type\": \"Fiat\"}]"; + "[{\"color\": \"Black\", \"type\": \"BMW\"}, {\"color\": \"Red\", \"type\": \"Fiat\"}]"; @BeforeEach public void init() { @@ -27,19 +27,21 @@ public void endEach() { @Test void processAsList() { - assertDoesNotThrow(() -> { - final List cars = javaListFromJSONArrayString.processAsList(JSON_CAR_ARRAY); - assertEquals("Black", cars.get(0).getColor()); - assertEquals("Red", cars.get(1).getColor()); - }); + assertDoesNotThrow( + () -> { + final List cars = javaListFromJSONArrayString.processAsList(JSON_CAR_ARRAY); + assertEquals("Black", cars.get(0).getColor()); + assertEquals("Red", cars.get(1).getColor()); + }); } @Test void processAsArray() { - assertDoesNotThrow(() -> { - final Car[] cars = javaListFromJSONArrayString.processAsArray(JSON_CAR_ARRAY); - assertEquals("Black", cars[0].getColor()); - assertEquals("Red", cars[1].getColor()); - }); + assertDoesNotThrow( + () -> { + final Car[] cars = javaListFromJSONArrayString.processAsArray(JSON_CAR_ARRAY); + assertEquals("Black", cars[0].getColor()); + assertEquals("Red", cars[1].getColor()); + }); } } diff --git a/Intro to Jackson ObjectMapper/src/test/java/com/metaxiii/fr/conversion/JavaMapFromJSONStringTest.java b/Intro to Jackson ObjectMapper/src/test/java/com/metaxiii/fr/conversion/JavaMapFromJSONStringTest.java index 0e90d816..3db251ba 100644 --- a/Intro to Jackson ObjectMapper/src/test/java/com/metaxiii/fr/conversion/JavaMapFromJSONStringTest.java +++ b/Intro to Jackson ObjectMapper/src/test/java/com/metaxiii/fr/conversion/JavaMapFromJSONStringTest.java @@ -25,10 +25,11 @@ public void endEach() { @Test void process() { - assertDoesNotThrow(() -> { - final Map cars = javaMapFromJSONString.process(JSON); - assertEquals("[color, type]", cars.keySet().toString()); - assertEquals("[Black, BMW]", cars.values().toString()); - }); + assertDoesNotThrow( + () -> { + final Map cars = javaMapFromJSONString.process(JSON); + assertEquals("[color, type]", cars.keySet().toString()); + assertEquals("[Black, BMW]", cars.values().toString()); + }); } } diff --git a/Intro to Jackson ObjectMapper/src/test/java/com/metaxiii/fr/conversion/JavaObjectToJsonTest.java b/Intro to Jackson ObjectMapper/src/test/java/com/metaxiii/fr/conversion/JavaObjectToJsonTest.java index b43ae0e4..45f75035 100644 --- a/Intro to Jackson ObjectMapper/src/test/java/com/metaxiii/fr/conversion/JavaObjectToJsonTest.java +++ b/Intro to Jackson ObjectMapper/src/test/java/com/metaxiii/fr/conversion/JavaObjectToJsonTest.java @@ -26,9 +26,10 @@ public void endEach() { @Test void itShouldRenderCarAsJson() { final Car car = new Car("Black", "BMW"); - assertDoesNotThrow(() -> { - final String process = javaObjectToJson.process(car); - assertEquals(JSON, process); - }); + assertDoesNotThrow( + () -> { + final String process = javaObjectToJson.process(car); + assertEquals(JSON, process); + }); } } diff --git a/Intro to Jackson ObjectMapper/src/test/java/com/metaxiii/fr/conversion/JsonToJavaObjectTest.java b/Intro to Jackson ObjectMapper/src/test/java/com/metaxiii/fr/conversion/JsonToJavaObjectTest.java index 2cee8012..1ce3ddc3 100644 --- a/Intro to Jackson ObjectMapper/src/test/java/com/metaxiii/fr/conversion/JsonToJavaObjectTest.java +++ b/Intro to Jackson ObjectMapper/src/test/java/com/metaxiii/fr/conversion/JsonToJavaObjectTest.java @@ -28,29 +28,32 @@ public void endEach() { @Test void processAsObject() { - assertDoesNotThrow(() -> { - final Car car = jsonToJavaObject.processAsObject(JSON); - assertEquals("Black", car.getColor()); - assertEquals("BMW", car.getType()); - }); + assertDoesNotThrow( + () -> { + final Car car = jsonToJavaObject.processAsObject(JSON); + assertEquals("Black", car.getColor()); + assertEquals("BMW", car.getType()); + }); } @Test void processAsFile() { - assertDoesNotThrow(() -> { - final Car car = jsonToJavaObject.processAsFile(FILE); - assertEquals("yellow", car.getColor()); - assertEquals("diesel", car.getType()); - }); + assertDoesNotThrow( + () -> { + final Car car = jsonToJavaObject.processAsFile(FILE); + assertEquals("yellow", car.getColor()); + assertEquals("diesel", car.getType()); + }); } @Test void processAsUrl() { - assertDoesNotThrow(() -> { - final URL url = new URL("file:src/test/resources/json_car_url.json"); - final Car car = jsonToJavaObject.processAsUrl(url); - assertEquals("pink", car.getColor()); - assertEquals("diesel", car.getType()); - }); + assertDoesNotThrow( + () -> { + final URL url = new File("src/test/resources/json_car_url.json").toURI().toURL(); + final Car car = jsonToJavaObject.processAsUrl(url); + assertEquals("pink", car.getColor()); + assertEquals("diesel", car.getType()); + }); } } diff --git a/Intro to Jackson ObjectMapper/src/test/java/com/metaxiii/fr/conversion/SerializationDeserializationTest.java b/Intro to Jackson ObjectMapper/src/test/java/com/metaxiii/fr/conversion/SerializationDeserializationTest.java index 4baea63c..71ab8303 100644 --- a/Intro to Jackson ObjectMapper/src/test/java/com/metaxiii/fr/conversion/SerializationDeserializationTest.java +++ b/Intro to Jackson ObjectMapper/src/test/java/com/metaxiii/fr/conversion/SerializationDeserializationTest.java @@ -16,7 +16,8 @@ class SerializationDeserializationTest { private SerializationDeserialization serializationDeserialization; - private static final String JSON = "{ \"color\" : \"Black\", \"type\" : \"BMW\", \"year\" : \"2022\" }"; + private static final String JSON = + "{ \"color\" : \"Black\", \"type\" : \"BMW\", \"year\" : \"2022\" }"; private static final String GOOD_JSON = "{ \"color\" : \"Black\", \"type\" : \"BMW\"}"; @BeforeEach @@ -30,39 +31,45 @@ public void endEach() { } @Test - void itShouldThrowsUnrecognizedPropertyExceptionWhenObjectMapperIsNotConfigureForDeserialization() { + void + itShouldThrowsUnrecognizedPropertyExceptionWhenObjectMapperIsNotConfigureForDeserialization() { assertThrows( - UnrecognizedPropertyException.class, - () -> { - final Car car = serializationDeserialization.processWithUnrecognizedPropertyException(JSON); - assertNull(car); - } - ); + UnrecognizedPropertyException.class, + () -> { + final Car car = + serializationDeserialization.processWithUnrecognizedPropertyException(JSON); + assertNull(car); + }); } @Test - void itShouldNotThrowsUnrecognizedPropertyExceptionWhenObjectMapperIsNotConfigureForDeserialization() { - assertDoesNotThrow(() -> { - final Car car = serializationDeserialization.processWithUnrecognizedPropertyException(GOOD_JSON); - assertNotNull(car); - }); + void + itShouldNotThrowsUnrecognizedPropertyExceptionWhenObjectMapperIsNotConfigureForDeserialization() { + assertDoesNotThrow( + () -> { + final Car car = + serializationDeserialization.processWithUnrecognizedPropertyException(GOOD_JSON); + assertNotNull(car); + }); } @Test void itShouldProcessWhenObjectMapperIsConfigure() { - assertDoesNotThrow(() -> { - final Car car = serializationDeserialization.process(JSON); - assertEquals("Black", car.getColor()); - assertEquals("BMW", car.getType()); - }); + assertDoesNotThrow( + () -> { + final Car car = serializationDeserialization.process(JSON); + assertEquals("Black", car.getColor()); + assertEquals("BMW", car.getType()); + }); } @Test void itShouldRenderJsonNode() { - assertDoesNotThrow(() -> { - final JsonNode jsonNodeRoot = serializationDeserialization.processJsonNode(JSON); - JsonNode jsonNodeYear = jsonNodeRoot.get("year"); - assertEquals("2022", jsonNodeYear.asText()); - }); + assertDoesNotThrow( + () -> { + final JsonNode jsonNodeRoot = serializationDeserialization.processJsonNode(JSON); + JsonNode jsonNodeYear = jsonNodeRoot.get("year"); + assertEquals("2022", jsonNodeYear.asText()); + }); } } diff --git a/Intro to Jackson ObjectMapper/src/test/java/com/metaxiii/fr/conversion/configuration/CustomCarDeserializerTest.java b/Intro to Jackson ObjectMapper/src/test/java/com/metaxiii/fr/conversion/configuration/CustomCarDeserializerTest.java index 64461869..5e5e4f04 100644 --- a/Intro to Jackson ObjectMapper/src/test/java/com/metaxiii/fr/conversion/configuration/CustomCarDeserializerTest.java +++ b/Intro to Jackson ObjectMapper/src/test/java/com/metaxiii/fr/conversion/configuration/CustomCarDeserializerTest.java @@ -15,7 +15,8 @@ class CustomCarDeserializerTest { private static final String JSON = "{ \"color\" : \"Black\", \"type\" : \"BMW\"}"; private ObjectMapper mapper = new ObjectMapper(); - private SimpleModule module = new SimpleModule("CustomCarDeserializer", new Version(1, 0, 0, null, null, null)); + private SimpleModule module = + new SimpleModule("CustomCarDeserializer", new Version(1, 0, 0, null, null, null)); @BeforeEach public void init() { @@ -37,17 +38,16 @@ void itShouldConstructor() { @Test void deserialize() { - assertDoesNotThrow(() -> { - ObjectMapper deserializeMapper = new ObjectMapper(); - SimpleModule deserializeModule = new SimpleModule( - "CustomCarDeserializer", - new Version(1, 0, 0, null, null, null) - ); - deserializeModule.addDeserializer(Car.class, new CustomCarDeserializer()); - deserializeMapper.registerModule(module); - final Car car = mapper.readValue(JSON, Car.class); - assertEquals("Black", car.getColor()); - assertEquals("BMW", car.getType()); - }); + assertDoesNotThrow( + () -> { + ObjectMapper deserializeMapper = new ObjectMapper(); + SimpleModule deserializeModule = + new SimpleModule("CustomCarDeserializer", new Version(1, 0, 0, null, null, null)); + deserializeModule.addDeserializer(Car.class, new CustomCarDeserializer()); + deserializeMapper.registerModule(module); + final Car car = mapper.readValue(JSON, Car.class); + assertEquals("Black", car.getColor()); + assertEquals("BMW", car.getType()); + }); } } diff --git a/Intro to Jackson ObjectMapper/src/test/java/com/metaxiii/fr/conversion/configuration/CustomCarSerializerTest.java b/Intro to Jackson ObjectMapper/src/test/java/com/metaxiii/fr/conversion/configuration/CustomCarSerializerTest.java index 00a8ea1f..f2210ab4 100644 --- a/Intro to Jackson ObjectMapper/src/test/java/com/metaxiii/fr/conversion/configuration/CustomCarSerializerTest.java +++ b/Intro to Jackson ObjectMapper/src/test/java/com/metaxiii/fr/conversion/configuration/CustomCarSerializerTest.java @@ -15,7 +15,8 @@ class CustomCarSerializerTest { private static final String JSON = "{\"car_brand\":\"renault\"}"; private ObjectMapper mapper = new ObjectMapper(); - private SimpleModule module = new SimpleModule("CustomCarSerializer", new Version(1, 0, 0, null, null, null)); + private SimpleModule module = + new SimpleModule("CustomCarSerializer", new Version(1, 0, 0, null, null, null)); @BeforeEach public void init() { @@ -31,11 +32,12 @@ public void endEach() { @Test void serialize() { - assertDoesNotThrow(() -> { - module.addSerializer(Car.class, new CustomCarSerializer()); - mapper.registerModule(module); - Car car = new Car("yellow", "renault"); - assertEquals(JSON, mapper.writeValueAsString(car)); - }); + assertDoesNotThrow( + () -> { + module.addSerializer(Car.class, new CustomCarSerializer()); + mapper.registerModule(module); + Car car = new Car("yellow", "renault"); + assertEquals(JSON, mapper.writeValueAsString(car)); + }); } } diff --git a/Serialize and deserialize enums with jackson/src/main/java/com/metaxiii/fr/enums/DistanceAsJSONCreator.java b/Serialize and deserialize enums with jackson/src/main/java/com/metaxiii/fr/enums/DistanceAsJSONCreator.java index 06d43b85..6733c70b 100644 --- a/Serialize and deserialize enums with jackson/src/main/java/com/metaxiii/fr/enums/DistanceAsJSONCreator.java +++ b/Serialize and deserialize enums with jackson/src/main/java/com/metaxiii/fr/enums/DistanceAsJSONCreator.java @@ -20,9 +20,7 @@ public enum DistanceAsJSONCreator { @JsonCreator public static DistanceAsJSONCreator forValues( - @JsonProperty("unit") final String unit, - @JsonProperty("meters") final double meters - ) { + @JsonProperty("unit") final String unit, @JsonProperty("meters") final double meters) { for (final DistanceAsJSONCreator distance : DistanceAsJSONCreator.values()) { if (distance.unit.equals(unit) && Double.compare(distance.meters, meters) == 0) { return distance; diff --git a/Serialize and deserialize enums with jackson/src/main/java/com/metaxiii/fr/enums/DistanceAsJsonValue.java b/Serialize and deserialize enums with jackson/src/main/java/com/metaxiii/fr/enums/DistanceAsJsonValue.java index c0d12ef5..f7cde8e1 100644 --- a/Serialize and deserialize enums with jackson/src/main/java/com/metaxiii/fr/enums/DistanceAsJsonValue.java +++ b/Serialize and deserialize enums with jackson/src/main/java/com/metaxiii/fr/enums/DistanceAsJsonValue.java @@ -16,6 +16,5 @@ public enum DistanceAsJsonValue { private final String unit; - @JsonValue - private final double meters; + @JsonValue private final double meters; } diff --git a/Serialize and deserialize enums with jackson/src/main/java/com/metaxiii/fr/enums/config/DistanceDeserializerConfig.java b/Serialize and deserialize enums with jackson/src/main/java/com/metaxiii/fr/enums/config/DistanceDeserializerConfig.java index 915da58e..51d7e972 100644 --- a/Serialize and deserialize enums with jackson/src/main/java/com/metaxiii/fr/enums/config/DistanceDeserializerConfig.java +++ b/Serialize and deserialize enums with jackson/src/main/java/com/metaxiii/fr/enums/config/DistanceDeserializerConfig.java @@ -14,8 +14,8 @@ public DistanceDeserializerConfig() { } @Override - public DistanceDeserializer deserialize(final JsonParser jsonParser, final DeserializationContext ctxt) - throws IOException { + public DistanceDeserializer deserialize( + final JsonParser jsonParser, final DeserializationContext ctxt) throws IOException { JsonNode node = jsonParser.getCodec().readTree(jsonParser); String unit = node.get("unit").asText(); double meters = node.get("meters").asDouble(); diff --git a/Serialize and deserialize enums with jackson/src/main/java/com/metaxiii/fr/enums/config/DistanceSerializerConfig.java b/Serialize and deserialize enums with jackson/src/main/java/com/metaxiii/fr/enums/config/DistanceSerializerConfig.java index c4e2af1d..f996bac2 100644 --- a/Serialize and deserialize enums with jackson/src/main/java/com/metaxiii/fr/enums/config/DistanceSerializerConfig.java +++ b/Serialize and deserialize enums with jackson/src/main/java/com/metaxiii/fr/enums/config/DistanceSerializerConfig.java @@ -13,8 +13,9 @@ public DistanceSerializerConfig() { } @Override - public void serialize(final DistanceSerializer distance, final JsonGenerator gen, final SerializerProvider provider) - throws IOException { + public void serialize( + final DistanceSerializer distance, final JsonGenerator gen, final SerializerProvider provider) + throws IOException { gen.writeStartObject(); gen.writeFieldName("name"); gen.writeString((distance.name())); diff --git a/Serialize and deserialize enums with jackson/src/test/java/com/metaxiii/fr/enums/DistanceTest.java b/Serialize and deserialize enums with jackson/src/test/java/com/metaxiii/fr/enums/DistanceTest.java index bfb083c8..19cc1eef 100644 --- a/Serialize and deserialize enums with jackson/src/test/java/com/metaxiii/fr/enums/DistanceTest.java +++ b/Serialize and deserialize enums with jackson/src/test/java/com/metaxiii/fr/enums/DistanceTest.java @@ -35,7 +35,8 @@ void itShouldGiveJSONEnumRepresentationWhenDistanceAsJSONValue() throws JsonProc } @Test - void itShouldGiveJSONEnumRepresentationWhenDistanceAsDistanceSerializer() throws JsonProcessingException { + void itShouldGiveJSONEnumRepresentationWhenDistanceAsDistanceSerializer() + throws JsonProcessingException { final ObjectMapper objectMapper = new ObjectMapper(); final String string = objectMapper.writeValueAsString(DistanceSerializer.MILE); assertEquals("{\"name\":\"MILE\",\"unit\":\"miles\",\"meters\":1609.34}", string); @@ -49,47 +50,49 @@ void itShouldDeserializeJsonToEnumWithDefaultBehavior() throws JsonProcessingExc @Test void itShouldDeserializeJsonToEnumUsingJsonValue() throws JsonProcessingException { - CityWithDistanceAsJsonValue city = new ObjectMapper() - .readValue("{\"distance\":\"0.0254\"}", CityWithDistanceAsJsonValue.class); + CityWithDistanceAsJsonValue city = + new ObjectMapper() + .readValue("{\"distance\":\"0.0254\"}", CityWithDistanceAsJsonValue.class); assertEquals(DistanceAsJsonValue.INCH, city.getDistance()); } @Test void itShouldDeserializeJsonToEnumUsingJsonproperties() throws JsonProcessingException { - CityWithDistanceAsJsonProperty city = new ObjectMapper() - .readValue("{\"distance\": \"distance-in-km\"}", CityWithDistanceAsJsonProperty.class); + CityWithDistanceAsJsonProperty city = + new ObjectMapper() + .readValue("{\"distance\": \"distance-in-km\"}", CityWithDistanceAsJsonProperty.class); assertEquals(DistanceAsJSONProperty.KILOMETER, city.getDistance()); } @Test void itShouldDeserializeJsonToEnumUsingJsonCreator() throws JsonProcessingException { - CityWithDistanceAsJsonCreator city = new ObjectMapper() - .readValue( - """ + CityWithDistanceAsJsonCreator city = + new ObjectMapper() + .readValue( + """ { "distance": { "unit":"miles", "meters":1609.34 } }""", - CityWithDistanceAsJsonCreator.class - ); + CityWithDistanceAsJsonCreator.class); assertEquals(DistanceAsJSONCreator.MILE, city.getDistance()); } @Test void itShouldDeserializeJsonToEnumUsingCustomDeserializor() throws JsonProcessingException { - CityWithDistanceAsJsonCustomDeserializor city = new ObjectMapper() - .readValue( - """ + CityWithDistanceAsJsonCustomDeserializor city = + new ObjectMapper() + .readValue( + """ { "distance": { "unit":"miles", "meters":1609.34 } }""", - CityWithDistanceAsJsonCustomDeserializor.class - ); + CityWithDistanceAsJsonCustomDeserializor.class); assertEquals(DistanceDeserializer.MILE, city.getDistance()); } } diff --git a/actuator/src/test/java/com/metaxiii/fr/actuator/ActuatorApplicationTests.java b/actuator/src/test/java/com/metaxiii/fr/actuator/ActuatorApplicationTests.java index 3a019e16..2c1948fb 100644 --- a/actuator/src/test/java/com/metaxiii/fr/actuator/ActuatorApplicationTests.java +++ b/actuator/src/test/java/com/metaxiii/fr/actuator/ActuatorApplicationTests.java @@ -15,8 +15,7 @@ @AutoConfigureMockMvc class ActuatorApplicationTests { - @Autowired - private MockMvc mockMvc; + @Autowired private MockMvc mockMvc; @Test void contextLoads() { @@ -25,7 +24,13 @@ void contextLoads() { @Test void itShouldCallActuator() throws Exception { - mockMvc.perform(MockMvcRequestBuilders.get("/actuator")).andDo(print()).andExpect(status().isOk()); - mockMvc.perform(MockMvcRequestBuilders.get("/actuator/info")).andDo(print()).andExpect(status().isOk()); + mockMvc + .perform(MockMvcRequestBuilders.get("/actuator")) + .andDo(print()) + .andExpect(status().isOk()); + mockMvc + .perform(MockMvcRequestBuilders.get("/actuator/info")) + .andDo(print()) + .andExpect(status().isOk()); } } diff --git a/array-custom-tostring/src/test/java/com/metaxiii/fr/AppTest.java b/array-custom-tostring/src/test/java/com/metaxiii/fr/AppTest.java index 83347dc5..c02e13da 100644 --- a/array-custom-tostring/src/test/java/com/metaxiii/fr/AppTest.java +++ b/array-custom-tostring/src/test/java/com/metaxiii/fr/AppTest.java @@ -11,7 +11,7 @@ class AppTest { - private static final String[] CONTENT = new String[] { "www.", "Baeldung.", "com" }; + private static final String[] CONTENT = new String[] {"www.", "Baeldung.", "com"}; @Test void givenArray_whenUsingJoinerJoin_thenPrintedArrayWithoutCommaBrackets() { @@ -49,7 +49,8 @@ void givenArray_whenUsingStringReplaceAll_thenPrintedArrayWithoutCommaBrackets() @Test void givenArray_whenUsingStringReplace_thenPrintedArrayWithoutCommaBrackets() { - final String result = Arrays.toString(CONTENT).replace("[", "").replace("]", "").replace(", ", ""); + final String result = + Arrays.toString(CONTENT).replace("[", "").replace("]", "").replace(", ", ""); assertEquals("www.Baeldung.com", result); } diff --git a/arraylist-include-string-arrays/src/test/java/com/metaxiii/fr/AppTest.java b/arraylist-include-string-arrays/src/test/java/com/metaxiii/fr/AppTest.java index 1747dd9a..6993097d 100644 --- a/arraylist-include-string-arrays/src/test/java/com/metaxiii/fr/AppTest.java +++ b/arraylist-include-string-arrays/src/test/java/com/metaxiii/fr/AppTest.java @@ -11,26 +11,26 @@ class AppTest { - private static final String[] ARRAY1 = { "Java", "Kotlin", "Sql", "Javascript" }; - private static final String[] ARRAY2 = { "C", "C++", "C#", "Typescript" }; - private static final String[] ARRAY3 = { "Python", "Ruby", "Go", "Rust" }; + private static final String[] ARRAY1 = {"Java", "Kotlin", "Sql", "Javascript"}; + private static final String[] ARRAY2 = {"C", "C++", "C#", "Typescript"}; + private static final String[] ARRAY3 = {"Python", "Ruby", "Go", "Rust"}; - private static final List EXPECTED = List.of( - "Languages", - ":", - "Java", - "Kotlin", - "Sql", - "Javascript", - "C", - "C++", - "C#", - "Typescript", - "Python", - "Ruby", - "Go", - "Rust" - ); + private static final List EXPECTED = + List.of( + "Languages", + ":", + "Java", + "Kotlin", + "Sql", + "Javascript", + "C", + "C++", + "C#", + "Typescript", + "Python", + "Ruby", + "Go", + "Rust"); @Test void whenConvertArrayToListThenAddAll_thenCorrect() { diff --git a/arraylist-no-duplicates/src/test/java/com/metaxiii/fr/AppTest.java b/arraylist-no-duplicates/src/test/java/com/metaxiii/fr/AppTest.java index 51d9acfa..a6e275a4 100644 --- a/arraylist-no-duplicates/src/test/java/com/metaxiii/fr/AppTest.java +++ b/arraylist-no-duplicates/src/test/java/com/metaxiii/fr/AppTest.java @@ -52,7 +52,8 @@ void givenArrayList_whenUsingFilterAndFindFirst_thenAvoidDuplicates() { final var distinctCities = Arrays.asList("Tamassint", "Madrid", "Paris", "Tokyo"); final var arrayListCities = new ArrayList<>(distinctCities); final var newCity = "Tamassint"; - final var optionalCity = arrayListCities.stream().filter(city -> city.equals(newCity)).findFirst(); + final var optionalCity = + arrayListCities.stream().filter(city -> city.equals(newCity)).findFirst(); if (optionalCity.isEmpty()) { arrayListCities.add(newCity); } @@ -73,7 +74,8 @@ void givenArrayList_whenUsingIterablesContains_thenAvoidDuplicates() { @Test void givenArrayList_whenUsingSet_thenAvoidDuplicates() { - final Set distinctCities = new HashSet<>(Arrays.asList("Tamassint", "Madrid", "Paris", "Tokyo")); + final Set distinctCities = + new HashSet<>(Arrays.asList("Tamassint", "Madrid", "Paris", "Tokyo")); final var newCity = "Paris"; distinctCities.add(newCity); final var arrayListCities = new ArrayList<>(distinctCities); diff --git a/avoid-no-multipart-boundary-was-found/src/main/java/com/metaxiii/fr/avoidnomultipartboundarywasfound/FileController.java b/avoid-no-multipart-boundary-was-found/src/main/java/com/metaxiii/fr/avoidnomultipartboundarywasfound/FileController.java index a76c6e8e..a66557e0 100644 --- a/avoid-no-multipart-boundary-was-found/src/main/java/com/metaxiii/fr/avoidnomultipartboundarywasfound/FileController.java +++ b/avoid-no-multipart-boundary-was-found/src/main/java/com/metaxiii/fr/avoidnomultipartboundarywasfound/FileController.java @@ -18,7 +18,8 @@ public class FileController { protected static final String FILES = "/files"; @PostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE) - public String upload(@RequestParam("file") final MultipartFile file, final String fileDescription) { + public String upload( + @RequestParam("file") final MultipartFile file, final String fileDescription) { log.info("Uploading file {}", file.getName()); log.info("upload fileDescrition {}", fileDescription); return "files/success"; diff --git a/avoid-no-multipart-boundary-was-found/src/test/java/com/metaxiii/fr/avoidnomultipartboundarywasfound/AvoidNoMultipartBoundaryWasFoundApplicationTests.java b/avoid-no-multipart-boundary-was-found/src/test/java/com/metaxiii/fr/avoidnomultipartboundarywasfound/AvoidNoMultipartBoundaryWasFoundApplicationTests.java index 7806d737..67934b8d 100644 --- a/avoid-no-multipart-boundary-was-found/src/test/java/com/metaxiii/fr/avoidnomultipartboundarywasfound/AvoidNoMultipartBoundaryWasFoundApplicationTests.java +++ b/avoid-no-multipart-boundary-was-found/src/test/java/com/metaxiii/fr/avoidnomultipartboundarywasfound/AvoidNoMultipartBoundaryWasFoundApplicationTests.java @@ -9,6 +9,7 @@ class AvoidNoMultipartBoundaryWasFoundApplicationTests { @Test void contextLoads() { - Assertions.assertDoesNotThrow(() -> AvoidNoMultipartBoundaryWasFoundApplication.main(new String[] {})); + Assertions.assertDoesNotThrow( + () -> AvoidNoMultipartBoundaryWasFoundApplication.main(new String[] {})); } } diff --git a/avoid-no-multipart-boundary-was-found/src/test/java/com/metaxiii/fr/avoidnomultipartboundarywasfound/FileControllerTest.java b/avoid-no-multipart-boundary-was-found/src/test/java/com/metaxiii/fr/avoidnomultipartboundarywasfound/FileControllerTest.java index ad2fa11c..bdade96a 100644 --- a/avoid-no-multipart-boundary-was-found/src/test/java/com/metaxiii/fr/avoidnomultipartboundarywasfound/FileControllerTest.java +++ b/avoid-no-multipart-boundary-was-found/src/test/java/com/metaxiii/fr/avoidnomultipartboundarywasfound/FileControllerTest.java @@ -22,45 +22,45 @@ class FileControllerTest { private static final String BOUNDARY = "OurCustomBoundaryValue"; private static final String BODY = - "--" + - BOUNDARY + - "\r\n" + - "Content-Disposition: form-data; name=\"file\"; filename=\"import.csv\"\r\n" + - "Content-Type: text/csv\r\n" + - "\r\n" + - "content-of-the-csv-file\r\n" + - "--" + - BOUNDARY + - "\r\n" + - "Content-Disposition: form-data; name=\"fileDescription\"\r\n" + - "\r\n" + - "Records\r\n" + - "--" + - BOUNDARY + - "--"; + "--" + + BOUNDARY + + "\r\n" + + "Content-Disposition: form-data; name=\"file\"; filename=\"import.csv\"\r\n" + + "Content-Type: text/csv\r\n" + + "\r\n" + + "content-of-the-csv-file\r\n" + + "--" + + BOUNDARY + + "\r\n" + + "Content-Disposition: form-data; name=\"fileDescription\"\r\n" + + "\r\n" + + "Records\r\n" + + "--" + + BOUNDARY + + "--"; - @LocalServerPort - private int port; + @LocalServerPort private int port; @Test void givenFormData_whenPostWithBoundary_thenReturn200() throws IOException { - final RequestBody requestBody = RequestBody.create( - BODY.getBytes(), - parse(MediaType.MULTIPART_FORM_DATA_VALUE + "; boundary=" + BOUNDARY) - ); + final RequestBody requestBody = + RequestBody.create( + BODY.getBytes(), parse(MediaType.MULTIPART_FORM_DATA_VALUE + "; boundary=" + BOUNDARY)); try (final Response response = executeCall(requestBody)) { assertEquals(HttpStatus.OK.value(), response.code()); } } private Response executeCall(final RequestBody requestBody) throws IOException { - final Request request = new Request.Builder().url(HOST + port + FILES).post(requestBody).build(); + final Request request = + new Request.Builder().url(HOST + port + FILES).post(requestBody).build(); return new OkHttpClient().newCall(request).execute(); } @Test void givenFormData_whenPostWithoutBoundary_thenReturn500() throws IOException { - final RequestBody requestBody = RequestBody.create(BODY.getBytes(), parse(MediaType.MULTIPART_FORM_DATA_VALUE)); + final RequestBody requestBody = + RequestBody.create(BODY.getBytes(), parse(MediaType.MULTIPART_FORM_DATA_VALUE)); try (final Response response = executeCall(requestBody)) { assertEquals(HttpStatus.INTERNAL_SERVER_ERROR.value(), response.code()); } diff --git a/camel-snake-case-conversion/src/main/java/com/metaxiii/fr/App.java b/camel-snake-case-conversion/src/main/java/com/metaxiii/fr/App.java index b91a4bb9..6ca834e2 100644 --- a/camel-snake-case-conversion/src/main/java/com/metaxiii/fr/App.java +++ b/camel-snake-case-conversion/src/main/java/com/metaxiii/fr/App.java @@ -19,6 +19,9 @@ public static String convertCamelCaseToSnake(final String input) { } public static String convertCamelCaseToSnakeRegex(final String input) { - return input.replaceAll("([A-Z])(?=[A-Z])", "$1_").replaceAll("([a-z])([A-Z])", "$1_$2").toLowerCase(); + return input + .replaceAll("([A-Z])(?=[A-Z])", "$1_") + .replaceAll("([a-z])([A-Z])", "$1_$2") + .toLowerCase(); } } diff --git a/camel-snake-case-conversion/src/test/java/com/metaxiii/fr/AppTest.java b/camel-snake-case-conversion/src/test/java/com/metaxiii/fr/AppTest.java index 1ed8a121..cd6e8ab4 100644 --- a/camel-snake-case-conversion/src/test/java/com/metaxiii/fr/AppTest.java +++ b/camel-snake-case-conversion/src/test/java/com/metaxiii/fr/AppTest.java @@ -8,16 +8,16 @@ class AppTest { @ParameterizedTest @CsvSource( - value = { - "'',''", - "snakecase,snakecase", - "snake_case,snake_case", - "convertCamelCase,convert_camel_case", - "convertCCamelCase,convert_c_camel_case", - "sn@keCase#,sn@ke_case#", - } - ) - void whenConvertAllLowerCaseString_thenGetUnchangedString_Manual(final String input, final String expected) { + value = { + "'',''", + "snakecase,snakecase", + "snake_case,snake_case", + "convertCamelCase,convert_camel_case", + "convertCCamelCase,convert_c_camel_case", + "sn@keCase#,sn@ke_case#", + }) + void whenConvertAllLowerCaseString_thenGetUnchangedString_Manual( + final String input, final String expected) { Assertions.assertEquals(expected, App.convertCamelCaseToSnake(input)); Assertions.assertEquals(expected, App.convertCamelCaseToSnakeRegex(input)); } diff --git a/convert-joda-time-datetime-sql-timestamp/src/test/java/com/metaxiii/fr/DateTimeAndTimestampConverterTest.java b/convert-joda-time-datetime-sql-timestamp/src/test/java/com/metaxiii/fr/DateTimeAndTimestampConverterTest.java index 4d8844c1..521ccb69 100644 --- a/convert-joda-time-datetime-sql-timestamp/src/test/java/com/metaxiii/fr/DateTimeAndTimestampConverterTest.java +++ b/convert-joda-time-datetime-sql-timestamp/src/test/java/com/metaxiii/fr/DateTimeAndTimestampConverterTest.java @@ -13,7 +13,8 @@ void givenDateTime_whenUsingConstructor_thenConvertToTimestamp() { final long currentTimeMillis = System.currentTimeMillis(); final DateTime dateTime = new DateTime(currentTimeMillis); final Timestamp expectedTimestamp = new Timestamp(currentTimeMillis); - final Timestamp convertedTimestamp = DateTimeAndTimestampConverter.convertToTimestampUsingConstructor(dateTime); + final Timestamp convertedTimestamp = + DateTimeAndTimestampConverter.convertToTimestampUsingConstructor(dateTime); assertEquals(expectedTimestamp, convertedTimestamp); } @@ -22,7 +23,8 @@ void givenDateTime_whenUsingInstant_thenConvertToTimestamp() { final long currentTimeMillis = System.currentTimeMillis(); final DateTime dateTime = new DateTime(currentTimeMillis); final Timestamp expectedTimestamp = new Timestamp(currentTimeMillis); - final Timestamp convertedTimestamp = DateTimeAndTimestampConverter.convertToTimestampUsingInstant(dateTime); + final Timestamp convertedTimestamp = + DateTimeAndTimestampConverter.convertToTimestampUsingInstant(dateTime); assertEquals(expectedTimestamp, convertedTimestamp); } @@ -31,7 +33,8 @@ void givenDateTime_whenUsingLocalDateTime_thenConvertToTimestamp() { final long currentTimeMillis = System.currentTimeMillis(); final DateTime dateTime = new DateTime(currentTimeMillis); final Timestamp expectedTimestamp = new Timestamp(currentTimeMillis); - final Timestamp convertedTimestamp = DateTimeAndTimestampConverter.convertToTimestampUsingLocalDateTime(dateTime); + final Timestamp convertedTimestamp = + DateTimeAndTimestampConverter.convertToTimestampUsingLocalDateTime(dateTime); assertEquals(expectedTimestamp, convertedTimestamp); } @@ -40,7 +43,8 @@ void givenTimestamp_whenUsingConstructor_thenConvertToDateTime() { final long currentTimeMillis = System.currentTimeMillis(); final Timestamp timestamp = new Timestamp(currentTimeMillis); final DateTime expectedDateTime = new DateTime(currentTimeMillis); - final DateTime convertedDateTime = DateTimeAndTimestampConverter.convertToDateTimeUsingConstructor(timestamp); + final DateTime convertedDateTime = + DateTimeAndTimestampConverter.convertToDateTimeUsingConstructor(timestamp); assertEquals(expectedDateTime, convertedDateTime); } @@ -49,7 +53,8 @@ void givenTimestamp_whenUsingInstant_thenConvertToDateTime() { final long currentTimeMillis = System.currentTimeMillis(); final Timestamp timestamp = new Timestamp(currentTimeMillis); final DateTime expectedDateTime = new DateTime(currentTimeMillis); - final DateTime convertedDateTime = DateTimeAndTimestampConverter.convertToDateTimeUsingInstant(timestamp); + final DateTime convertedDateTime = + DateTimeAndTimestampConverter.convertToDateTimeUsingInstant(timestamp); assertEquals(expectedDateTime, convertedDateTime); } @@ -58,7 +63,8 @@ void givenTimestamp_whenUsingLocalDateTime_thenConvertToDateTime() { final long currentTimeMillis = System.currentTimeMillis(); final Timestamp timestamp = new Timestamp(currentTimeMillis); final DateTime expectedDateTime = new DateTime(currentTimeMillis); - final DateTime convertedDateTime = DateTimeAndTimestampConverter.convertToDateTimeUsingLocalDateTime(timestamp); + final DateTime convertedDateTime = + DateTimeAndTimestampConverter.convertToDateTimeUsingLocalDateTime(timestamp); assertEquals(expectedDateTime, convertedDateTime); } } diff --git a/convert-org-w3c-dom-document-string/src/main/java/com/metaxiii/fr/App.java b/convert-org-w3c-dom-document-string/src/main/java/com/metaxiii/fr/App.java index 4e3183f5..4c395167 100644 --- a/convert-org-w3c-dom-document-string/src/main/java/com/metaxiii/fr/App.java +++ b/convert-org-w3c-dom-document-string/src/main/java/com/metaxiii/fr/App.java @@ -22,7 +22,7 @@ public class App { public static final String FRUIT_XML = - """ + """ Apple Red @@ -30,7 +30,8 @@ public class App { 7 """; - public static Document getDocument() throws SAXException, IOException, ParserConfigurationException { + public static Document getDocument() + throws SAXException, IOException, ParserConfigurationException { final DocumentBuilderFactory factory = DocumentBuilderFactory.newDefaultInstance(); return factory.newDocumentBuilder().parse(new InputSource(new StringReader(FRUIT_XML))); } diff --git a/convert-org-w3c-dom-document-string/src/test/java/com/metaxiii/fr/AppTest.java b/convert-org-w3c-dom-document-string/src/test/java/com/metaxiii/fr/AppTest.java index d57171cb..1d8d604d 100644 --- a/convert-org-w3c-dom-document-string/src/test/java/com/metaxiii/fr/AppTest.java +++ b/convert-org-w3c-dom-document-string/src/test/java/com/metaxiii/fr/AppTest.java @@ -7,7 +7,8 @@ class AppTest { - private static final String startXml = """ + private static final String startXml = + """ """; @Test diff --git a/draw-random-hexadecimal-number/src/main/java/com/metaxiii/fr/App.java b/draw-random-hexadecimal-number/src/main/java/com/metaxiii/fr/App.java index 9b5f409f..7d149628 100644 --- a/draw-random-hexadecimal-number/src/main/java/com/metaxiii/fr/App.java +++ b/draw-random-hexadecimal-number/src/main/java/com/metaxiii/fr/App.java @@ -12,7 +12,7 @@ String generateRandomHexUsingRandomNextIntWithInRange(final int lower, final int return Integer.toHexString(randomInt); } - @SuppressWarnings({ "java:S2245" }) + @SuppressWarnings({"java:S2245"}) private static Random getRandom() { return new Random(); } @@ -40,13 +40,15 @@ String generateRandomHexWithCommonsMathRandomDataGenerator(final int len) { return randomDataGenerator.nextHexString(len); } - String generateRandomHexWithCommonsMathRandomDataGeneratorNextIntWithRange(final int lower, final int upper) { + String generateRandomHexWithCommonsMathRandomDataGeneratorNextIntWithRange( + final int lower, final int upper) { final var randomDataGenerator = new RandomDataGenerator(); final var randomInt = randomDataGenerator.nextInt(lower, upper); return Integer.toHexString(randomInt); } - String generateRandomHexWithCommonsMathRandomDataGeneratorSecureNextIntWithRange(final int lower, final int upper) { + String generateRandomHexWithCommonsMathRandomDataGeneratorSecureNextIntWithRange( + final int lower, final int upper) { final var randomDataGenerator = new RandomDataGenerator(); final var randomInt = randomDataGenerator.nextSecureInt(lower, upper); return Integer.toHexString(randomInt); diff --git a/draw-random-hexadecimal-number/src/test/java/com/metaxiii/fr/AppTest.java b/draw-random-hexadecimal-number/src/test/java/com/metaxiii/fr/AppTest.java index fd02a50f..e7f4797e 100644 --- a/draw-random-hexadecimal-number/src/test/java/com/metaxiii/fr/AppTest.java +++ b/draw-random-hexadecimal-number/src/test/java/com/metaxiii/fr/AppTest.java @@ -31,7 +31,8 @@ void itShouldGenerateRandomHexUsingSecureRandomNextInt() { @ParameterizedTest @MethodSource(value = "argumentsProvider") - void itShouldGenerateRandomHexUsingSecureRandomNextIntWithInRange(final int lower, final int upper) { + void itShouldGenerateRandomHexUsingSecureRandomNextIntWithInRange( + final int lower, final int upper) { assertThat(app.generateRandomHexUsingSecureRandomNextIntWithInRange(lower, upper)).isNotNull(); } @@ -41,24 +42,28 @@ void itShouldGenerateRandomHexUsingSecureRandomNextLong() { } @ParameterizedTest - @ValueSource(ints = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }) + @ValueSource(ints = {1, 2, 3, 4, 5, 6, 7, 8, 9}) void itShouldGenerateRandomHexWithCommonsMathRandomDataGenerator(final int len) { assertThat(app.generateRandomHexWithCommonsMathRandomDataGenerator(len)).isNotNull(); } @ParameterizedTest @MethodSource(value = "argumentsProvider") - void itShouldGenerateRandomHexWithCommonsMathRandomDataGeneratorNextIntWithRange(final int lower, final int upper) { - assertThat(app.generateRandomHexWithCommonsMathRandomDataGeneratorNextIntWithRange(lower, upper)).isNotNull(); + void itShouldGenerateRandomHexWithCommonsMathRandomDataGeneratorNextIntWithRange( + final int lower, final int upper) { + assertThat( + app.generateRandomHexWithCommonsMathRandomDataGeneratorNextIntWithRange(lower, upper)) + .isNotNull(); } @ParameterizedTest @MethodSource(value = "argumentsProvider") void itShouldGenerateRandomHexWithCommonsMathRandomDataGeneratorSecureNextIntWithRange( - final int lower, - final int upper - ) { - assertThat(app.generateRandomHexWithCommonsMathRandomDataGeneratorSecureNextIntWithRange(lower, upper)).isNotNull(); + final int lower, final int upper) { + assertThat( + app.generateRandomHexWithCommonsMathRandomDataGeneratorSecureNextIntWithRange( + lower, upper)) + .isNotNull(); } @Test @@ -67,7 +72,7 @@ void itShouldGenerateRandomHexWithStringFormatter() { } @ParameterizedTest - @ValueSource(ints = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }) + @ValueSource(ints = {1, 2, 3, 4, 5, 6, 7, 8, 9}) void itShouldGenerateSecureRandomHexWithCommonsMathRandomDataGenerator(final int len) { assertThat(app.generateSecureRandomHexWithCommonsMathRandomDataGenerator(len)).isNotNull(); } diff --git a/entity-dto-conversion-rest-api/src/main/java/com/metaxiii/fr/entitydtoconversionrestapi/controller/PostController.java b/entity-dto-conversion-rest-api/src/main/java/com/metaxiii/fr/entitydtoconversionrestapi/controller/PostController.java index d9fd48f2..862992cb 100644 --- a/entity-dto-conversion-rest-api/src/main/java/com/metaxiii/fr/entitydtoconversionrestapi/controller/PostController.java +++ b/entity-dto-conversion-rest-api/src/main/java/com/metaxiii/fr/entitydtoconversionrestapi/controller/PostController.java @@ -23,18 +23,18 @@ public class PostController { @GetMapping("{page}/{size}/{sortDir}/{sort}") @ResponseBody public List getPosts( - @PathVariable("page") int page, - @PathVariable("size") int size, - @PathVariable("sortDir") String sortDir, - @PathVariable("sort") String sort - ) { + @PathVariable("page") int page, + @PathVariable("size") int size, + @PathVariable("sortDir") String sortDir, + @PathVariable("sort") String sort) { List posts = postService.getPostsList(page, size, sortDir, sort); return posts.stream().map(this::toDTO).toList(); } private PostDto toDTO(final Post post) { PostDto postDto = modelMapper.map(post, PostDto.class); - postDto.setSubmissionDate(post.getSubmissionDate(), userService.getCurrentUser().getPreference().getTimezone()); + postDto.setSubmissionDate( + post.getSubmissionDate(), userService.getCurrentUser().getPreference().getTimezone()); return postDto; } } diff --git a/entity-dto-conversion-rest-api/src/main/java/com/metaxiii/fr/entitydtoconversionrestapi/model/User.java b/entity-dto-conversion-rest-api/src/main/java/com/metaxiii/fr/entitydtoconversionrestapi/model/User.java index 80a8f199..a571eed0 100644 --- a/entity-dto-conversion-rest-api/src/main/java/com/metaxiii/fr/entitydtoconversionrestapi/model/User.java +++ b/entity-dto-conversion-rest-api/src/main/java/com/metaxiii/fr/entitydtoconversionrestapi/model/User.java @@ -21,6 +21,5 @@ public class User { private String name; - @OneToOne - private Preference preference; + @OneToOne private Preference preference; } diff --git a/entity-dto-conversion-rest-api/src/main/java/com/metaxiii/fr/entitydtoconversionrestapi/service/impl/PostServiceImpl.java b/entity-dto-conversion-rest-api/src/main/java/com/metaxiii/fr/entitydtoconversionrestapi/service/impl/PostServiceImpl.java index 1ffe2028..24ef2c2a 100644 --- a/entity-dto-conversion-rest-api/src/main/java/com/metaxiii/fr/entitydtoconversionrestapi/service/impl/PostServiceImpl.java +++ b/entity-dto-conversion-rest-api/src/main/java/com/metaxiii/fr/entitydtoconversionrestapi/service/impl/PostServiceImpl.java @@ -19,7 +19,8 @@ public class PostServiceImpl implements PostService { private final UserService userService; @Override - public List getPostsList(final int page, final int size, final String sortDir, final String sort) { + public List getPostsList( + final int page, final int size, final String sortDir, final String sort) { PageRequest pageReq = PageRequest.of(page, size, Sort.Direction.fromString(sortDir), sort); Page posts = postRepository.findByUser(userService.getCurrentUser(), pageReq); return posts.getContent(); diff --git a/entity-dto-conversion-rest-api/src/test/java/com/metaxiii/fr/entitydtoconversionrestapi/EntityDtoConversionRestApiApplicationTests.java b/entity-dto-conversion-rest-api/src/test/java/com/metaxiii/fr/entitydtoconversionrestapi/EntityDtoConversionRestApiApplicationTests.java index 010b174e..994ada00 100644 --- a/entity-dto-conversion-rest-api/src/test/java/com/metaxiii/fr/entitydtoconversionrestapi/EntityDtoConversionRestApiApplicationTests.java +++ b/entity-dto-conversion-rest-api/src/test/java/com/metaxiii/fr/entitydtoconversionrestapi/EntityDtoConversionRestApiApplicationTests.java @@ -9,6 +9,7 @@ class EntityDtoConversionRestApiApplicationTests { @Test void contextLoads() { - Assertions.assertDoesNotThrow(() -> EntityDtoConversionRestApiApplication.main(new String[] {})); + Assertions.assertDoesNotThrow( + () -> EntityDtoConversionRestApiApplication.main(new String[] {})); } } diff --git a/entity-dto-conversion-rest-api/src/test/java/com/metaxiii/fr/entitydtoconversionrestapi/controller/PostControllerTest.java b/entity-dto-conversion-rest-api/src/test/java/com/metaxiii/fr/entitydtoconversionrestapi/controller/PostControllerTest.java index 86189be4..42ca4b37 100644 --- a/entity-dto-conversion-rest-api/src/test/java/com/metaxiii/fr/entitydtoconversionrestapi/controller/PostControllerTest.java +++ b/entity-dto-conversion-rest-api/src/test/java/com/metaxiii/fr/entitydtoconversionrestapi/controller/PostControllerTest.java @@ -25,20 +25,20 @@ @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) class PostControllerTest { - @Autowired - private MockMvc mockMvc; + @Autowired private MockMvc mockMvc; @Test void getPosts() throws Exception { final var url = "/0/1/asc/userName"; - final var mvcResult = mockMvc.perform(get(url)).andDo(print()).andExpect(status().isOk()).andReturn(); + final var mvcResult = + mockMvc.perform(get(url)).andDo(print()).andExpect(status().isOk()).andReturn(); final var objectMapper = new JsonMapper(); - Assertions.assertDoesNotThrow(() -> { - final List result = objectMapper.readValue( - mvcResult.getResponse().getContentAsString(), - new TypeReference<>() {} - ); - assertEquals(1, result.size()); - }); + Assertions.assertDoesNotThrow( + () -> { + final List result = + objectMapper.readValue( + mvcResult.getResponse().getContentAsString(), new TypeReference<>() {}); + assertEquals(1, result.size()); + }); } } diff --git a/entity-dto-conversion-rest-api/src/test/java/com/metaxiii/fr/entitydtoconversionrestapi/service/impl/PostServiceImplTest.java b/entity-dto-conversion-rest-api/src/test/java/com/metaxiii/fr/entitydtoconversionrestapi/service/impl/PostServiceImplTest.java index c6bc8f12..1ff3cd0a 100644 --- a/entity-dto-conversion-rest-api/src/test/java/com/metaxiii/fr/entitydtoconversionrestapi/service/impl/PostServiceImplTest.java +++ b/entity-dto-conversion-rest-api/src/test/java/com/metaxiii/fr/entitydtoconversionrestapi/service/impl/PostServiceImplTest.java @@ -16,14 +16,14 @@ @Sql(scripts = "classpath:/init-db/post.sql") class PostServiceImplTest { - @Autowired - private PostServiceImpl postService; + @Autowired private PostServiceImpl postService; @Test void getPostsList() { - assertDoesNotThrow(() -> { - final List postsList = postService.getPostsList(0, 1, "asc", "userName"); - assertEquals(1, postsList.size()); - }); + assertDoesNotThrow( + () -> { + final List postsList = postService.getPostsList(0, 1, "asc", "userName"); + assertEquals(1, postsList.size()); + }); } } diff --git a/error-handling-for-rest-with-spring/src/main/java/com/metaxiii/fr/errorhandlingforrestwithspring/controller/ApiExceptionHandler.java b/error-handling-for-rest-with-spring/src/main/java/com/metaxiii/fr/errorhandlingforrestwithspring/controller/ApiExceptionHandler.java index 13040530..a9f80910 100644 --- a/error-handling-for-rest-with-spring/src/main/java/com/metaxiii/fr/errorhandlingforrestwithspring/controller/ApiExceptionHandler.java +++ b/error-handling-for-rest-with-spring/src/main/java/com/metaxiii/fr/errorhandlingforrestwithspring/controller/ApiExceptionHandler.java @@ -14,10 +14,11 @@ @Slf4j public class ApiExceptionHandler extends ResponseEntityExceptionHandler { - @ExceptionHandler({ AccessDeniedException.class }) + @ExceptionHandler({AccessDeniedException.class}) public ResponseEntity handleAccessDeniedException(Exception ex, WebRequest request) { log.error(ex.getMessage()); log.info(request.toString()); - return new ResponseEntity<>("Access denied message here", new HttpHeaders(), HttpStatus.FORBIDDEN); + return new ResponseEntity<>( + "Access denied message here", new HttpHeaders(), HttpStatus.FORBIDDEN); } } diff --git a/error-handling-for-rest-with-spring/src/main/java/com/metaxiii/fr/errorhandlingforrestwithspring/controller/FooController.java b/error-handling-for-rest-with-spring/src/main/java/com/metaxiii/fr/errorhandlingforrestwithspring/controller/FooController.java index d7a1f40e..6de70d3c 100644 --- a/error-handling-for-rest-with-spring/src/main/java/com/metaxiii/fr/errorhandlingforrestwithspring/controller/FooController.java +++ b/error-handling-for-rest-with-spring/src/main/java/com/metaxiii/fr/errorhandlingforrestwithspring/controller/FooController.java @@ -31,7 +31,7 @@ ResponseEntity findFooThrowsAccessException() throws AccessDeniedException throw new AccessDeniedException("Not allowed here"); } - @ExceptionHandler({ CustomException.class }) + @ExceptionHandler({CustomException.class}) private void handleException() { log.error("une erreur est survenue"); } diff --git a/error-handling-for-rest-with-spring/src/test/java/com/metaxiii/fr/errorhandlingforrestwithspring/controller/ApiExceptionHandlerTest.java b/error-handling-for-rest-with-spring/src/test/java/com/metaxiii/fr/errorhandlingforrestwithspring/controller/ApiExceptionHandlerTest.java index 73f32edb..5b8872e7 100644 --- a/error-handling-for-rest-with-spring/src/test/java/com/metaxiii/fr/errorhandlingforrestwithspring/controller/ApiExceptionHandlerTest.java +++ b/error-handling-for-rest-with-spring/src/test/java/com/metaxiii/fr/errorhandlingforrestwithspring/controller/ApiExceptionHandlerTest.java @@ -23,14 +23,14 @@ public void endEach() { @Test void handleAccessDeniedException() { - assertDoesNotThrow(() -> { - final ResponseEntity custom_exception = apiExceptionHandler.handleAccessDeniedException( - new Exception("custom exception"), - getWebRequest() - ); - assertEquals(403, custom_exception.getStatusCode().value()); - assertEquals("Access denied message here", custom_exception.getBody()); - }); + assertDoesNotThrow( + () -> { + final ResponseEntity customException = + apiExceptionHandler.handleAccessDeniedException( + new Exception("custom exception"), getWebRequest()); + assertEquals(403, customException.getStatusCode().value()); + assertEquals("Access denied message here", customException.getBody()); + }); } private WebRequest getWebRequest() { diff --git a/error-handling-for-rest-with-spring/src/test/java/com/metaxiii/fr/errorhandlingforrestwithspring/controller/FooControllerTest.java b/error-handling-for-rest-with-spring/src/test/java/com/metaxiii/fr/errorhandlingforrestwithspring/controller/FooControllerTest.java index d66529a9..470fa81d 100644 --- a/error-handling-for-rest-with-spring/src/test/java/com/metaxiii/fr/errorhandlingforrestwithspring/controller/FooControllerTest.java +++ b/error-handling-for-rest-with-spring/src/test/java/com/metaxiii/fr/errorhandlingforrestwithspring/controller/FooControllerTest.java @@ -14,8 +14,7 @@ @AutoConfigureMockMvc class FooControllerTest { - @Autowired - private MockMvc mockMvc; + @Autowired private MockMvc mockMvc; @Test void findFoo() throws Exception { diff --git a/gson-convert-jsonarray-hashmap/src/test/java/com/metaxiii/fr/AppTest.java b/gson-convert-jsonarray-hashmap/src/test/java/com/metaxiii/fr/AppTest.java index 5901a5fb..4ae510d8 100644 --- a/gson-convert-jsonarray-hashmap/src/test/java/com/metaxiii/fr/AppTest.java +++ b/gson-convert-jsonarray-hashmap/src/test/java/com/metaxiii/fr/AppTest.java @@ -43,15 +43,12 @@ void itShouldConvertWithStreamsApproach() { } Map convertUsingStreams(final JsonArray jsonArray) { - return StreamSupport - .stream(jsonArray.spliterator(), false) - .map(JsonElement::getAsJsonObject) - .collect( - Collectors.toMap( - jsonObject -> jsonObject.get("name").getAsString(), - jsonObject -> jsonObject.get("age").getAsInt() - ) - ); + return StreamSupport.stream(jsonArray.spliterator(), false) + .map(JsonElement::getAsJsonObject) + .collect( + Collectors.toMap( + jsonObject -> jsonObject.get("name").getAsString(), + jsonObject -> jsonObject.get("age").getAsInt())); } @BeforeEach diff --git a/guava - Join and split/src/test/java/com/metaxiii/fr/GuavaSplitAndJoinTest.java b/guava - Join and split/src/test/java/com/metaxiii/fr/GuavaSplitAndJoinTest.java index 2b49d00b..564e4407 100644 --- a/guava - Join and split/src/test/java/com/metaxiii/fr/GuavaSplitAndJoinTest.java +++ b/guava - Join and split/src/test/java/com/metaxiii/fr/GuavaSplitAndJoinTest.java @@ -34,14 +34,16 @@ void whenConvertMapToString_thenConverted() { @SuppressWarnings("StaticPseudoFunctionalStyleMethod") @Test void whenJoinNestedCollections_thenJoined() { - final var nested = Lists.newArrayList( - Lists.newArrayList("apple", "banana", "orange"), - Lists.newArrayList("cat", "dog", "bird"), - Lists.newArrayList("John", "Jane", "Adam") - ); - final var result = Joiner - .on(";") - .join(Iterables.transform(nested, (Function, String>) input -> Joiner.on("-").join(input))); + final var nested = + Lists.newArrayList( + Lists.newArrayList("apple", "banana", "orange"), + Lists.newArrayList("cat", "dog", "bird"), + Lists.newArrayList("John", "Jane", "Adam")); + final var result = + Joiner.on(";") + .join( + Iterables.transform( + nested, (Function, String>) input -> Joiner.on("-").join(input))); assertTrue(result.contains("apple-banana-orange")); assertTrue(result.contains("cat-dog-bird")); diff --git a/guava cache/src/main/java/com/metaxiii/fr/GuavaCache.java b/guava cache/src/main/java/com/metaxiii/fr/GuavaCache.java index 0dd3f3ef..a65f4bdf 100644 --- a/guava cache/src/main/java/com/metaxiii/fr/GuavaCache.java +++ b/guava cache/src/main/java/com/metaxiii/fr/GuavaCache.java @@ -9,11 +9,12 @@ public class GuavaCache { private final CacheLoader loader; public GuavaCache() { - loader = new CacheLoader<>() { - @Override - public String load(String key) { - return key.toUpperCase(); - } - }; + loader = + new CacheLoader<>() { + @Override + public String load(String key) { + return key.toUpperCase(); + } + }; } } diff --git a/guava cache/src/test/java/com/metaxiii/fr/GuavaCacheTest.java b/guava cache/src/test/java/com/metaxiii/fr/GuavaCacheTest.java index 49b5ab09..d98d9299 100644 --- a/guava cache/src/test/java/com/metaxiii/fr/GuavaCacheTest.java +++ b/guava cache/src/test/java/com/metaxiii/fr/GuavaCacheTest.java @@ -11,10 +11,10 @@ import com.google.common.cache.RemovalCause; import com.google.common.cache.RemovalListener; import com.google.common.cache.Weigher; +import java.time.Duration; import java.util.HashMap; import java.util.Map; import java.util.Optional; -import java.util.concurrent.TimeUnit; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -56,7 +56,11 @@ void whenCacheReachMaxSize_thenEviction() { @Test void whenCacheReachMaxWeight_thenEviction() { final Weigher weighByLength = (key, value) -> value.length(); - final var cache = CacheBuilder.newBuilder().maximumWeight(16).weigher(weighByLength).build(guavaCache.getLoader()); + final var cache = + CacheBuilder.newBuilder() + .maximumWeight(16) + .weigher(weighByLength) + .build(guavaCache.getLoader()); cache.getUnchecked("first"); cache.getUnchecked("second"); cache.getUnchecked("third"); @@ -68,10 +72,10 @@ void whenCacheReachMaxWeight_thenEviction() { @Test void whenEntryIdle_thenEviction() throws InterruptedException { - final var cache = CacheBuilder - .newBuilder() - .expireAfterAccess(2, TimeUnit.MILLISECONDS) - .build(guavaCache.getLoader()); + final var cache = + CacheBuilder.newBuilder() + .expireAfterAccess(Duration.ofMillis(2)) + .build(guavaCache.getLoader()); cache.getUnchecked("hello"); assertEquals(1, cache.size()); cache.getUnchecked("hello"); @@ -83,10 +87,10 @@ void whenEntryIdle_thenEviction() throws InterruptedException { @Test void whenEntryLiveTimeExpire_thenEviction() throws InterruptedException { - final var cache = CacheBuilder - .newBuilder() - .expireAfterWrite(2, TimeUnit.MILLISECONDS) - .build(guavaCache.getLoader()); + final var cache = + CacheBuilder.newBuilder() + .expireAfterWrite(Duration.ofMillis(2)) + .build(guavaCache.getLoader()); cache.getUnchecked("hello"); assertEquals(1, cache.size()); Thread.sleep(300); @@ -111,12 +115,12 @@ void whenSoftValue_thenRemoveFromCache() { void whenNullValue_thenOptional() { CacheLoader> loader; loader = - new CacheLoader<>() { - @Override - public Optional load(String key) { - return Optional.ofNullable(getSuffix(key)); - } - }; + new CacheLoader<>() { + @Override + public Optional load(String key) { + return Optional.ofNullable(getSuffix(key)); + } + }; LoadingCache> cache; cache = CacheBuilder.newBuilder().build(loader); assertEquals("txt", cache.getUnchecked("text.txt").orElse(null)); @@ -125,7 +129,10 @@ public Optional load(String key) { @Test void whenLiveTimeEnd_thenRefresh() { - final var cache = CacheBuilder.newBuilder().refreshAfterWrite(1, TimeUnit.MINUTES).build(guavaCache.getLoader()); + final var cache = + CacheBuilder.newBuilder() + .refreshAfterWrite(Duration.ofMinutes(1)) + .build(guavaCache.getLoader()); assertNotNull(cache); } @@ -143,13 +150,17 @@ void whenPreloadCache_thenUsePutAll() { void whenEntryRemovedFromCache_thenNotify() { final RemovalListener listener; listener = - n -> { - if (n.wasEvicted()) { - String cause = n.getCause().name(); - assertEquals(RemovalCause.SIZE.toString(), cause); - } - }; - final var cache = CacheBuilder.newBuilder().maximumSize(3).removalListener(listener).build(guavaCache.getLoader()); + n -> { + if (n.wasEvicted()) { + String cause = n.getCause().name(); + assertEquals(RemovalCause.SIZE.toString(), cause); + } + }; + final var cache = + CacheBuilder.newBuilder() + .maximumSize(3) + .removalListener(listener) + .build(guavaCache.getLoader()); cache.getUnchecked("first"); cache.getUnchecked("second"); cache.getUnchecked("third"); diff --git a/gzip-compress-create-byte-array/src/test/java/com/metaxiii/fr/AppTest.java b/gzip-compress-create-byte-array/src/test/java/com/metaxiii/fr/AppTest.java index 78e66167..df9649ad 100644 --- a/gzip-compress-create-byte-array/src/test/java/com/metaxiii/fr/AppTest.java +++ b/gzip-compress-create-byte-array/src/test/java/com/metaxiii/fr/AppTest.java @@ -18,7 +18,7 @@ public class AppTest { @Test void whenCompressingUsingGZip_thenGetCompressedByteArray() throws IOException { final String payload = - """ + """ This is a sample text to test method gzip. The gzip algorithm will compress this string. The result will be smaller than this string. """; diff --git a/hibernate-reactive/src/main/java/com/metaxiii/fr/hibernatereactive/configuration/R2DBCConfiguration.java b/hibernate-reactive/src/main/java/com/metaxiii/fr/hibernatereactive/configuration/R2DBCConfiguration.java index 4f612252..8a63213b 100644 --- a/hibernate-reactive/src/main/java/com/metaxiii/fr/hibernatereactive/configuration/R2DBCConfiguration.java +++ b/hibernate-reactive/src/main/java/com/metaxiii/fr/hibernatereactive/configuration/R2DBCConfiguration.java @@ -3,7 +3,6 @@ import io.r2dbc.h2.H2ConnectionConfiguration; import io.r2dbc.h2.H2ConnectionFactory; import io.r2dbc.spi.ConnectionFactory; - import org.jspecify.annotations.NonNull; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -23,8 +22,10 @@ public class R2DBCConfiguration extends AbstractR2dbcConfiguration { @Override public H2ConnectionFactory connectionFactory() { return new H2ConnectionFactory( - H2ConnectionConfiguration.builder().url("mem:testdb;DB_CLOSE_DELAY=-1;TRACE_LEVEL_FILE=4;").username("sa").build() - ); + H2ConnectionConfiguration.builder() + .url("mem:testdb;DB_CLOSE_DELAY=-1;TRACE_LEVEL_FILE=4;") + .username("sa") + .build()); } @Bean diff --git a/hibernate-reactive/src/main/java/com/metaxiii/fr/hibernatereactive/entity/Product.java b/hibernate-reactive/src/main/java/com/metaxiii/fr/hibernatereactive/entity/Product.java index d1122f23..3aa8c169 100644 --- a/hibernate-reactive/src/main/java/com/metaxiii/fr/hibernatereactive/entity/Product.java +++ b/hibernate-reactive/src/main/java/com/metaxiii/fr/hibernatereactive/entity/Product.java @@ -14,8 +14,7 @@ @AllArgsConstructor public class Product { - @Id - private Long id; + @Id private Long id; private String name; private String category; diff --git a/hibernate-reactive/src/test/java/com/metaxiii/fr/hibernatereactive/service/ProductServiceTest.java b/hibernate-reactive/src/test/java/com/metaxiii/fr/hibernatereactive/service/ProductServiceTest.java index 4adcdae6..f3dfa305 100644 --- a/hibernate-reactive/src/test/java/com/metaxiii/fr/hibernatereactive/service/ProductServiceTest.java +++ b/hibernate-reactive/src/test/java/com/metaxiii/fr/hibernatereactive/service/ProductServiceTest.java @@ -12,23 +12,21 @@ import org.springframework.boot.test.context.SpringBootTest; import reactor.test.StepVerifier; -@SpringBootTest(classes = { R2DBCConfiguration.class, ProductService.class, ProductRepository.class }) +@SpringBootTest(classes = {R2DBCConfiguration.class, ProductService.class, ProductRepository.class}) class ProductServiceTest { - @Autowired - private ProductService productService; + @Autowired private ProductService productService; - @Autowired - private ProductRepository productRepository; + @Autowired private ProductRepository productRepository; @BeforeEach void beforeEach() { productRepository - .deleteAll() - .then(productRepository.save(new Product(1L, "Product 1", "Category 1", 10.0))) - .then(productRepository.save(new Product(2L, "Product 2", "Category 2", 15.0))) - .then(productRepository.save(new Product(3L, "Product 3", "Category 3", 20.0))) - .block(); + .deleteAll() + .then(productRepository.save(new Product(1L, "Product 1", "Category 1", 10.0))) + .then(productRepository.save(new Product(2L, "Product 2", "Category 2", 15.0))) + .then(productRepository.save(new Product(3L, "Product 3", "Category 3", 20.0))) + .block(); } @Test @@ -39,13 +37,13 @@ void testFindAll() { @Test void testSave() { final Product newProduct = new Product(4L, "Product 4", "Category 4", 24.0); - StepVerifier - .create(productService.save(newProduct)) - .assertNext(product -> { - assertNotNull(product.getId()); - assertEquals("Product 4", product.getName()); - }) - .verifyComplete(); + StepVerifier.create(productService.save(newProduct)) + .assertNext( + product -> { + assertNotNull(product.getId()); + assertEquals("Product 4", product.getName()); + }) + .verifyComplete(); StepVerifier.create(productService.findAll()).expectNextCount(4).verifyComplete(); } diff --git a/implement-builder-pattern/src/main/java/com/metaxiii/fr/model/GenericBuilder.java b/implement-builder-pattern/src/main/java/com/metaxiii/fr/model/GenericBuilder.java index 43ff39be..0410a265 100644 --- a/implement-builder-pattern/src/main/java/com/metaxiii/fr/model/GenericBuilder.java +++ b/implement-builder-pattern/src/main/java/com/metaxiii/fr/model/GenericBuilder.java @@ -20,10 +20,11 @@ public T build() { } public

GenericBuilder with(final BiConsumer consumer, final P value) { - return new GenericBuilder<>(() -> { - final T obj = supplier.get(); - consumer.accept(obj, value); - return obj; - }); + return new GenericBuilder<>( + () -> { + final T obj = supplier.get(); + consumer.accept(obj, value); + return obj; + }); } } diff --git a/implement-builder-pattern/src/test/java/com/metaxiii/fr/PostTest.java b/implement-builder-pattern/src/test/java/com/metaxiii/fr/PostTest.java index 5f869ae2..2c70cfb6 100644 --- a/implement-builder-pattern/src/test/java/com/metaxiii/fr/PostTest.java +++ b/implement-builder-pattern/src/test/java/com/metaxiii/fr/PostTest.java @@ -26,12 +26,12 @@ void itShouldCreatePost() { @Test void itShouldCreatePostWithGenericBuilder() { - final var post = GenericBuilder - .of(GenericPost::new) - .with(GenericPost::setTitle, TITLE) - .with(GenericPost::setText, TEXT) - .with(GenericPost::setCategory, CATEGORY) - .build(); + final var post = + GenericBuilder.of(GenericPost::new) + .with(GenericPost::setTitle, TITLE) + .with(GenericPost::setText, TEXT) + .with(GenericPost::setCategory, CATEGORY) + .build(); assertEquals(TITLE, post.getTitle()); assertEquals(TEXT, post.getText()); assertEquals(CATEGORY, post.getCategory()); @@ -61,8 +61,9 @@ void itShouldCreatePostWithPersonalAndCustomValidators() { assertThrows(NullPointerException.class, () -> getPersonalPost(true, true, false)); } - private static void getPersonalPost(final boolean title, final boolean text, final boolean category) - throws IllegalAccessException { + private static void getPersonalPost( + final boolean title, final boolean text, final boolean category) + throws IllegalAccessException { if (!title && !text && !category) { PersonalPost.builder().build(); } diff --git a/initial-name/src/main/java/com/metaxiii/fr/App.java b/initial-name/src/main/java/com/metaxiii/fr/App.java index 51332d6f..43afc945 100644 --- a/initial-name/src/main/java/com/metaxiii/fr/App.java +++ b/initial-name/src/main/java/com/metaxiii/fr/App.java @@ -39,12 +39,11 @@ String getInitialUsingStreamsAPI(final String name) { if (name == null || name.isEmpty()) { return ""; } - return Arrays - .stream(name.split("\\s+")) - .filter(part -> part.matches("[a-zA-Z].*")) - .map(part -> part.substring(0, 1)) - .collect(Collectors.joining()) - .toUpperCase(); + return Arrays.stream(name.split("\\s+")) + .filter(part -> part.matches("[a-zA-Z].*")) + .map(part -> part.substring(0, 1)) + .collect(Collectors.joining()) + .toUpperCase(); } String getInitialUsingStringTokenizer(final String name) { diff --git a/initial-name/src/test/java/com/metaxiii/fr/AppTest.java b/initial-name/src/test/java/com/metaxiii/fr/AppTest.java index a235695a..4539890e 100644 --- a/initial-name/src/test/java/com/metaxiii/fr/AppTest.java +++ b/initial-name/src/test/java/com/metaxiii/fr/AppTest.java @@ -16,72 +16,64 @@ public void beforeEach() { } @ParameterizedTest - @CsvSource( - { - "John F Kennedy,JFK", - ",''", - "'',''", - "Not Correct 88text,NC", - "michael jackson,MJ", - "123,''", - "123 234A,''", - "1test 2test, ''", - } - ) + @CsvSource({ + "John F Kennedy,JFK", + ",''", + "'',''", + "Not Correct 88text,NC", + "michael jackson,MJ", + "123,''", + "123 234A,''", + "1test 2test, ''", + }) void getInitialFromName_usingLoop(final String input, final String expected) { final String initial = app.getInitialUsingLoop(input); assertEquals(expected, initial); } @ParameterizedTest - @CsvSource( - { - "John F Kennedy,JFK", - ",''", - "'',''", - "Not Correct 88text,NC", - "michael jackson,MJ", - "123,''", - "123 234A,''", - "1test 2test, ''", - } - ) + @CsvSource({ + "John F Kennedy,JFK", + ",''", + "'',''", + "Not Correct 88text,NC", + "michael jackson,MJ", + "123,''", + "123 234A,''", + "1test 2test, ''", + }) void getInitialUsingRegex(final String input, final String expected) { final String initial = app.getInitialUsingRegex(input); assertEquals(expected, initial); } @ParameterizedTest - @CsvSource( - { - "John F Kennedy,JFK", - ",''", - "'',''", - "Not Correct 88text,NC", - "michael jackson,MJ", - "123,''", - "123 234A,''", - "1test 2test, ''", - } - ) + @CsvSource({ + "John F Kennedy,JFK", + ",''", + "'',''", + "Not Correct 88text,NC", + "michael jackson,MJ", + "123,''", + "123 234A,''", + "1test 2test, ''", + }) void getInitialUsingStreamsAPI(final String input, final String expected) { final String initial = app.getInitialUsingStreamsAPI(input); assertEquals(expected, initial); } @ParameterizedTest - @CsvSource( - { - "John F Kennedy,JFK", - ",''", - "'',''", - "Not Correct 88text,NC", - "michael jackson,MJ", - "123,''", - "123 234A,''", - "1test 2test, ''", - } - ) + @CsvSource({ + "John F Kennedy,JFK", + ",''", + "'',''", + "Not Correct 88text,NC", + "michael jackson,MJ", + "123,''", + "123 234A,''", + "1test 2test, ''", + }) void getInitialUsingStringTokenizer(final String input, final String expected) { final String initial = app.getInitialUsingStringTokenizer(input); assertEquals(expected, initial); diff --git a/intro-jfreechart/src/main/java/com/metaxiii/fr/App.java b/intro-jfreechart/src/main/java/com/metaxiii/fr/App.java index 087c94ef..7d1ba096 100644 --- a/intro-jfreechart/src/main/java/com/metaxiii/fr/App.java +++ b/intro-jfreechart/src/main/java/com/metaxiii/fr/App.java @@ -70,15 +70,9 @@ private static void getTimeSeriesChart() { final TimeSeriesCollection dataset = new TimeSeriesCollection(); dataset.addSeries(series); - final JFreeChart chart = ChartFactory.createTimeSeriesChart( - MONTHLY_SALES, - "Date", - SALES, - dataset, - true, - false, - false - ); + final JFreeChart chart = + ChartFactory.createTimeSeriesChart( + MONTHLY_SALES, "Date", SALES, dataset, true, false, false); renderPanel(chart); } diff --git a/jackson-annotations/src/main/java/com/metaxiii/fr/config/CustomAnnotation.java b/jackson-annotations/src/main/java/com/metaxiii/fr/config/CustomAnnotation.java index 24508688..2e14cb80 100644 --- a/jackson-annotations/src/main/java/com/metaxiii/fr/config/CustomAnnotation.java +++ b/jackson-annotations/src/main/java/com/metaxiii/fr/config/CustomAnnotation.java @@ -9,6 +9,5 @@ @Retention(RetentionPolicy.RUNTIME) @JacksonAnnotationsInside @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonPropertyOrder({ "name", "id", "dateCreated" }) -public @interface CustomAnnotation { -} +@JsonPropertyOrder({"name", "id", "dateCreated"}) +public @interface CustomAnnotation {} diff --git a/jackson-annotations/src/main/java/com/metaxiii/fr/config/CustomDateDeSerializer.java b/jackson-annotations/src/main/java/com/metaxiii/fr/config/CustomDateDeSerializer.java index 82c27939..28145392 100644 --- a/jackson-annotations/src/main/java/com/metaxiii/fr/config/CustomDateDeSerializer.java +++ b/jackson-annotations/src/main/java/com/metaxiii/fr/config/CustomDateDeSerializer.java @@ -21,8 +21,9 @@ public CustomDateDeSerializer(Class vc) { } @Override - public Date deserialize(final JsonParser jsonParser, final DeserializationContext deserializationContext) - throws IOException { + public Date deserialize( + final JsonParser jsonParser, final DeserializationContext deserializationContext) + throws IOException { String date = jsonParser.getText(); try { return formatter.parse(date); diff --git a/jackson-annotations/src/main/java/com/metaxiii/fr/config/CustomDateSerializer.java b/jackson-annotations/src/main/java/com/metaxiii/fr/config/CustomDateSerializer.java index 68dc1711..a7f658ac 100644 --- a/jackson-annotations/src/main/java/com/metaxiii/fr/config/CustomDateSerializer.java +++ b/jackson-annotations/src/main/java/com/metaxiii/fr/config/CustomDateSerializer.java @@ -21,10 +21,10 @@ public CustomDateSerializer(Class t) { @Override public void serialize( - final Date date, - final JsonGenerator jsonGenerator, - final SerializerProvider serializerProvider - ) throws IOException { + final Date date, + final JsonGenerator jsonGenerator, + final SerializerProvider serializerProvider) + throws IOException { jsonGenerator.writeString(formatter.format(date)); } } diff --git a/jackson-annotations/src/main/java/com/metaxiii/fr/enums/TypeEnumWithValue.java b/jackson-annotations/src/main/java/com/metaxiii/fr/enums/TypeEnumWithValue.java index ffc7bff7..ce9336bb 100644 --- a/jackson-annotations/src/main/java/com/metaxiii/fr/enums/TypeEnumWithValue.java +++ b/jackson-annotations/src/main/java/com/metaxiii/fr/enums/TypeEnumWithValue.java @@ -9,8 +9,7 @@ public enum TypeEnumWithValue { TYPE1(1, "Type A"), TYPE2(2, "Type B"); - @Getter - private final Integer id; + @Getter private final Integer id; private final String name; diff --git a/jackson-annotations/src/main/java/com/metaxiii/fr/model/AliasBean.java b/jackson-annotations/src/main/java/com/metaxiii/fr/model/AliasBean.java index ce62ef41..37629574 100644 --- a/jackson-annotations/src/main/java/com/metaxiii/fr/model/AliasBean.java +++ b/jackson-annotations/src/main/java/com/metaxiii/fr/model/AliasBean.java @@ -10,7 +10,7 @@ @NoArgsConstructor public class AliasBean { - @JsonAlias({ "fName", "f_name" }) + @JsonAlias({"fName", "f_name"}) private String firstName; private String lastName; diff --git a/jackson-annotations/src/main/java/com/metaxiii/fr/model/BeanWithCreator.java b/jackson-annotations/src/main/java/com/metaxiii/fr/model/BeanWithCreator.java index 911b9c8b..6fddbac2 100644 --- a/jackson-annotations/src/main/java/com/metaxiii/fr/model/BeanWithCreator.java +++ b/jackson-annotations/src/main/java/com/metaxiii/fr/model/BeanWithCreator.java @@ -13,7 +13,8 @@ public class BeanWithCreator { private String name; @JsonCreator - public BeanWithCreator(@JsonProperty("custom_id") int id, @JsonProperty("custom_name") String name) { + public BeanWithCreator( + @JsonProperty("custom_id") int id, @JsonProperty("custom_name") String name) { this.id = id; this.name = name; } diff --git a/jackson-annotations/src/main/java/com/metaxiii/fr/model/BeanWithIgnore.java b/jackson-annotations/src/main/java/com/metaxiii/fr/model/BeanWithIgnore.java index 6bf6346a..232b82e6 100644 --- a/jackson-annotations/src/main/java/com/metaxiii/fr/model/BeanWithIgnore.java +++ b/jackson-annotations/src/main/java/com/metaxiii/fr/model/BeanWithIgnore.java @@ -6,7 +6,7 @@ import lombok.Getter; import lombok.Setter; -@JsonIgnoreProperties({ "id" }) +@JsonIgnoreProperties({"id"}) @Getter @Setter @AllArgsConstructor @@ -15,6 +15,5 @@ public class BeanWithIgnore { private int id; private String name; - @JsonIgnore - private int otherId; + @JsonIgnore private int otherId; } diff --git a/jackson-annotations/src/main/java/com/metaxiii/fr/model/BeanWithInject.java b/jackson-annotations/src/main/java/com/metaxiii/fr/model/BeanWithInject.java index 5496c571..a72cd9e4 100644 --- a/jackson-annotations/src/main/java/com/metaxiii/fr/model/BeanWithInject.java +++ b/jackson-annotations/src/main/java/com/metaxiii/fr/model/BeanWithInject.java @@ -10,8 +10,7 @@ @RequiredArgsConstructor public class BeanWithInject { - @JacksonInject - private int id; + @JacksonInject private int id; private String name; } diff --git a/jackson-annotations/src/main/java/com/metaxiii/fr/model/ItemWithRef.java b/jackson-annotations/src/main/java/com/metaxiii/fr/model/ItemWithRef.java index 7fff5e9b..4b640888 100644 --- a/jackson-annotations/src/main/java/com/metaxiii/fr/model/ItemWithRef.java +++ b/jackson-annotations/src/main/java/com/metaxiii/fr/model/ItemWithRef.java @@ -13,6 +13,5 @@ public class ItemWithRef { private int id; private String name; - @JsonManagedReference - public UserWithRef owner; + @JsonManagedReference public UserWithRef owner; } diff --git a/jackson-annotations/src/main/java/com/metaxiii/fr/model/MyBean.java b/jackson-annotations/src/main/java/com/metaxiii/fr/model/MyBean.java index b943da96..38508769 100644 --- a/jackson-annotations/src/main/java/com/metaxiii/fr/model/MyBean.java +++ b/jackson-annotations/src/main/java/com/metaxiii/fr/model/MyBean.java @@ -12,12 +12,11 @@ @Setter @AllArgsConstructor @RequiredArgsConstructor -@JsonPropertyOrder({ "custom_name", "id" }) +@JsonPropertyOrder({"custom_name", "id"}) @JsonInclude(JsonInclude.Include.NON_NULL) public class MyBean { - @Getter - private int id; + @Getter private int id; private String name; diff --git a/jackson-annotations/src/main/java/com/metaxiii/fr/model/MyBeanDuplicated.java b/jackson-annotations/src/main/java/com/metaxiii/fr/model/MyBeanDuplicated.java index 29ce6b42..7ead27cf 100644 --- a/jackson-annotations/src/main/java/com/metaxiii/fr/model/MyBeanDuplicated.java +++ b/jackson-annotations/src/main/java/com/metaxiii/fr/model/MyBeanDuplicated.java @@ -12,12 +12,11 @@ @Setter @AllArgsConstructor @RequiredArgsConstructor -@JsonPropertyOrder({ "custom_name", "id" }) +@JsonPropertyOrder({"custom_name", "id"}) @JsonInclude(JsonInclude.Include.NON_NULL) public class MyBeanDuplicated { - @Getter - private int id; + @Getter private int id; private String name; diff --git a/jackson-annotations/src/main/java/com/metaxiii/fr/model/RawBean.java b/jackson-annotations/src/main/java/com/metaxiii/fr/model/RawBean.java index 8de0f269..6d27c104 100644 --- a/jackson-annotations/src/main/java/com/metaxiii/fr/model/RawBean.java +++ b/jackson-annotations/src/main/java/com/metaxiii/fr/model/RawBean.java @@ -12,6 +12,5 @@ public class RawBean { private String name; - @JsonRawValue - private String json; + @JsonRawValue private String json; } diff --git a/jackson-annotations/src/main/java/com/metaxiii/fr/model/UnwrappedUser.java b/jackson-annotations/src/main/java/com/metaxiii/fr/model/UnwrappedUser.java index a39ef250..93938d79 100644 --- a/jackson-annotations/src/main/java/com/metaxiii/fr/model/UnwrappedUser.java +++ b/jackson-annotations/src/main/java/com/metaxiii/fr/model/UnwrappedUser.java @@ -12,8 +12,7 @@ public class UnwrappedUser { private int id; - @JsonUnwrapped - private Name name; + @JsonUnwrapped private Name name; @AllArgsConstructor @Getter diff --git a/jackson-annotations/src/main/java/com/metaxiii/fr/model/UserWithRef.java b/jackson-annotations/src/main/java/com/metaxiii/fr/model/UserWithRef.java index 0b68ccb6..13f25178 100644 --- a/jackson-annotations/src/main/java/com/metaxiii/fr/model/UserWithRef.java +++ b/jackson-annotations/src/main/java/com/metaxiii/fr/model/UserWithRef.java @@ -13,8 +13,7 @@ public class UserWithRef { private int id; private String name; - @JsonBackReference - public List userItems; + @JsonBackReference public List userItems; public UserWithRef(final int id, final String name) { this.id = id; diff --git a/jackson-annotations/src/test/java/com/metaxiii/fr/model/BeanWithFilterTest.java b/jackson-annotations/src/test/java/com/metaxiii/fr/model/BeanWithFilterTest.java index d4f0f005..61539fa0 100644 --- a/jackson-annotations/src/test/java/com/metaxiii/fr/model/BeanWithFilterTest.java +++ b/jackson-annotations/src/test/java/com/metaxiii/fr/model/BeanWithFilterTest.java @@ -15,8 +15,9 @@ class BeanWithFilterTest { @Test void whenSerializingUsingJsonFilter_thenCorrect() throws JsonProcessingException { BeanWithFilter bean = new BeanWithFilter(1, "My bean"); - FilterProvider filters = new SimpleFilterProvider() - .addFilter("myFilter", SimpleBeanPropertyFilter.filterOutAllExcept("name")); + FilterProvider filters = + new SimpleFilterProvider() + .addFilter("myFilter", SimpleBeanPropertyFilter.filterOutAllExcept("name")); String result = new ObjectMapper().writer(filters).writeValueAsString(bean); System.out.println(result); assertTrue(result.contains("My bean")); diff --git a/jackson-annotations/src/test/java/com/metaxiii/fr/model/BeanWithInjectTest.java b/jackson-annotations/src/test/java/com/metaxiii/fr/model/BeanWithInjectTest.java index 47173bb8..b891c926 100644 --- a/jackson-annotations/src/test/java/com/metaxiii/fr/model/BeanWithInjectTest.java +++ b/jackson-annotations/src/test/java/com/metaxiii/fr/model/BeanWithInjectTest.java @@ -13,7 +13,8 @@ class BeanWithInjectTest { void whenDeserializingUsingJsonInject_thenCorrect() throws IOException { String json = "{\"name\":\"My bean\"}"; InjectableValues inject = new InjectableValues.Std().addValue(int.class, 1); - BeanWithInject bean = new ObjectMapper().reader(inject).forType(BeanWithInject.class).readValue(json); + BeanWithInject bean = + new ObjectMapper().reader(inject).forType(BeanWithInject.class).readValue(json); assertEquals("My bean", bean.getName()); assertEquals(1, bean.getId()); } diff --git a/jackson-annotations/src/test/java/com/metaxiii/fr/model/EventWithSerializerTest.java b/jackson-annotations/src/test/java/com/metaxiii/fr/model/EventWithSerializerTest.java index 092d56cf..bb09a609 100644 --- a/jackson-annotations/src/test/java/com/metaxiii/fr/model/EventWithSerializerTest.java +++ b/jackson-annotations/src/test/java/com/metaxiii/fr/model/EventWithSerializerTest.java @@ -14,7 +14,8 @@ class EventWithSerializerTest { @Test - void whenSerializingUsingJsonSerialize_thenCorrect() throws JsonProcessingException, ParseException { + void whenSerializingUsingJsonSerialize_thenCorrect() + throws JsonProcessingException, ParseException { SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss"); String toParse = "20-12-2014 02:30:00"; Date date = df.parse(toParse); @@ -28,7 +29,8 @@ void whenSerializingUsingJsonSerialize_thenCorrect() throws JsonProcessingExcept void whenDeserializingUsingJsonDeserialize_thenCorrect() throws IOException { String json = "{\"name\":\"party\",\"eventDate\":\"20-12-2014 02:30:00\"}"; SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss"); - EventWithSerializer event = new ObjectMapper().readerFor(EventWithSerializer.class).readValue(json); + EventWithSerializer event = + new ObjectMapper().readerFor(EventWithSerializer.class).readValue(json); assertEquals("20-12-2014 02:30:00", df.format(event.eventDate)); } } diff --git a/jackson-annotations/src/test/java/com/metaxiii/fr/model/Zoo.java b/jackson-annotations/src/test/java/com/metaxiii/fr/model/Zoo.java index 99a5c2aa..f5b61549 100644 --- a/jackson-annotations/src/test/java/com/metaxiii/fr/model/Zoo.java +++ b/jackson-annotations/src/test/java/com/metaxiii/fr/model/Zoo.java @@ -13,9 +13,10 @@ public class Zoo { public Animal animal; @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type") - @JsonSubTypes( - { @JsonSubTypes.Type(value = Dog.class, name = "dog"), @JsonSubTypes.Type(value = Cat.class, name = "cat") } - ) + @JsonSubTypes({ + @JsonSubTypes.Type(value = Dog.class, name = "dog"), + @JsonSubTypes.Type(value = Cat.class, name = "cat") + }) @AllArgsConstructor @NoArgsConstructor public static class Animal { diff --git a/jackson-date/src/test/java/com/metaxiii/fr/JacksonDateTest.java b/jackson-date/src/test/java/com/metaxiii/fr/JacksonDateTest.java index 06b01339..9b967df5 100644 --- a/jackson-date/src/test/java/com/metaxiii/fr/JacksonDateTest.java +++ b/jackson-date/src/test/java/com/metaxiii/fr/JacksonDateTest.java @@ -24,7 +24,8 @@ class JacksonDateTest { @Test - void whenSerializingDateWithJackson_thenSerializedToTimestamp() throws JsonProcessingException, ParseException { + void whenSerializingDateWithJackson_thenSerializedToTimestamp() + throws JsonProcessingException, ParseException { SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy hh:mm"); df.setTimeZone(TimeZone.getTimeZone("UTC")); Date date = df.parse("01-01-1970 01:00"); @@ -34,7 +35,8 @@ void whenSerializingDateWithJackson_thenSerializedToTimestamp() throws JsonProce } @Test - void whenSerializingDateToISO8601_thenSerializedToText() throws JsonProcessingException, ParseException { + void whenSerializingDateToISO8601_thenSerializedToText() + throws JsonProcessingException, ParseException { SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy hh:mm"); df.setTimeZone(TimeZone.getTimeZone("UTC")); String toParse = "01-01-1970 02:30"; @@ -48,7 +50,8 @@ void whenSerializingDateToISO8601_thenSerializedToText() throws JsonProcessingEx } @Test - void whenSettingObjectMapperDateFormat_thenCorrect() throws JsonProcessingException, ParseException { + void whenSettingObjectMapperDateFormat_thenCorrect() + throws JsonProcessingException, ParseException { SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy hh:mm"); String toParse = "20-12-2014 02:30"; Date date = df.parse(toParse); @@ -60,7 +63,8 @@ void whenSettingObjectMapperDateFormat_thenCorrect() throws JsonProcessingExcept } @Test - void whenUsingJsonFormatAnnotationToFormatDate_thenCorrect() throws JsonProcessingException, ParseException { + void whenUsingJsonFormatAnnotationToFormatDate_thenCorrect() + throws JsonProcessingException, ParseException { SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss"); df.setTimeZone(TimeZone.getTimeZone("UTC")); String toParse = "20-12-2014 02:30:00"; @@ -126,7 +130,8 @@ private CustomDateSerializer(Class t) { } @Override - public void serialize(Date value, JsonGenerator gen, SerializerProvider arg2) throws IOException { + public void serialize(Date value, JsonGenerator gen, SerializerProvider arg2) + throws IOException { gen.writeString(FORMATTER.format(value)); } } diff --git a/jackson-json-view/src/main/java/com/metaxiii/fr/config/MyBeanSerializerModifier.java b/jackson-json-view/src/main/java/com/metaxiii/fr/config/MyBeanSerializerModifier.java index fa1a43c6..da6d3f9c 100644 --- a/jackson-json-view/src/main/java/com/metaxiii/fr/config/MyBeanSerializerModifier.java +++ b/jackson-json-view/src/main/java/com/metaxiii/fr/config/MyBeanSerializerModifier.java @@ -10,10 +10,9 @@ public class MyBeanSerializerModifier extends BeanSerializerModifier { @Override public List changeProperties( - SerializationConfig config, - BeanDescription beanDesc, - List beanProperties - ) { + SerializationConfig config, + BeanDescription beanDesc, + List beanProperties) { for (int i = 0; i < beanProperties.size(); i++) { BeanPropertyWriter writer = beanProperties.get(i); if ("name".equals(writer.getName())) { diff --git a/jackson-json-view/src/main/java/com/metaxiii/fr/config/UpperCasingWriter.java b/jackson-json-view/src/main/java/com/metaxiii/fr/config/UpperCasingWriter.java index a9ecc7d6..5e8ef7d4 100644 --- a/jackson-json-view/src/main/java/com/metaxiii/fr/config/UpperCasingWriter.java +++ b/jackson-json-view/src/main/java/com/metaxiii/fr/config/UpperCasingWriter.java @@ -15,7 +15,8 @@ public UpperCasingWriter(BeanPropertyWriter w) { } @Override - public void serializeAsField(Object bean, JsonGenerator gen, SerializerProvider prov) throws Exception { + public void serializeAsField(Object bean, JsonGenerator gen, SerializerProvider prov) + throws Exception { String value = ((User) bean).name; value = (value == null) ? "" : value.toUpperCase(); gen.writeStringField("name", value); diff --git a/jackson-json-view/src/test/java/com/metaxiii/fr/controller/ItemControllerTest.java b/jackson-json-view/src/test/java/com/metaxiii/fr/controller/ItemControllerTest.java index 4ab065af..87b7bb02 100644 --- a/jackson-json-view/src/test/java/com/metaxiii/fr/controller/ItemControllerTest.java +++ b/jackson-json-view/src/test/java/com/metaxiii/fr/controller/ItemControllerTest.java @@ -20,17 +20,18 @@ @AutoConfigureMockMvc class ItemControllerTest { - @Autowired - private MockMvc mockMvc; + @Autowired private MockMvc mockMvc; @Test void getItemInternal() throws Exception { - final MvcResult mvcResult = mockMvc - .perform(get("/items-internal").contentType(MediaType.APPLICATION_JSON)) - .andDo(print()) - .andExpect(status().isOk()) - .andReturn(); - final Item item = new ObjectMapper().readValue(mvcResult.getResponse().getContentAsString(), Item.class); + final MvcResult mvcResult = + mockMvc + .perform(get("/items-internal").contentType(MediaType.APPLICATION_JSON)) + .andDo(print()) + .andExpect(status().isOk()) + .andReturn(); + final Item item = + new ObjectMapper().readValue(mvcResult.getResponse().getContentAsString(), Item.class); assertEquals(1, item.getId()); assertEquals("item name", item.getItemName()); assertEquals("owner", item.getOwnerName()); @@ -40,12 +41,14 @@ void getItemInternal() throws Exception { @Test void getItemPublic() throws Exception { - final MvcResult mvcResult = mockMvc - .perform(get("/items-public").contentType(MediaType.APPLICATION_JSON)) - .andDo(print()) - .andExpect(status().isOk()) - .andReturn(); - final Item item = new ObjectMapper().readValue(mvcResult.getResponse().getContentAsString(), Item.class); + final MvcResult mvcResult = + mockMvc + .perform(get("/items-public").contentType(MediaType.APPLICATION_JSON)) + .andDo(print()) + .andExpect(status().isOk()) + .andReturn(); + final Item item = + new ObjectMapper().readValue(mvcResult.getResponse().getContentAsString(), Item.class); assertEquals(1, item.getId()); assertEquals("item name", item.getItemName()); final var mapper = new ObjectMapper(); diff --git a/jackson-json-view/src/test/java/com/metaxiii/fr/model/UserTest.java b/jackson-json-view/src/test/java/com/metaxiii/fr/model/UserTest.java index eab90b9b..2dbdff43 100644 --- a/jackson-json-view/src/test/java/com/metaxiii/fr/model/UserTest.java +++ b/jackson-json-view/src/test/java/com/metaxiii/fr/model/UserTest.java @@ -57,9 +57,8 @@ void whenUseJsonViewToDeserialize_thenCorrect() throws IOException { @Test void whenUseCustomJsonViewToSerialize_thenCorrect() throws JsonProcessingException { User user = new User(1, "John"); - SerializerFactory serializerFactory = BeanSerializerFactory.instance.withSerializerModifier( - new MyBeanSerializerModifier() - ); + SerializerFactory serializerFactory = + BeanSerializerFactory.instance.withSerializerModifier(new MyBeanSerializerModifier()); ObjectMapper mapper = new ObjectMapper(); mapper.setSerializerFactory(serializerFactory); String result = mapper.writerWithView(Views.Public.class).writeValueAsString(user); diff --git a/jpa-query-localdatetime-with-localdate/src/main/java/com/metaxiii/fr/jpaquerylocaldatetimewithlocaldate/EventCriteriaRepository.java b/jpa-query-localdatetime-with-localdate/src/main/java/com/metaxiii/fr/jpaquerylocaldatetimewithlocaldate/EventCriteriaRepository.java index 8d99f335..61030688 100644 --- a/jpa-query-localdatetime-with-localdate/src/main/java/com/metaxiii/fr/jpaquerylocaldatetimewithlocaldate/EventCriteriaRepository.java +++ b/jpa-query-localdatetime-with-localdate/src/main/java/com/metaxiii/fr/jpaquerylocaldatetimewithlocaldate/EventCriteriaRepository.java @@ -13,8 +13,7 @@ @Repository public class EventCriteriaRepository { - @PersistenceContext - private EntityManager entityManager; + @PersistenceContext private EntityManager entityManager; public List findByCreatedDate(final LocalDate date) { final LocalDateTime startOfDay = date.atStartOfDay(); diff --git a/jpa-query-localdatetime-with-localdate/src/main/java/com/metaxiii/fr/jpaquerylocaldatetimewithlocaldate/EventRepository.java b/jpa-query-localdatetime-with-localdate/src/main/java/com/metaxiii/fr/jpaquerylocaldatetimewithlocaldate/EventRepository.java index 3dcfecc8..722a5b7a 100644 --- a/jpa-query-localdatetime-with-localdate/src/main/java/com/metaxiii/fr/jpaquerylocaldatetimewithlocaldate/EventRepository.java +++ b/jpa-query-localdatetime-with-localdate/src/main/java/com/metaxiii/fr/jpaquerylocaldatetimewithlocaldate/EventRepository.java @@ -10,21 +10,20 @@ public interface EventRepository extends JpaRepository { List findByCreatedAtBetween(LocalDateTime start, LocalDateTime end); - List findByCreatedAtGreaterThanEqualAndCreatedAtLessThan(LocalDateTime start, LocalDateTime end); + List findByCreatedAtGreaterThanEqualAndCreatedAtLessThan( + LocalDateTime start, LocalDateTime end); @Query("SELECT e FROM Event e WHERE cast(e.createdAt as date ) = :date") List findByDate(@Param("date") LocalDate date); @Query( - value = """ + value = + """ SELECT * FROM events e WHERE e.created_at >= :startOfDay AND e.created_at < :endOfDay""", - nativeQuery = true - ) + nativeQuery = true) List findByDateRangeNative( - @Param("startOfDay") LocalDateTime startOfDay, - @Param("endOfDay") LocalDateTime endOfDay - ); + @Param("startOfDay") LocalDateTime startOfDay, @Param("endOfDay") LocalDateTime endOfDay); } diff --git a/jpa-query-localdatetime-with-localdate/src/test/java/com/metaxiii/fr/jpaquerylocaldatetimewithlocaldate/JpaQueryLocaldatetimeWithLocaldateApplicationTests.java b/jpa-query-localdatetime-with-localdate/src/test/java/com/metaxiii/fr/jpaquerylocaldatetimewithlocaldate/JpaQueryLocaldatetimeWithLocaldateApplicationTests.java index 922bd2a3..e52ddd7e 100644 --- a/jpa-query-localdatetime-with-localdate/src/test/java/com/metaxiii/fr/jpaquerylocaldatetimewithlocaldate/JpaQueryLocaldatetimeWithLocaldateApplicationTests.java +++ b/jpa-query-localdatetime-with-localdate/src/test/java/com/metaxiii/fr/jpaquerylocaldatetimewithlocaldate/JpaQueryLocaldatetimeWithLocaldateApplicationTests.java @@ -16,11 +16,9 @@ class JpaQueryLocaldatetimeWithLocaldateApplicationTests { private static final LocalDateTime startOfDay = date.atStartOfDay(); private static final LocalDateTime endOfDay = date.plusDays(1).atStartOfDay().minusSeconds(1); - @Autowired - private EventRepository eventRepository; + @Autowired private EventRepository eventRepository; - @Autowired - private EventCriteriaRepository eventCriteriaRepository; + @Autowired private EventCriteriaRepository eventCriteriaRepository; @Test void contextLoads() { @@ -35,7 +33,8 @@ void itShouldFindByCreatedAtBetween() { @Test void itShouldFindByCreatedAtGreaterThanEqualAndCreatedAtLessThan() { - final var results = eventRepository.findByCreatedAtGreaterThanEqualAndCreatedAtLessThan(startOfDay, endOfDay); + final var results = + eventRepository.findByCreatedAtGreaterThanEqualAndCreatedAtLessThan(startOfDay, endOfDay); assertEquals(3, results.size()); } diff --git a/mapstruct-lombok/src/test/java/com/metaxiii/fr/AppTest.java b/mapstruct-lombok/src/test/java/com/metaxiii/fr/AppTest.java index d26a2349..570f3695 100644 --- a/mapstruct-lombok/src/test/java/com/metaxiii/fr/AppTest.java +++ b/mapstruct-lombok/src/test/java/com/metaxiii/fr/AppTest.java @@ -17,7 +17,8 @@ void whenDestinationIsMapped_thenIsSuccessful() { Assertions.assertNotNull(simpleDestination); Assertions.assertEquals(simpleSource.getName(), simpleDestination.getName()); Assertions.assertEquals(simpleSource.getDescription(), simpleDestination.getDescription()); - final LombokDestination lombokDestination = lombokMapper.sourceToLombokDestination(simpleSource); + final LombokDestination lombokDestination = + lombokMapper.sourceToLombokDestination(simpleSource); Assertions.assertNotNull(lombokDestination); Assertions.assertEquals(simpleSource.getName(), lombokDestination.getName()); Assertions.assertEquals(simpleSource.getDescription(), lombokDestination.getDescription()); diff --git a/mask-email-adress-phone/src/test/java/com/metaxiii/fr/MaskingTest.java b/mask-email-adress-phone/src/test/java/com/metaxiii/fr/MaskingTest.java index 5912dd35..4a3b348a 100644 --- a/mask-email-adress-phone/src/test/java/com/metaxiii/fr/MaskingTest.java +++ b/mask-email-adress-phone/src/test/java/com/metaxiii/fr/MaskingTest.java @@ -26,7 +26,8 @@ void givenEmailAddress_whenUsingRegex_thenMaskEmail() { @Test void givenEmailAddress_whenUsingStringManipulation_thenMaskEmail() { final var atIndex = email.indexOf('@'); - final var repeatedString = IntStream.range(0, atIndex - 2).mapToObj(i -> "*").collect(Collectors.joining()); + final var repeatedString = + IntStream.range(0, atIndex - 2).mapToObj(i -> "*").collect(Collectors.joining()); final var maskedPart = email.substring(0, atIndex - repeatedString.length()) + repeatedString; final var maskedEmail = maskedPart + email.substring(atIndex); diff --git a/mode-integer-array/src/main/java/com/metaxiii/fr/App.java b/mode-integer-array/src/main/java/com/metaxiii/fr/App.java index 3bc72e25..60185740 100644 --- a/mode-integer-array/src/main/java/com/metaxiii/fr/App.java +++ b/mode-integer-array/src/main/java/com/metaxiii/fr/App.java @@ -64,14 +64,13 @@ public Set findModeBySorting(final int[] nums) { } public Set findModeByUsingStreams(final int[] nums) { - final var frequencyMap = Arrays.stream(nums).boxed().collect(Collectors.groupingBy(e -> e, Collectors.counting())); + final var frequencyMap = + Arrays.stream(nums).boxed().collect(Collectors.groupingBy(e -> e, Collectors.counting())); final var maxFrequency = Collections.max(frequencyMap.values()); - return frequencyMap - .entrySet() - .stream() - .filter(entry -> entry.getValue().equals(maxFrequency)) - .map(Map.Entry::getKey) - .collect(Collectors.toSet()); + return frequencyMap.entrySet().stream() + .filter(entry -> entry.getValue().equals(maxFrequency)) + .map(Map.Entry::getKey) + .collect(Collectors.toSet()); } public Set findModeByUsingTreemap(final int[] nums) { diff --git a/mode-integer-array/src/test/java/com/metaxiii/fr/AppTest.java b/mode-integer-array/src/test/java/com/metaxiii/fr/AppTest.java index 3c9a60e8..0c2cccfe 100644 --- a/mode-integer-array/src/test/java/com/metaxiii/fr/AppTest.java +++ b/mode-integer-array/src/test/java/com/metaxiii/fr/AppTest.java @@ -8,7 +8,7 @@ class AppTest { - private static final int[] NUMS = { 1, 2, 2, 3, 3, 4, 4, 4, 5 }; + private static final int[] NUMS = {1, 2, 2, 3, 3, 4, 4, 4, 5}; private App app; @BeforeEach @@ -28,8 +28,9 @@ void itShouldFindModeBySortingWithUsingSort() { final var mode = app.findModeBySorting(NUMS); assertEquals(1, mode.size()); assertDoesNotThrow(() -> mode.stream().filter(e -> e.equals(4)).findFirst().orElseThrow()); - final var modeWithOnlyOneElement = app.findModeBySorting(new int[] { 1 }); - assertDoesNotThrow(() -> modeWithOnlyOneElement.stream().filter(e -> e.equals(1)).findFirst().orElseThrow()); + final var modeWithOnlyOneElement = app.findModeBySorting(new int[] {1}); + assertDoesNotThrow( + () -> modeWithOnlyOneElement.stream().filter(e -> e.equals(1)).findFirst().orElseThrow()); } @Test diff --git a/month-number-name-convert/src/test/java/com/metaxiii/fr/AppTest.java b/month-number-name-convert/src/test/java/com/metaxiii/fr/AppTest.java index d00f2533..161be8b8 100644 --- a/month-number-name-convert/src/test/java/com/metaxiii/fr/AppTest.java +++ b/month-number-name-convert/src/test/java/com/metaxiii/fr/AppTest.java @@ -15,11 +15,11 @@ class AppTest { void givenMonthName_whenUsingChronoFieldEnum_thenReturnNumber() { final String givenMonthName = "Sep"; final int expectedMonthNumber = 9; - final int monthNumber = DateTimeFormatter - .ofPattern("MMM") - .withLocale(Locale.ENGLISH) - .parse(givenMonthName) - .get(ChronoField.MONTH_OF_YEAR); + final int monthNumber = + DateTimeFormatter.ofPattern("MMM") + .withLocale(Locale.ENGLISH) + .parse(givenMonthName) + .get(ChronoField.MONTH_OF_YEAR); assertEquals(expectedMonthNumber, monthNumber); } @@ -27,11 +27,11 @@ void givenMonthName_whenUsingChronoFieldEnum_thenReturnNumber() { void givenMonthName_whenUsingJodaTime_thenReturnNumber() { final String givenMonthName = "April"; final int expectedMonthNumber = 4; - final int monthNumber = DateTimeFormat - .forPattern("MMM") - .withLocale(Locale.ENGLISH) - .parseDateTime(givenMonthName) - .getMonthOfYear(); + final int monthNumber = + DateTimeFormat.forPattern("MMM") + .withLocale(Locale.ENGLISH) + .parseDateTime(givenMonthName) + .getMonthOfYear(); assertEquals(expectedMonthNumber, monthNumber); } diff --git a/null-array-empty-list-convert/src/test/java/com/metaxiii/fr/AppTest.java b/null-array-empty-list-convert/src/test/java/com/metaxiii/fr/AppTest.java index b96ec9e3..7f695f72 100644 --- a/null-array-empty-list-convert/src/test/java/com/metaxiii/fr/AppTest.java +++ b/null-array-empty-list-convert/src/test/java/com/metaxiii/fr/AppTest.java @@ -32,13 +32,13 @@ static List getAsListOptional(final String[] args) { @Test void whenArrayIsNotEmpty_thenReturnListWithSameElements_getAsListApacheCommonsLang() { - final String[] possiblyNullArray = { "a", "b" }; + final String[] possiblyNullArray = {"a", "b"}; assertThat(getAsListApacheCommonsLang(possiblyNullArray)).containsExactly(possiblyNullArray); } @Test void whenArrayIsNotEmpty_thenReturnListWithSameElements_getAsListOptional() { - final String[] possiblyNullArray = { "a", "b" }; + final String[] possiblyNullArray = {"a", "b"}; assertThat(getAsListOptional(possiblyNullArray)).containsExactly(possiblyNullArray); } diff --git a/partition list in java/src/test/java/MainTest.java b/partition list in java/src/test/java/MainTest.java index 16179326..3c1ab7c7 100644 --- a/partition list in java/src/test/java/MainTest.java +++ b/partition list in java/src/test/java/MainTest.java @@ -56,7 +56,8 @@ void givenList_whenParitioningIntoNSublists_thenCorrectWithApacheCollections() { @Test void givenList_whenParitioningIntoSublistsUsingPartitionBy_thenCorrect() { List intList = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8); - Map> groups = intList.stream().collect(Collectors.partitioningBy(s -> s > 6)); + Map> groups = + intList.stream().collect(Collectors.partitioningBy(s -> s > 6)); List> subSets = new ArrayList>(groups.values()); List lastPartition = subSets.get(1); List expectedLastPartition = Lists.newArrayList(7, 8); @@ -67,7 +68,8 @@ void givenList_whenParitioningIntoSublistsUsingPartitionBy_thenCorrect() { @Test public final void givenList_whenParitioningIntoNSublistsUsingGroupingBy_thenCorrect() { List intList = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8); - Map> groups = intList.stream().collect(Collectors.groupingBy(s -> (s - 1) / 3)); + Map> groups = + intList.stream().collect(Collectors.groupingBy(s -> (s - 1) / 3)); List> subSets = new ArrayList>(groups.values()); List lastPartition = subSets.get(2); List expectedLastPartition = Lists.newArrayList(7, 8); @@ -78,18 +80,17 @@ public final void givenList_whenParitioningIntoNSublistsUsingGroupingBy_thenCorr @Test void givenList_whenSplittingBySeparator_thenCorrect() { List intList = Lists.newArrayList(1, 2, 3, 0, 4, 5, 6, 0, 7, 8); - int[] indexes = Stream - .of( - IntStream.of(-1), - IntStream.range(0, intList.size()).filter(i -> intList.get(i) == 0), - IntStream.of(intList.size()) - ) - .flatMapToInt(s -> s) - .toArray(); - List> subSets = IntStream - .range(0, indexes.length - 1) - .mapToObj(i -> intList.subList(indexes[i] + 1, indexes[i + 1])) - .collect(Collectors.toList()); + int[] indexes = + Stream.of( + IntStream.of(-1), + IntStream.range(0, intList.size()).filter(i -> intList.get(i) == 0), + IntStream.of(intList.size())) + .flatMapToInt(s -> s) + .toArray(); + List> subSets = + IntStream.range(0, indexes.length - 1) + .mapToObj(i -> intList.subList(indexes[i] + 1, indexes[i + 1])) + .collect(Collectors.toList()); List lastPartition = subSets.get(2); List expectedLastPartition = Lists.newArrayList(7, 8); assertEquals(3, subSets.size()); diff --git a/passing-method-parameter/src/test/java/com/metaxiii/fr/PassingMethodParameterWithInterfaceBeforeJava8Test.java b/passing-method-parameter/src/test/java/com/metaxiii/fr/PassingMethodParameterWithInterfaceBeforeJava8Test.java index d8114a9b..6a636957 100644 --- a/passing-method-parameter/src/test/java/com/metaxiii/fr/PassingMethodParameterWithInterfaceBeforeJava8Test.java +++ b/passing-method-parameter/src/test/java/com/metaxiii/fr/PassingMethodParameterWithInterfaceBeforeJava8Test.java @@ -17,16 +17,16 @@ int performOperation(final int a, final int b, final Operation operation) { @Test @SuppressWarnings("Convert2Lambda") void itShouldPassMethodParameterWithInterface_BeforeJava8() { - final var actualResult = performOperation( - 5, - 3, - new Operation() { - @Override - public int execute(final int a, final int b) { - return a + b; - } - } - ); + final var actualResult = + performOperation( + 5, + 3, + new Operation() { + @Override + public int execute(final int a, final int b) { + return a + b; + } + }); assertEquals(8, actualResult); } } diff --git a/passing-method-parameter/src/test/java/com/metaxiii/fr/PassingMethodParameterWithInterfaceTest.java b/passing-method-parameter/src/test/java/com/metaxiii/fr/PassingMethodParameterWithInterfaceTest.java index 7eec4c6d..09a472d6 100644 --- a/passing-method-parameter/src/test/java/com/metaxiii/fr/PassingMethodParameterWithInterfaceTest.java +++ b/passing-method-parameter/src/test/java/com/metaxiii/fr/PassingMethodParameterWithInterfaceTest.java @@ -26,10 +26,7 @@ void itShouldPassMethodParameterWithFunction() { assertEquals(8, actualResult); } - int executeBiFunction( - final IntBinaryOperator function, - final int a, - final int b) { + int executeBiFunction(final IntBinaryOperator function, final int a, final int b) { return function.applyAsInt(a, b); } diff --git a/pom.xml b/pom.xml index dc845071..2d625ad5 100644 --- a/pom.xml +++ b/pom.xml @@ -107,6 +107,7 @@ 0.8.14 6.0.3 + 1.35.0 @@ -185,6 +186,26 @@ org.springframework.boot spring-boot-maven-plugin + + com.diffplug.spotless + spotless-maven-plugin + + + + ${spotless-maven-plugin.version} + + + + + + spotless-check + validate + + check + + + + diff --git a/powerful_comparison_with_lambdas/src/test/java/com/metaxiii/fr/model/HumanTest.java b/powerful_comparison_with_lambdas/src/test/java/com/metaxiii/fr/model/HumanTest.java index d762d122..11a627f0 100644 --- a/powerful_comparison_with_lambdas/src/test/java/com/metaxiii/fr/model/HumanTest.java +++ b/powerful_comparison_with_lambdas/src/test/java/com/metaxiii/fr/model/HumanTest.java @@ -9,23 +9,22 @@ import java.util.Collections; import java.util.Comparator; import java.util.List; -import java.util.stream.Collectors; import org.junit.jupiter.api.Test; class HumanTest { @Test public void givenPreLambda_whenSortingEntitiesByName_thenCorrectlySorted() { - final ArrayList humans = new ArrayList<>(List.of(new Human("Sarah", 10), new Human("Jack", 12))); + final ArrayList humans = + new ArrayList<>(List.of(new Human("Sarah", 10), new Human("Jack", 12))); Collections.sort( - humans, - new Comparator<>() { - @Override - public int compare(Human h1, Human h2) { - return h1.getName().compareTo(h2.getName()); - } - } - ); + humans, + new Comparator<>() { + @Override + public int compare(Human h1, Human h2) { + return h1.getName().compareTo(h2.getName()); + } + }); assertEquals(humans.get(0), new Human("Jack", 12)); } @@ -67,75 +66,74 @@ public void whenSortingEntitiesByNameReversed_thenCorrectlySorted() { @Test public void whenSortingEntitiesByNameThenAge_thenCorrectlySorted() { - List humans = new ArrayList<>( - List.of(new Human("Sarah", 10), new Human("Sarah", 10), new Human("Zack", 12)) - ); - humans.sort((lhs, rhs) -> { - if (lhs.getName().equals(rhs.getName())) { - return Integer.compare(lhs.getAge(), rhs.getAge()); - } else { - return lhs.getName().compareTo(rhs.getName()); - } - }); + List humans = + new ArrayList<>( + List.of(new Human("Sarah", 10), new Human("Sarah", 10), new Human("Zack", 12))); + humans.sort( + (lhs, rhs) -> { + if (lhs.getName().equals(rhs.getName())) { + return Integer.compare(lhs.getAge(), rhs.getAge()); + } else { + return lhs.getName().compareTo(rhs.getName()); + } + }); assertEquals(humans.get(0), new Human("Sarah", 10)); } @Test public void givenComposition_whenSortingEntitiesByNameThenAge_thenCorrectlySorted() { - List humans = new ArrayList<>( - List.of(new Human("Sarah", 10), new Human("Sarah", 12), new Human("Zack", 12)) - ); + List humans = + new ArrayList<>( + List.of(new Human("Sarah", 10), new Human("Sarah", 12), new Human("Zack", 12))); humans.sort(Comparator.comparing(Human::getName).thenComparing(Human::getAge)); assertEquals(humans.get(0), new Human("Sarah", 10)); } @Test - public final void givenStreamNaturalOrdering_whenSortingEntitiesByName_thenCorrectlySorted() { + void givenStreamNaturalOrdering_whenSortingEntitiesByName_thenCorrectlySorted() { List letters = List.of("B", "A", "C"); - List sortedLetters = letters.stream().sorted().collect(Collectors.toList()); + List sortedLetters = letters.stream().sorted().toList(); assertEquals("A", sortedLetters.get(0)); } @Test - public final void givenStreamCustomOrdering_whenSortingEntitiesByName_thenCorrectlySorted() { + void givenStreamCustomOrdering_whenSortingEntitiesByName_thenCorrectlySorted() { List humans = new ArrayList<>(List.of(new Human("Sarah", 10), new Human("Jack", 12))); Comparator nameComparator = (h1, h2) -> h1.getName().compareTo(h2.getName()); - List sortedHumans = humans.stream().sorted(nameComparator).collect(Collectors.toList()); + List sortedHumans = humans.stream().sorted(nameComparator).toList(); assertEquals(sortedHumans.get(0), new Human("Jack", 12)); } @Test - public final void givenStreamComparatorOrdering_whenSortingEntitiesByName_thenCorrectlySorted() { + void givenStreamComparatorOrdering_whenSortingEntitiesByName_thenCorrectlySorted() { List humans = new ArrayList<>(List.of(new Human("Sarah", 10), new Human("Jack", 12))); - List sortedHumans = humans - .stream() - .sorted(Comparator.comparing(Human::getName)) - .collect(Collectors.toList()); + List sortedHumans = + humans.stream().sorted(Comparator.comparing(Human::getName)).toList(); assertEquals(sortedHumans.get(0), new Human("Jack", 12)); } @Test - public final void givenStreamNaturalOrdering_whenSortingEntitiesByNameReversed_thenCorrectlySorted() { + void givenStreamNaturalOrdering_whenSortingEntitiesByNameReversed_thenCorrectlySorted() { List letters = List.of("B", "A", "C"); - List reverseSortedLetters = letters.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList()); + List reverseSortedLetters = letters.stream().sorted(Comparator.reverseOrder()).toList(); assertEquals("C", reverseSortedLetters.get(0)); } @Test - public final void givenStreamCustomOrdering_whenSortingEntitiesByNameReversed_thenCorrectlySorted() { + void givenStreamCustomOrdering_whenSortingEntitiesByNameReversed_thenCorrectlySorted() { List humans = new ArrayList<>(List.of(new Human("Sarah", 10), new Human("Jack", 12))); Comparator reverseNameComparator = (h1, h2) -> h2.getName().compareTo(h1.getName()); - List reverseSortedHumans = humans.stream().sorted(reverseNameComparator).collect(Collectors.toList()); + List reverseSortedHumans = humans.stream().sorted(reverseNameComparator).toList(); assertEquals(reverseSortedHumans.get(0), new Human("Sarah", 10)); } @Test - public final void givenStreamComparatorOrdering_whenSortingEntitiesByNameReversed_thenCorrectlySorted() { + void givenStreamComparatorOrdering_whenSortingEntitiesByNameReversed_thenCorrectlySorted() { List humans = new ArrayList<>(List.of(new Human("Sarah", 10), new Human("Jack", 12))); - List reverseSortedHumans = humans - .stream() - .sorted(Comparator.comparing(Human::getName, Comparator.reverseOrder())) - .collect(Collectors.toList()); + List reverseSortedHumans = + humans.stream() + .sorted(Comparator.comparing(Human::getName, Comparator.reverseOrder())) + .toList(); assertEquals(reverseSortedHumans.get(0), new Human("Sarah", 10)); } @@ -145,11 +143,10 @@ public void givenANullElement_whenSortingEntitiesByName_thenThrowsNPE() { humans.add(null); humans.add(new Human("Jack", 12)); assertThrows( - NullPointerException.class, - () -> { - humans.sort((h1, h2) -> h1.getName().compareTo(h2.getName())); - } - ); + NullPointerException.class, + () -> { + humans.sort((h1, h2) -> h1.getName().compareTo(h2.getName())); + }); } @Test @@ -158,14 +155,15 @@ public void givenANullElement_whenSortingEntitiesByNameManually_thenMovesTheNull humans.add(null); humans.add(new Human("Jack", 12)); humans.add(null); - humans.sort((h1, h2) -> { - if (h1 == null) { - return h2 == null ? 0 : 1; - } else if (h2 == null) { - return -1; - } - return h1.getName().compareTo(h2.getName()); - }); + humans.sort( + (h1, h2) -> { + if (h1 == null) { + return h2 == null ? 0 : 1; + } else if (h2 == null) { + return -1; + } + return h1.getName().compareTo(h2.getName()); + }); assertNotNull(humans.get(0)); assertNull(humans.get(1)); assertNull(humans.get(2)); diff --git a/simple-mail/src/main/java/com/metaxiii/fr/model/SimpleMail.java b/simple-mail/src/main/java/com/metaxiii/fr/model/SimpleMail.java index 862023e5..b85be8b2 100644 --- a/simple-mail/src/main/java/com/metaxiii/fr/model/SimpleMail.java +++ b/simple-mail/src/main/java/com/metaxiii/fr/model/SimpleMail.java @@ -25,11 +25,11 @@ private SimpleMail() throws IllegalAccessException { } public static void forwardingEmail(final Email receivedEmail) { - final Email email = EmailBuilder - .forwarding(receivedEmail) - .from(SENDER_EXAMPLE_COM) - .prependText("This is an Forward Email. See below email:") - .buildEmail(); + final Email email = + EmailBuilder.forwarding(receivedEmail) + .from(SENDER_EXAMPLE_COM) + .prependText("This is an Forward Email. See below email:") + .buildEmail(); } public static void handleExceptionWhenSendingEmail() { @@ -42,23 +42,21 @@ public static void handleExceptionWhenSendingEmail() { } public static void sendPlainTextEmail() { - final Email email = EmailBuilder - .startingBlank() - .from(SENDER_EXAMPLE_COM) - .to(RECIPIENT_EXAMPLE_COM) - .withSubject("Email with Plain Text!") - .withPlainText("This is a test email sent using SJM.") - .buildEmail(); + final Email email = + EmailBuilder.startingBlank() + .from(SENDER_EXAMPLE_COM) + .to(RECIPIENT_EXAMPLE_COM) + .withSubject("Email with Plain Text!") + .withPlainText("This is a test email sent using SJM.") + .buildEmail(); sendEmail(email); } private static void sendEmail(final Email email) { - try ( - final Mailer mailer = MailerBuilder - .withSMTPServer("smtp.example.com", 25, "username", "password") - .withMaximumEmailSize(1024 * 1024 * 5) // 5 Megabytes - .buildMailer() - ) { + try (final Mailer mailer = + MailerBuilder.withSMTPServer("smtp.example.com", 25, "username", "password") + .withMaximumEmailSize(1024 * 1024 * 5) // 5 Megabytes + .buildMailer()) { final boolean validate = mailer.validate(email); if (validate) { mailer.sendMail(email); @@ -71,91 +69,96 @@ private static void sendEmail(final Email email) { } public static void replyingToEmail(final Email receivedEmail) { - EmailBuilder - .replyingTo(receivedEmail) - .from(SENDER_EXAMPLE_COM) - .prependText("This is a Reply Email. Original email included below:") - .buildEmail(); + EmailBuilder.replyingTo(receivedEmail) + .from(SENDER_EXAMPLE_COM) + .prependText("This is a Reply Email. Original email included below:") + .buildEmail(); } public static void sendEmailWithAttachment() { - final Email email = EmailBuilder - .startingBlank() - .from(SENDER_EXAMPLE_COM) - .to(RECIPIENT_EXAMPLE_COM) - .withSubject("Email with Plain Text and Attachment!") - .withPlainText("This is a test email with attachment sent using SJM.") - .withAttachment("important_document.pdf", new FileDataSource("path/to/important_document.pdf")) - .buildEmail(); + final Email email = + EmailBuilder.startingBlank() + .from(SENDER_EXAMPLE_COM) + .to(RECIPIENT_EXAMPLE_COM) + .withSubject("Email with Plain Text and Attachment!") + .withPlainText("This is a test email with attachment sent using SJM.") + .withAttachment( + "important_document.pdf", new FileDataSource("path/to/important_document.pdf")) + .buildEmail(); sendEmail(email); } private static void sendEmailWithDeliveryReadRecipient() { - final Email email = EmailBuilder - .startingBlank() - .from(SENDER_EXAMPLE_COM) - .to(RECIPIENT_EXAMPLE_COM) - .withSubject("Email with Delivery/Read Receipt Configured!") - .withPlainText("This is an email sending with delivery/read receipt.") - .withDispositionNotificationTo(new Recipient("name", "address@domain.com", Message.RecipientType.TO)) - .withReturnReceiptTo(new Recipient("name", "address@domain.com", Message.RecipientType.TO)) - .buildEmail(); + final Email email = + EmailBuilder.startingBlank() + .from(SENDER_EXAMPLE_COM) + .to(RECIPIENT_EXAMPLE_COM) + .withSubject("Email with Delivery/Read Receipt Configured!") + .withPlainText("This is an email sending with delivery/read receipt.") + .withDispositionNotificationTo( + new Recipient("name", "address@domain.com", Message.RecipientType.TO)) + .withReturnReceiptTo( + new Recipient("name", "address@domain.com", Message.RecipientType.TO)) + .buildEmail(); sendEmail(email); } public static void sendEmailWithMultipleAttachment() { final List arList = new ArrayList<>(); - arList.add(new AttachmentResource("important_document.pdf", new FileDataSource("path/to/important_document.pdf"))); - arList.add(new AttachmentResource("company_logo.png", new FileDataSource("path/to/company_logo.png"))); - final Email email = EmailBuilder - .startingBlank() - .from(SENDER_EXAMPLE_COM) - .to(RECIPIENT_EXAMPLE_COM) - .withSubject("Email with Plain Text and multiple Attachments!") - .withPlainText("This is a test email with attachment sent using SJM.") - .withAttachments(arList) - .buildEmail(); + arList.add( + new AttachmentResource( + "important_document.pdf", new FileDataSource("path/to/important_document.pdf"))); + arList.add( + new AttachmentResource("company_logo.png", new FileDataSource("path/to/company_logo.png"))); + final Email email = + EmailBuilder.startingBlank() + .from(SENDER_EXAMPLE_COM) + .to(RECIPIENT_EXAMPLE_COM) + .withSubject("Email with Plain Text and multiple Attachments!") + .withPlainText("This is a test email with attachment sent using SJM.") + .withAttachments(arList) + .buildEmail(); sendEmail(email); } public static void sendHTMLTextWithEmbeddedImageEmail() { final String htmlContent = - "

This is an email with HTML content

" + - "

This email body contains additional information and formatting.

" + - "\"Company"; - - final Email email = EmailBuilder - .startingBlank() - .from(SENDER_EXAMPLE_COM) - .to(RECIPIENT_EXAMPLE_COM) - .withSubject("Email with HTML and Embedded Image!") - .withHTMLText(htmlContent) - .withEmbeddedImage("company_logo", new FileDataSource("path/to/company_logo.png")) - .buildEmail(); + "

This is an email with HTML content

" + + "

This email body contains additional information and formatting.

" + + "\"Company"; + + final Email email = + EmailBuilder.startingBlank() + .from(SENDER_EXAMPLE_COM) + .to(RECIPIENT_EXAMPLE_COM) + .withSubject("Email with HTML and Embedded Image!") + .withHTMLText(htmlContent) + .withEmbeddedImage("company_logo", new FileDataSource("path/to/company_logo.png")) + .buildEmail(); sendEmail(email); } public static void sendPlainTextEmailToMultipleRecipient() { - final Email email = EmailBuilder - .startingBlank() - .from(SENDER_EXAMPLE_COM) - .to("recipient1@example.com, recipient2@example.com, recipient3@example.com") - .withSubject("Email with Plain Text!") - .withPlainText("This is a test email sent using SJM to multiple recipients.") - .buildEmail(); + final Email email = + EmailBuilder.startingBlank() + .from(SENDER_EXAMPLE_COM) + .to("recipient1@example.com, recipient2@example.com, recipient3@example.com") + .withSubject("Email with Plain Text!") + .withPlainText("This is a test email sent using SJM to multiple recipients.") + .buildEmail(); sendEmail(email); } public static void setCustomHeaderWhenSendingEmail() { - final Email email = EmailBuilder - .startingBlank() - .from(SENDER_EXAMPLE_COM) - .to(RECIPIENT_EXAMPLE_COM) - .withSubject("Email with Custom Header") - .withPlainText("This is an important message.") - .withHeader("X-Priority", "1") - .buildEmail(); + final Email email = + EmailBuilder.startingBlank() + .from(SENDER_EXAMPLE_COM) + .to(RECIPIENT_EXAMPLE_COM) + .withSubject("Email with Custom Header") + .withPlainText("This is an important message.") + .withHeader("X-Priority", "1") + .buildEmail(); sendEmail(email); } } diff --git a/sort-map-value-list-streams/src/test/java/com/metaxiii/fr/SortingArrayListUsingStreamUnitTest.java b/sort-map-value-list-streams/src/test/java/com/metaxiii/fr/SortingArrayListUsingStreamUnitTest.java index eccda950..4f781d37 100644 --- a/sort-map-value-list-streams/src/test/java/com/metaxiii/fr/SortingArrayListUsingStreamUnitTest.java +++ b/sort-map-value-list-streams/src/test/java/com/metaxiii/fr/SortingArrayListUsingStreamUnitTest.java @@ -17,21 +17,24 @@ class SortingArrayListUsingStreamUnitTest { - private static final Map>> MAP_OF_DEPT_TO_MAP_OF_SEX_TO_EMPLOYEES = - new HashMap<>(); + private static final Map>> + MAP_OF_DEPT_TO_MAP_OF_SEX_TO_EMPLOYEES = new HashMap<>(); @Test void givenHashMapContainingEmployeeList_whenSortWithStreamAPI_thenSort() throws IOException { final var lstOfEmployees = new ArrayList(); - MAP_OF_DEPT_TO_MAP_OF_SEX_TO_EMPLOYEES.forEach((dept, deptToSexToEmps) -> - deptToSexToEmps.forEach((sex, emps) -> { - final List employees = emps - .stream() - .sorted(Comparator.comparingInt(Employee::getSalary).thenComparing(Employee::getName)) - .toList(); - lstOfEmployees.addAll(employees); - }) - ); + MAP_OF_DEPT_TO_MAP_OF_SEX_TO_EMPLOYEES.forEach( + (dept, deptToSexToEmps) -> + deptToSexToEmps.forEach( + (sex, emps) -> { + final List employees = + emps.stream() + .sorted( + Comparator.comparingInt(Employee::getSalary) + .thenComparing(Employee::getName)) + .toList(); + lstOfEmployees.addAll(employees); + })); final String[] expectedArray = readLinesFromFile(getFilePath("emp_sorted.csv")); final String[] actualArray = getCSVDelimitedLines(lstOfEmployees); assertArrayEquals(expectedArray, actualArray); @@ -42,28 +45,38 @@ private static String[] readLinesFromFile(final String filePath) throws IOExcept } private static String getFilePath(final String fileName) { - return Objects - .requireNonNull(SortingArrayListUsingStreamUnitTest.class.getClassLoader().getResource(fileName)) - .getPath(); + return Objects.requireNonNull( + SortingArrayListUsingStreamUnitTest.class.getClassLoader().getResource(fileName)) + .getPath(); } private static String[] getCSVDelimitedLines(final List emps) { - return emps - .stream() - .map(emp -> emp.getDepartment() + "," + emp.getName() + "," + emp.getSalary() + "," + emp.getSex()) - .toArray(String[]::new); + return emps.stream() + .map( + emp -> + emp.getDepartment() + + "," + + emp.getName() + + "," + + emp.getSalary() + + "," + + emp.getSex()) + .toArray(String[]::new); } @Test void givenHashMapContainingEmployeeList_whenSortWithoutStreamAPI_thenSort() throws IOException { final List lstOfEmployees = new ArrayList<>(); - MAP_OF_DEPT_TO_MAP_OF_SEX_TO_EMPLOYEES.forEach((dept, deptToSexToEmps) -> - deptToSexToEmps.forEach((sex, emps) -> { - emps.sort(Comparator.comparingInt(Employee::getSalary).thenComparing(Employee::getName)); - lstOfEmployees.addAll(emps); - }) - ); + MAP_OF_DEPT_TO_MAP_OF_SEX_TO_EMPLOYEES.forEach( + (dept, deptToSexToEmps) -> + deptToSexToEmps.forEach( + (sex, emps) -> { + emps.sort( + Comparator.comparingInt(Employee::getSalary) + .thenComparing(Employee::getName)); + lstOfEmployees.addAll(emps); + })); final String[] expectedArray = readLinesFromFile(getFilePath("emp_sorted.csv")); final String[] actualArray = getCSVDelimitedLines(lstOfEmployees); assertArrayEquals(expectedArray, actualArray); @@ -77,16 +90,17 @@ void setup() throws IOException { private static void populateMap(final String filePath) throws IOException { final String[] lines = readLinesFromFile(filePath); MAP_OF_DEPT_TO_MAP_OF_SEX_TO_EMPLOYEES.clear(); - Arrays - .asList(lines) - .forEach(e -> { - final String[] strArr = e.split(","); - final Employee emp = new Employee(strArr[1], Integer.parseInt(strArr[2]), strArr[0], strArr[3]); + Arrays.asList(lines) + .forEach( + e -> { + final String[] strArr = e.split(","); + final Employee emp = + new Employee(strArr[1], Integer.parseInt(strArr[2]), strArr[0], strArr[3]); - MAP_OF_DEPT_TO_MAP_OF_SEX_TO_EMPLOYEES - .computeIfAbsent(emp.getDepartment(), k -> new HashMap<>()) - .computeIfAbsent(emp.getSex(), k -> new ArrayList<>()) - .add(emp); - }); + MAP_OF_DEPT_TO_MAP_OF_SEX_TO_EMPLOYEES + .computeIfAbsent(emp.getDepartment(), k -> new HashMap<>()) + .computeIfAbsent(emp.getSex(), k -> new ArrayList<>()) + .add(emp); + }); } } diff --git a/sort-string-array-length-comparator/src/test/java/com/metaxiii/fr/AppTest.java b/sort-string-array-length-comparator/src/test/java/com/metaxiii/fr/AppTest.java index 01d039bb..486ad0c4 100644 --- a/sort-string-array-length-comparator/src/test/java/com/metaxiii/fr/AppTest.java +++ b/sort-string-array-length-comparator/src/test/java/com/metaxiii/fr/AppTest.java @@ -8,8 +8,8 @@ class AppTest { - private static final String[] INPUT_ARRAY = new String[] { "am", "today", "too", "I", "busy" }; - private static final String[] SORTED = new String[] { "I", "am", "too", "busy", "today" }; + private static final String[] INPUT_ARRAY = new String[] {"am", "today", "too", "I", "busy"}; + private static final String[] SORTED = new String[] {"I", "am", "too", "busy", "today"}; @Test void whenSortByCustomComparator_thenArraySorted() { diff --git a/spring security integration test/src/main/java/com/metaxiii/fr/configuration/WebSecurityConfigurer.java b/spring security integration test/src/main/java/com/metaxiii/fr/configuration/WebSecurityConfigurer.java index 77276cb1..681d512f 100644 --- a/spring security integration test/src/main/java/com/metaxiii/fr/configuration/WebSecurityConfigurer.java +++ b/spring security integration test/src/main/java/com/metaxiii/fr/configuration/WebSecurityConfigurer.java @@ -16,12 +16,11 @@ public class WebSecurityConfigurer { @Bean public SecurityFilterChain filterChain(final HttpSecurity http) { - return http - .authorizeHttpRequests(cust -> cust.requestMatchers("/private/**").hasRole("USER")) - .authorizeHttpRequests(cust -> cust.requestMatchers("/public/**").permitAll()) - .authorizeHttpRequests(cust -> cust.anyRequest().authenticated()) - .httpBasic(Customizer.withDefaults()) - .build(); + return http.authorizeHttpRequests(cust -> cust.requestMatchers("/private/**").hasRole("USER")) + .authorizeHttpRequests(cust -> cust.requestMatchers("/public/**").permitAll()) + .authorizeHttpRequests(cust -> cust.anyRequest().authenticated()) + .httpBasic(Customizer.withDefaults()) + .build(); } @Bean @@ -32,7 +31,11 @@ public BCryptPasswordEncoder passwordEncoder() { @Bean @SuppressWarnings("all") public InMemoryUserDetailsManager userDetailsService(PasswordEncoder passwordEncoder) { - UserDetails user = User.withUsername("spring").password(passwordEncoder.encode("secret")).roles("USER").build(); + UserDetails user = + User.withUsername("spring") + .password(passwordEncoder.encode("secret")) + .roles("USER") + .build(); return new InMemoryUserDetailsManager(user); } } diff --git a/spring security integration test/src/test/java/com/metaxiii/fr/controller/SecuredControllerRestTemplateIntegrationTest.java b/spring security integration test/src/test/java/com/metaxiii/fr/controller/SecuredControllerRestTemplateIntegrationTest.java index 0171838e..c42927af 100644 --- a/spring security integration test/src/test/java/com/metaxiii/fr/controller/SecuredControllerRestTemplateIntegrationTest.java +++ b/spring security integration test/src/test/java/com/metaxiii/fr/controller/SecuredControllerRestTemplateIntegrationTest.java @@ -14,20 +14,21 @@ @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) class SecuredControllerRestTemplateIntegrationTest { - @Autowired - private TestRestTemplate testRestTemplate; + @Autowired private TestRestTemplate testRestTemplate; @Test void givenAuthRequestOnPrivateService_shouldSucceedWith200() { - final ResponseEntity result = testRestTemplate - .withBasicAuth("spring", "secret") - .getForEntity("/private/hello", String.class); + final ResponseEntity result = + testRestTemplate + .withBasicAuth("spring", "secret") + .getForEntity("/private/hello", String.class); assertEquals(HttpStatus.OK, result.getStatusCode()); } @Test void givenRequestOnPrivateService_shouldFailWith401() { - final ResponseEntity result = testRestTemplate.getForEntity("/private/hello", String.class); + final ResponseEntity result = + testRestTemplate.getForEntity("/private/hello", String.class); assertEquals(HttpStatus.UNAUTHORIZED, result.getStatusCode()); } } diff --git a/spring security integration test/src/test/java/com/metaxiii/fr/controller/SecuredControllerSpringBootIntegrationTest.java b/spring security integration test/src/test/java/com/metaxiii/fr/controller/SecuredControllerSpringBootIntegrationTest.java index a38e9467..a3336ad8 100644 --- a/spring security integration test/src/test/java/com/metaxiii/fr/controller/SecuredControllerSpringBootIntegrationTest.java +++ b/spring security integration test/src/test/java/com/metaxiii/fr/controller/SecuredControllerSpringBootIntegrationTest.java @@ -19,22 +19,22 @@ @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) class SecuredControllerSpringBootIntegrationTest { - @Autowired - private WebApplicationContext context; + @Autowired private WebApplicationContext context; - @Autowired - private MockMvc mvc; + @Autowired private MockMvc mvc; @Test @WithMockUser("spring") void givenAuthRequestOnPrivateService_shouldSucceedWith200() throws Exception { - mvc.perform(get("/private/hello").contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk()); + mvc.perform(get("/private/hello").contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()); } @Test @WithMockUser(roles = "NO_ROLE") void givenAuthRequestOnPrivateService_shouldSucceedWith401() throws Exception { - mvc.perform(get("/private/hello").contentType(MediaType.APPLICATION_JSON)).andExpect(status().isForbidden()); + mvc.perform(get("/private/hello").contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isForbidden()); } @BeforeEach diff --git a/spring security integration test/src/test/java/com/metaxiii/fr/service/SecuredServiceTest.java b/spring security integration test/src/test/java/com/metaxiii/fr/service/SecuredServiceTest.java index feba9d80..6f07ed2e 100644 --- a/spring security integration test/src/test/java/com/metaxiii/fr/service/SecuredServiceTest.java +++ b/spring security integration test/src/test/java/com/metaxiii/fr/service/SecuredServiceTest.java @@ -12,8 +12,7 @@ @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) class SecuredServiceTest { - @Autowired - private SecuredService service; + @Autowired private SecuredService service; @Test void givenUnauthenticated_whenCallService_thenThrowsException() { diff --git a/spring-boot-start/src/main/java/com/metaxiii/fr/configuration/SecurityConfig.java b/spring-boot-start/src/main/java/com/metaxiii/fr/configuration/SecurityConfig.java index fcd0a40b..274a7d08 100644 --- a/spring-boot-start/src/main/java/com/metaxiii/fr/configuration/SecurityConfig.java +++ b/spring-boot-start/src/main/java/com/metaxiii/fr/configuration/SecurityConfig.java @@ -12,9 +12,6 @@ public class SecurityConfig { @Bean public SecurityFilterChain filterChain(final HttpSecurity http) throws Exception { - return http - .authorizeHttpRequests((autz) -> autz.anyRequest() - .permitAll()) - .build(); + return http.authorizeHttpRequests((autz) -> autz.anyRequest().permitAll()).build(); } } diff --git a/spring-boot-start/src/main/java/com/metaxiii/fr/exception/RestExceptionHandler.java b/spring-boot-start/src/main/java/com/metaxiii/fr/exception/RestExceptionHandler.java index 64925fee..0fc97afe 100644 --- a/spring-boot-start/src/main/java/com/metaxiii/fr/exception/RestExceptionHandler.java +++ b/spring-boot-start/src/main/java/com/metaxiii/fr/exception/RestExceptionHandler.java @@ -13,21 +13,23 @@ @ControllerAdvice public class RestExceptionHandler extends ResponseEntityExceptionHandler { - @ExceptionHandler({ BookNotFoundException.class }) + @ExceptionHandler({BookNotFoundException.class}) protected ResponseEntity handleNotFound(Exception exception, WebRequest webRequest) { - return handleExceptionInternal(exception, "Book not found", new HttpHeaders(), HttpStatus.NOT_FOUND, webRequest); + return handleExceptionInternal( + exception, "Book not found", new HttpHeaders(), HttpStatus.NOT_FOUND, webRequest); } - @ExceptionHandler( - { BookIdMismatchException.class, ConstraintViolationException.class, DataIntegrityViolationException.class } - ) + @ExceptionHandler({ + BookIdMismatchException.class, + ConstraintViolationException.class, + DataIntegrityViolationException.class + }) public ResponseEntity handleBadRequest(Exception exception, WebRequest webRequest) { return handleExceptionInternal( - exception, - exception.getLocalizedMessage(), - new HttpHeaders(), - HttpStatus.BAD_REQUEST, - webRequest - ); + exception, + exception.getLocalizedMessage(), + new HttpHeaders(), + HttpStatus.BAD_REQUEST, + webRequest); } } diff --git a/spring-boot-start/src/test/java/com/metaxiii/fr/controller/BookControllerTest.java b/spring-boot-start/src/test/java/com/metaxiii/fr/controller/BookControllerTest.java index e6cdb388..9f5311e6 100644 --- a/spring-boot-start/src/test/java/com/metaxiii/fr/controller/BookControllerTest.java +++ b/spring-boot-start/src/test/java/com/metaxiii/fr/controller/BookControllerTest.java @@ -30,8 +30,7 @@ public class BookControllerTest { private static final String API_ROOT = "/api/books"; - @Autowired - private MockMvc mockMvc; + @Autowired private MockMvc mockMvc; @Test void itshouldThrowsBookMismatchExceptionWhenUpdateHasDifferentBookIdAndId() throws Exception { @@ -40,27 +39,36 @@ void itshouldThrowsBookMismatchExceptionWhenUpdateHasDifferentBookIdAndId() thro book.setId(Long.valueOf(RandomStringUtils.secure().nextNumeric(6))); book.setAuthor("newAuthor"); mockMvc - .perform( - put(API_ROOT + location).with(csrf()).content(ObjectToJson(book)).contentType(MediaType.APPLICATION_JSON) - ) - .andDo(print()) - .andExpect(status().isBadRequest()); + .perform( + put(API_ROOT + location) + .with(csrf()) + .content(ObjectToJson(book)) + .contentType(MediaType.APPLICATION_JSON)) + .andDo(print()) + .andExpect(status().isBadRequest()); } @Test void whenCreateNewBook_thenCreated() throws Exception { final Book book = createRandomBook(); mockMvc - .perform(post(API_ROOT).with(csrf()).content(ObjectToJson(book)).contentType(MediaType.APPLICATION_JSON)) - .andDo(print()) - .andExpect(status().isCreated()); + .perform( + post(API_ROOT) + .with(csrf()) + .content(ObjectToJson(book)) + .contentType(MediaType.APPLICATION_JSON)) + .andDo(print()) + .andExpect(status().isCreated()); } @Test void whenDeleteCreatedBook_thenOk() throws Exception { final Book book = createRandomBook(); final String location = createBookAsUri(book); - mockMvc.perform(delete(API_ROOT + location).with(csrf())).andDo(print()).andExpect(status().isOk()); + mockMvc + .perform(delete(API_ROOT + location).with(csrf())) + .andDo(print()) + .andExpect(status().isOk()); mockMvc.perform(get(API_ROOT + location)).andDo(print()).andExpect(status().isNotFound()); } @@ -73,24 +81,29 @@ void whenGetAllBooks_thenOK() throws Exception { void whenGetBooksByTitle_thenOK() throws Exception { final Book book = createRandomBook(); createBookAsUri(book); - final MvcResult mvcResult = mockMvc - .perform(get(API_ROOT + "/title/" + book.getTitle()).with(csrf())) - .andDo(print()) - .andExpect(status().isOk()) - .andReturn(); - final List bookReturn = new JsonMapper().readValue( - mvcResult.getResponse().getContentAsString(), - new TypeReference<>() {} - ); + final MvcResult mvcResult = + mockMvc + .perform(get(API_ROOT + "/title/" + book.getTitle()).with(csrf())) + .andDo(print()) + .andExpect(status().isOk()) + .andReturn(); + final List bookReturn = + new JsonMapper() + .readValue(mvcResult.getResponse().getContentAsString(), new TypeReference<>() {}); assertFalse(bookReturn.isEmpty()); } private String createBookAsUri(final Book book) throws Exception { - final MvcResult mvcResult = mockMvc - .perform(post(API_ROOT).with(csrf()).content(ObjectToJson(book)).contentType(MediaType.APPLICATION_JSON)) - .andDo(print()) - .andExpect(status().isCreated()) - .andReturn(); + final MvcResult mvcResult = + mockMvc + .perform( + post(API_ROOT) + .with(csrf()) + .content(ObjectToJson(book)) + .contentType(MediaType.APPLICATION_JSON)) + .andDo(print()) + .andExpect(status().isCreated()) + .andReturn(); final Book bookReturn = getBook(mvcResult); return "/" + bookReturn.getId(); } @@ -103,11 +116,12 @@ private static Book getBook(final MvcResult mvcResult) throws UnsupportedEncodin void whenGetCreatedBookById_thenOK() throws Exception { final Book book = createRandomBook(); final String location = createBookAsUri(book); - final MvcResult mvcResult = mockMvc - .perform(get(API_ROOT + location).with(csrf())) - .andDo(print()) - .andExpect(status().isOk()) - .andReturn(); + final MvcResult mvcResult = + mockMvc + .perform(get(API_ROOT + location).with(csrf())) + .andDo(print()) + .andExpect(status().isOk()) + .andReturn(); final Book bookReturn = getBook(mvcResult); assertEquals(book.getTitle(), bookReturn.getTitle()); } @@ -115,9 +129,9 @@ void whenGetCreatedBookById_thenOK() throws Exception { @Test void whenGetNotExistBookById_thenNotFound() throws Exception { mockMvc - .perform(get(API_ROOT + "/" + RandomStringUtils.secure().nextNumeric(4)).with(csrf())) - .andDo(print()) - .andExpect(status().isNotFound()); + .perform(get(API_ROOT + "/" + RandomStringUtils.secure().nextNumeric(4)).with(csrf())) + .andDo(print()) + .andExpect(status().isNotFound()); } @Test @@ -125,9 +139,13 @@ void whenInvalidBook_thenError() throws Exception { final Book book = createRandomBook(); book.setAuthor(null); mockMvc - .perform(post(API_ROOT).with(csrf()).content(ObjectToJson(book)).contentType(MediaType.APPLICATION_JSON)) - .andDo(print()) - .andExpect(status().isBadRequest()); + .perform( + post(API_ROOT) + .with(csrf()) + .content(ObjectToJson(book)) + .contentType(MediaType.APPLICATION_JSON)) + .andDo(print()) + .andExpect(status().isBadRequest()); } private Book createRandomBook() { @@ -152,16 +170,19 @@ void whenUpdateCreatedBook_thenUpdated() throws Exception { book.setId(Long.parseLong(location.substring(1))); book.setAuthor("newAuthor"); mockMvc - .perform( - put(API_ROOT + location).with(csrf()).content(ObjectToJson(book)).contentType(MediaType.APPLICATION_JSON) - ) - .andDo(print()) - .andExpect(status().isOk()); - final MvcResult mvcResult = mockMvc - .perform(get(API_ROOT + location).with(csrf())) - .andDo(print()) - .andExpect(status().isOk()) - .andReturn(); + .perform( + put(API_ROOT + location) + .with(csrf()) + .content(ObjectToJson(book)) + .contentType(MediaType.APPLICATION_JSON)) + .andDo(print()) + .andExpect(status().isOk()); + final MvcResult mvcResult = + mockMvc + .perform(get(API_ROOT + location).with(csrf())) + .andDo(print()) + .andExpect(status().isOk()) + .andReturn(); final Book bookReturn = getBook(mvcResult); assertEquals("newAuthor", bookReturn.getAuthor()); } diff --git a/spring-boot-start/src/test/java/com/metaxiii/fr/controller/SimpleControllerTest.java b/spring-boot-start/src/test/java/com/metaxiii/fr/controller/SimpleControllerTest.java index e8e7d756..c39226af 100644 --- a/spring-boot-start/src/test/java/com/metaxiii/fr/controller/SimpleControllerTest.java +++ b/spring-boot-start/src/test/java/com/metaxiii/fr/controller/SimpleControllerTest.java @@ -14,8 +14,7 @@ @AutoConfigureMockMvc class SimpleControllerTest { - @Autowired - private MockMvc mockMvc; + @Autowired private MockMvc mockMvc; @Test void homePage() throws Exception { diff --git a/spring-boot-start/src/test/java/com/metaxiii/fr/service/impl/BookServiceImplTest.java b/spring-boot-start/src/test/java/com/metaxiii/fr/service/impl/BookServiceImplTest.java index b944cf06..c9ef1109 100644 --- a/spring-boot-start/src/test/java/com/metaxiii/fr/service/impl/BookServiceImplTest.java +++ b/spring-boot-start/src/test/java/com/metaxiii/fr/service/impl/BookServiceImplTest.java @@ -22,14 +22,11 @@ @ExtendWith(MockitoExtension.class) class BookServiceImplTest { - @InjectMocks - private BookServiceImpl bookService; + @InjectMocks private BookServiceImpl bookService; - @Mock - BookMapper mapper; + @Mock BookMapper mapper; - @Mock - private BookRepository repository; + @Mock private BookRepository repository; private static BookDTO getBookDTO() { return BookDTO.builder().id(1L).author("author").title("title").build(); @@ -37,37 +34,41 @@ private static BookDTO getBookDTO() { @Test void findAll() { - assertDoesNotThrow(() -> { - bookService.findAll(); - }); + assertDoesNotThrow( + () -> { + bookService.findAll(); + }); } @Test void findByTitle() { - assertDoesNotThrow(() -> { - bookService.findByTitle(anyString()); - }); + assertDoesNotThrow( + () -> { + bookService.findByTitle(anyString()); + }); } @Test void findById() { assertThrows(BookNotFoundException.class, () -> bookService.findById(1L)); when(repository.findById(1L)).thenReturn(Optional.of(getBook())); - assertDoesNotThrow(() -> { - bookService.findById(1L); - }); + assertDoesNotThrow( + () -> { + bookService.findById(1L); + }); } @Test void save() { - assertDoesNotThrow(() -> { - when(mapper.toEntity(any(BookDTO.class))).thenReturn(getBook()); - when(repository.save(any(Book.class))).thenReturn(getBook()); - final Book save = bookService.save(getBookDTO()); - assertEquals(1, save.getId()); - assertEquals("author", save.getAuthor()); - assertEquals("title", save.getTitle()); - }); + assertDoesNotThrow( + () -> { + when(mapper.toEntity(any(BookDTO.class))).thenReturn(getBook()); + when(repository.save(any(Book.class))).thenReturn(getBook()); + final Book save = bookService.save(getBookDTO()); + assertEquals(1, save.getId()); + assertEquals("author", save.getAuthor()); + assertEquals("title", save.getTitle()); + }); } private static Book getBook() { diff --git a/spring-data-get-last-record/src/main/java/com/metaxiii/fr/springdatagetlastrecord/entity/Post.java b/spring-data-get-last-record/src/main/java/com/metaxiii/fr/springdatagetlastrecord/entity/Post.java index 2264a850..8b33660f 100644 --- a/spring-data-get-last-record/src/main/java/com/metaxiii/fr/springdatagetlastrecord/entity/Post.java +++ b/spring-data-get-last-record/src/main/java/com/metaxiii/fr/springdatagetlastrecord/entity/Post.java @@ -11,8 +11,7 @@ @NoArgsConstructor public class Post { - @Id - private Long id; + @Id private Long id; private String title; private LocalDate publicationDate; diff --git a/spring-data-get-last-record/src/test/java/com/metaxiii/fr/springdatagetlastrecord/repository/PostServiceTest.java b/spring-data-get-last-record/src/test/java/com/metaxiii/fr/springdatagetlastrecord/repository/PostServiceTest.java index 2c527515..8113836c 100644 --- a/spring-data-get-last-record/src/test/java/com/metaxiii/fr/springdatagetlastrecord/repository/PostServiceTest.java +++ b/spring-data-get-last-record/src/test/java/com/metaxiii/fr/springdatagetlastrecord/repository/PostServiceTest.java @@ -13,8 +13,7 @@ @Sql(scripts = "classpath:/data.sql") class PostServiceTest { - @Autowired - private PostRepository repository; + @Autowired private PostRepository repository; @Test void givenPosts_whenUsingQueryAnnotation_thenReturnLastPost() { diff --git a/springwebclient-vs-resttemplate/src/main/java/com/metaxiii/fr/controller/TweetController.java b/springwebclient-vs-resttemplate/src/main/java/com/metaxiii/fr/controller/TweetController.java index 71dcfb93..d0d53343 100644 --- a/springwebclient-vs-resttemplate/src/main/java/com/metaxiii/fr/controller/TweetController.java +++ b/springwebclient-vs-resttemplate/src/main/java/com/metaxiii/fr/controller/TweetController.java @@ -28,10 +28,10 @@ public TweetController(final ServerProperties serverProperties) { @GetMapping("/slow-service-tweets") public Mono> getAllTweets() { return Mono.just( - Arrays.asList( - new Tweet("RestTemplate rules", "@user1"), - new Tweet("WebClient is better", "@user2"), - new Tweet("OK, both are useful", "@user1"))) + Arrays.asList( + new Tweet("RestTemplate rules", "@user1"), + new Tweet("WebClient is better", "@user2"), + new Tweet("OK, both are useful", "@user1"))) .delayElement(Duration.ofSeconds(1)); } @@ -42,22 +42,25 @@ public Mono> getTweetsBlocking() { .get() .uri("/slow-service-tweets") .retrieve() - .bodyToMono(new ParameterizedTypeReference>() { - }) - .doOnNext(result -> { - result.forEach(tweet -> log.info(tweet.toString())); - log.info("Exiting Controller!"); - }); + .bodyToMono(new ParameterizedTypeReference>() {}) + .doOnNext( + result -> { + result.forEach(tweet -> log.info(tweet.toString())); + log.info("Exiting Controller!"); + }); } @GetMapping(value = "/tweets-non-blocking", produces = MediaType.TEXT_EVENT_STREAM_VALUE) public Flux getTweetsNonBlocking() { log.info("Starting NON-BLOCKING Controller!"); - final Flux tweetFlux = WebClient.create() - .get() - .uri(URI.create("http://localhost:" + serverProperties.getPort() + "/slow-service-tweets")) - .retrieve() - .bodyToFlux(Tweet.class); + final Flux tweetFlux = + WebClient.create() + .get() + .uri( + URI.create( + "http://localhost:" + serverProperties.getPort() + "/slow-service-tweets")) + .retrieve() + .bodyToFlux(Tweet.class); // noinspection CallingSubscribeInNonBlockingScope tweetFlux.subscribe(tweet -> log.info(tweet.toString())); log.info("Exiting NON-BLOCKING Controller!"); diff --git a/springwebclient-vs-resttemplate/src/test/java/com/metaxiii/fr/controller/TweetControllerTest.java b/springwebclient-vs-resttemplate/src/test/java/com/metaxiii/fr/controller/TweetControllerTest.java index 8703b226..9b2ef208 100644 --- a/springwebclient-vs-resttemplate/src/test/java/com/metaxiii/fr/controller/TweetControllerTest.java +++ b/springwebclient-vs-resttemplate/src/test/java/com/metaxiii/fr/controller/TweetControllerTest.java @@ -15,34 +15,39 @@ @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) class TweetControllerTest { - @Autowired - private WebTestClient webTestClient; + @Autowired private WebTestClient webTestClient; @Test void getAllTweets() { webTestClient - .get() - .uri("/slow-service-tweets") - .exchange() - .expectStatus() - .is2xxSuccessful() - .expectBodyList(Tweet.class) - .value(tweets -> assertEquals(3, tweets.size())); + .get() + .uri("/slow-service-tweets") + .exchange() + .expectStatus() + .is2xxSuccessful() + .expectBodyList(Tweet.class) + .value(tweets -> assertEquals(3, tweets.size())); } @Test void getTweetsBlocking() { - webTestClient.get().uri("/tweets-blocking").exchange().expectStatus().is2xxSuccessful().expectBodyList(Tweet.class); + webTestClient + .get() + .uri("/tweets-blocking") + .exchange() + .expectStatus() + .is2xxSuccessful() + .expectBodyList(Tweet.class); } @Test void getTweetsNonBlocking() { webTestClient - .get() - .uri("/tweets-non-blocking") - .exchange() - .expectStatus() - .is2xxSuccessful() - .expectBodyList(Tweet.class); + .get() + .uri("/tweets-non-blocking") + .exchange() + .expectStatus() + .is2xxSuccessful() + .expectBodyList(Tweet.class); } } diff --git a/string-cast-vs-valueof/src/test/java/com/metaxiii/fr/AppTest.java b/string-cast-vs-valueof/src/test/java/com/metaxiii/fr/AppTest.java index dc3ffc0a..710e6f6b 100644 --- a/string-cast-vs-valueof/src/test/java/com/metaxiii/fr/AppTest.java +++ b/string-cast-vs-valueof/src/test/java/com/metaxiii/fr/AppTest.java @@ -22,22 +22,20 @@ void itShouldCast1ToStringAndStringValueOf() { } @Test - @SuppressWarnings({ "DataFlowIssue", "unused" }) + @SuppressWarnings({"DataFlowIssue", "unused"}) void itShouldCast2NonStringObject() { final Object obj = 42; assertThrows( - ClassCastException.class, - () -> { - final String castResult = (String) obj; - } - ); + ClassCastException.class, + () -> { + final String castResult = (String) obj; + }); final Object obj2 = List.of("Java", "is", "cool"); assertThrows( - ClassCastException.class, - () -> { - final String castResult = (String) obj2; - } - ); + ClassCastException.class, + () -> { + final String castResult = (String) obj2; + }); String valueOfResult = String.valueOf(obj); assertEquals("42", valueOfResult); valueOfResult = String.valueOf(obj2); @@ -45,7 +43,7 @@ void itShouldCast2NonStringObject() { } @Test - @SuppressWarnings({ "CastCanBeRemovedNarrowingVariableType", "ConstantValue" }) + @SuppressWarnings({"CastCanBeRemovedNarrowingVariableType", "ConstantValue"}) void itShouldCast3HandleNullValues() { final Object obj = null; final String castResult = (String) obj; diff --git a/string-delete-digits/src/test/java/com/metaxiii/fr/AppTest.java b/string-delete-digits/src/test/java/com/metaxiii/fr/AppTest.java index a6c02e75..035c2625 100644 --- a/string-delete-digits/src/test/java/com/metaxiii/fr/AppTest.java +++ b/string-delete-digits/src/test/java/com/metaxiii/fr/AppTest.java @@ -21,12 +21,13 @@ void whenUsingApacheCommonsLang_thenGetExpectedResult() { @Test void whenUsingCharacterStream_thenGetExpectedResult() { - final var updatedString = INPUT_STRING - .chars() - .filter(c -> !Character.isDigit(c)) - .mapToObj(c -> (char) c) - .map(String::valueOf) - .collect(Collectors.joining()); + final var updatedString = + INPUT_STRING + .chars() + .filter(c -> !Character.isDigit(c)) + .mapToObj(c -> (char) c) + .map(String::valueOf) + .collect(Collectors.joining()); assertEquals(EXPECTED_STRING, updatedString); } diff --git a/string-insert-emoji/src/test/java/com/metaxiii/fr/AppTest.java b/string-insert-emoji/src/test/java/com/metaxiii/fr/AppTest.java index 7e7f54b2..2de9cedf 100644 --- a/string-insert-emoji/src/test/java/com/metaxiii/fr/AppTest.java +++ b/string-insert-emoji/src/test/java/com/metaxiii/fr/AppTest.java @@ -12,7 +12,8 @@ class AppTest { @Test void givenCodePoint_whenConvertToEmoji_thenCorrectString() { final var textWithEmoji = - "Java Tutorials and Guides at Baeldung. " + new String(Character.toChars(SMILEY_CODE_POINT)); + "Java Tutorials and Guides at Baeldung. " + + new String(Character.toChars(SMILEY_CODE_POINT)); assertEquals(EXPECTED, textWithEmoji); } diff --git a/string-to-offsetdatetime/src/test/java/com/metaxiii/fr/AppTest.java b/string-to-offsetdatetime/src/test/java/com/metaxiii/fr/AppTest.java index 5e0f466a..f556ba98 100644 --- a/string-to-offsetdatetime/src/test/java/com/metaxiii/fr/AppTest.java +++ b/string-to-offsetdatetime/src/test/java/com/metaxiii/fr/AppTest.java @@ -16,14 +16,16 @@ void givenDateTimeStringAndFormatter_whenUsingDateTimeFormatter_thenConvertToOff final String customDateTimeString = "11-04-2024 10:15:30 +0100"; final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss Z"); final OffsetDateTime offsetDateTime = OffsetDateTime.parse(customDateTimeString, formatter); - final OffsetDateTime expected = OffsetDateTime.of(2024, 4, 11, 10, 15, 30, 0, ZoneOffset.ofHours(1)); + final OffsetDateTime expected = + OffsetDateTime.of(2024, 4, 11, 10, 15, 30, 0, ZoneOffset.ofHours(1)); assertEquals(expected, offsetDateTime); } @Test void givenDateTimeString_whenUsingOffsetDateTimeParse_thenConvertToOffsetDateTime() { final OffsetDateTime offsetDateTime = OffsetDateTime.parse(DATE_TIME_STRING); - final OffsetDateTime expected = OffsetDateTime.of(2024, 4, 11, 10, 15, 30, 0, ZoneOffset.ofHours(1)); + final OffsetDateTime expected = + OffsetDateTime.of(2024, 4, 11, 10, 15, 30, 0, ZoneOffset.ofHours(1)); assertEquals(expected, offsetDateTime); } } diff --git a/test-whether-file-image/src/test/java/com/metaxiii/fr/ImageValidatorTest.java b/test-whether-file-image/src/test/java/com/metaxiii/fr/ImageValidatorTest.java index fd4705f8..b383bbd1 100644 --- a/test-whether-file-image/src/test/java/com/metaxiii/fr/ImageValidatorTest.java +++ b/test-whether-file-image/src/test/java/com/metaxiii/fr/ImageValidatorTest.java @@ -16,7 +16,8 @@ void givenFakeImageFile_whenCheckedUsingImageIO_thenShouldReturnFalse() throws I } @Test - void givenFakeImageFile_whenCheckedUsingProbeContentType_thenShouldReturnTrue() throws IOException { + void givenFakeImageFile_whenCheckedUsingProbeContentType_thenShouldReturnTrue() + throws IOException { final File file = new File("src/test/resources/fake-image.jpg"); assertTrue(ImageValidator.isImageFileUsingProbeContentType(file)); } @@ -46,7 +47,8 @@ void givenImageFile_whenCheckedUsingTika_thenShouldReturnTrue() throws IOExcepti } @Test - void givenNonImageFile_whenCheckedUsingProbeContentType_thenShouldReturnFalse() throws IOException { + void givenNonImageFile_whenCheckedUsingProbeContentType_thenShouldReturnFalse() + throws IOException { final File file = new File("src/test/resources/test-document.txt"); assertFalse(ImageValidator.isImageFileUsingProbeContentType(file)); }