From 1cba1b043cadbd12f499e34d36a94ef902df1cea Mon Sep 17 00:00:00 2001 From: eugenp Date: Thu, 24 Aug 2017 13:11:52 +0300 Subject: [PATCH] minor formatting cleanup --- .../blockingqueue/NumbersProducer.java | 6 +- .../concurrent/delayqueue/DelayObject.java | 5 +- .../adapter/LuxuryCarsSpeed.java | 4 +- .../adapter/LuxuryCarsSpeedAdapter.java | 2 + .../baeldung/designpatterns/bridge/Blue.java | 2 +- .../decorator/DecoratorPatternDriver.java | 12 +- .../proxy/ExpensiveObjectImpl.java | 6 +- .../forkjoin/CustomRecursiveAction.java | 3 +- .../com/baeldung/java/reflection/Greeter.java | 4 +- .../baeldung/map/iteration/MapIteration.java | 7 +- .../com/baeldung/maths/BigIntegerImpl.java | 2 +- .../cookies/PersistentCookieStore.java | 3 +- .../com/baeldung/printscreen/Screenshot.java | 3 +- .../java/com/baeldung/uuid/UUIDGenerator.java | 38 ++- .../CompletableFutureLongRunningUnitTest.java | 39 +-- .../datetime/UseLocalDateTimeUnitTest.java | 6 +- .../datetime/UseLocalDateUnitTest.java | 15 +- .../FunctionalInterfaceUnitTest.java | 11 +- ...oncurrentMapAggregateStatusManualTest.java | 6 +- ...ncurretMapMemoryConsistencyManualTest.java | 24 +- .../Java8GroupingByCollectorUnitTest.java | 244 +++++++----------- .../baeldung/java8/Java8MapAndFlatMap.java | 20 +- .../java8/JavaFolderSizeUnitTest.java | 15 +- .../comparator/Java8ComparatorUnitTest.java | 74 +++--- .../java8/optional/OptionalUnitTest.java | 54 ++-- .../FlattenNestedListUnitTest.java | 4 +- .../java/com/baeldung/maths/RoundTest.java | 24 +- .../baeldung/socket/EchoIntegrationTest.java | 3 +- .../socket/GreetServerIntegrationTest.java | 3 +- .../org/baeldung/java/JavaIoUnitTest.java | 9 +- .../org/baeldung/java/JavaRandomUnitTest.java | 16 +- .../java/JavaTimerLongRunningUnitTest.java | 4 +- .../org/baeldung/java/sorting/Employee.java | 11 +- .../java/sorting/JavaSortingUnitTest.java | 6 +- .../BookControllerFeignClientBuilder.java | 8 +- .../feign/clients/BookClientLiveTest.java | 14 +- .../deserialization/jacksoninject/Author.java | 3 +- .../deserialization/jacksoninject/Person.java | 2 +- .../deserialization/jsoncreator/Author.java | 5 +- .../deserialization/jsondeserialize/Book.java | 3 +- .../CustomDateDeserializer.java | 6 +- .../deserialization/jsondeserialize/Item.java | 3 +- .../deserialization/jsonsetter/Author.java | 3 +- .../com/baeldung/jackson/domain/Book.java | 2 +- .../com/baeldung/jackson/domain/Course.java | 4 +- .../com/baeldung/jackson/domain/Item.java | 3 +- .../com/baeldung/jackson/domain/Person.java | 3 +- .../jackson/entities/ClassWithAMap.java | 20 +- .../com/baeldung/jackson/entities/MyPair.java | 128 ++++----- .../com/baeldung/jackson/format/User.java | 17 +- .../jackson/inclusion/jsonignore/Person.java | 3 +- .../jsonignoreproperties/Course.java | 6 +- .../inheritance/ItemIdAddedToUser.java | 5 +- .../inheritance/ItemIdRemovedFromUser.java | 5 +- .../jackson/miscellaneous/custom/Course.java | 4 +- .../custom/CustomCourseAnnotation.java | 4 +- .../jackson/miscellaneous/custom/Item.java | 3 +- .../jackson/miscellaneous/disable/Author.java | 2 +- .../baeldung/jackson/polymorphism/Order.java | 8 +- .../serialization/ActorJacksonSerializer.java | 7 +- .../serialization/MyPairDeserializer.java | 9 +- .../serialization/MyPairSerializer.java | 16 +- .../serialization/jsongetter/Author.java | 1 - .../jsonpropertyorder/Author.java | 3 +- .../serialization/jsonserialize/Book.java | 3 +- .../jsonserialize/CustomDateSerializer.java | 6 +- .../serialization/jsonserialize/Item.java | 3 +- .../serialization/jsonvalue/Course.java | 4 +- .../extra/ExtraAnnotationUnitTest.java | 12 +- .../extra/IdentityReferenceBeans.java | 3 +- .../bidirection/CustomListSerializer.java | 1 + .../date/CustomLocalDateTimeSerializer.java | 1 - .../deserialization/ItemDeserializer.java | 6 +- .../ItemDeserializerOnClass.java | 6 +- .../JacksonMapDeserializeUnitTest.java | 65 +++-- .../jacksoninject/JacksonInjectUnitTest.java | 4 +- .../jsonanysetter/JsonAnySetterUnitTest.java | 27 +- .../jsoncreator/JsonCreatorUnitTest.java | 9 +- .../JsonDeserializeUnitTest.java | 3 +- .../jsonsetter/JsonSetterUnitTest.java | 7 +- .../jackson/dynamicIgnore/Address.java | 1 - .../jackson/dynamicIgnore/Hidable.java | 1 - .../jackson/dynamicIgnore/Person.java | 3 +- .../jackson/format/JsonFormatUnitTest.java | 16 +- .../jsonfilter/JsonFilterUnitTest.java | 6 +- .../jackson/general/jsonformat/Book.java | 4 +- .../jsonformat/JsonFormatUnitTest.java | 5 +- .../general/jsonidentityinfo/Author.java | 4 +- .../general/jsonidentityinfo/Course.java | 5 +- .../general/jsonidentityinfo/Item.java | 7 +- .../general/jsonidentityinfo/Person.java | 3 +- .../jackson/general/jsonproperty/Item.java | 3 +- .../jsonproperty/JsonPropertyUnitTest.java | 9 +- .../jsonunwrapped/JsonUnwrappedUnitTest.java | 1 - .../general/jsonview/JsonViewUnitTest.java | 7 +- .../jackson/general/reference/Course.java | 5 +- .../jackson/general/reference/Item.java | 3 +- .../jackson/general/reference/Person.java | 3 +- .../general/reference/ReferenceUnitTest.java | 2 +- .../JsonAutoDetectUnitTest.java | 2 +- .../jsoninclude/JsonIncludeUnitTest.java | 1 - .../ItemIdRemovedFromUserUnitTest.java | 12 +- .../inheritance/SubTypeHandlingUnitTest.java | 6 +- .../TypeInfoInclusionUnitTest.java | 12 +- .../jackson/node/ExampleStructure.java | 3 +- .../jackson/node/NodeOperationUnitTest.java | 36 ++- .../objectmapper/CustomCarDeserializer.java | 2 - .../objectmapper/CustomCarSerializer.java | 6 +- .../JavaReadWriteJsonExampleUnitTest.java | 3 +- ...izationDeserializationFeatureUnitTest.java | 2 +- .../polymorphism/PolymorphismUnitTest.java | 8 +- .../sandbox/JacksonPrettyPrintUnitTest.java | 6 +- .../jackson/sandbox/SandboxUnitTest.java | 5 +- .../JacksonMapSerializeUnitTest.java | 70 +++-- .../JacksonSerializeUnitTest.java | 7 +- .../jsonrawvalue/JsonRawValueUnitTest.java | 1 - .../JacksonStreamingAPIUnitTest.java | 19 +- .../test/JacksonAnnotationUnitTest.java | 31 ++- .../JacksonBidirectionRelationUnitTest.java | 12 +- ...ksonCollectionDeserializationUnitTest.java | 3 +- .../jackson/test/JacksonDateUnitTest.java | 6 +- .../test/JacksonExceptionsUnitTest.java | 56 ++-- .../jackson/test/JacksonJsonViewUnitTest.java | 16 +- .../JacksonSerializationIgnoreUnitTest.java | 15 +- .../try1/RestLoaderRequestDeserializer.java | 6 +- .../xml/XMLSerializeDeserializeUnitTest.java | 3 +- .../SpringBootAnnotatedApp.java | 2 +- .../SpringBootPlainApp.java | 2 +- .../components/AttrListener.java | 5 +- .../components/EchoServlet.java | 5 +- .../components/HelloFilter.java | 5 +- .../components/HelloServlet.java | 10 +- .../MySQLAutoconfiguration.java | 16 +- .../example/MyUserRepository.java | 4 +- .../baeldung/displayallbeans/Application.java | 6 +- .../controller/FooController.java | 6 +- .../displayallbeans/service/FooService.java | 10 +- .../config/PersistenceConfig.java | 5 +- .../FailureAnalyzerApplication.java | 2 +- ...yBeanNotOfRequiredTypeFailureAnalyzer.java | 16 +- .../com/baeldung/git/CommitIdApplication.java | 2 +- .../graphql/GraphqlConfiguration.java | 6 +- .../java/com/baeldung/graphql/Mutation.java | 3 +- .../InternationalizationApp.java | 2 +- .../src/main/java/com/baeldung/intro/App.java | 8 +- .../intro/controller/HomeController.java | 6 +- .../baeldung/servlets/ApplicationMain.java | 2 +- .../configuration/WebMvcConfigure.java | 7 +- .../servlets/props/PropertySourcesLoader.java | 3 +- .../servlets/javaee/AnnotationServlet.java | 7 +- .../baeldung/toggle/EmployeeRepository.java | 2 +- .../java/com/baeldung/toggle/MyFeatures.java | 10 +- .../com/baeldung/utils/UtilsApplication.java | 12 +- .../utils/controller/UtilsController.java | 66 ++--- .../webjar/WebjarsdemoApplication.java | 2 +- .../main/java/org/baeldung/Application.java | 2 +- .../org/baeldung/boot/DemoApplication.java | 2 +- .../baeldung/boot/components/FooService.java | 4 +- .../boot/exceptions/CommonException.java | 4 +- .../boot/exceptions/FooNotFoundException.java | 4 +- .../java/org/baeldung/boot/model/Foo.java | 1 - .../baeldung/boot/service/FooController.java | 2 +- .../controller/GenericEntityController.java | 18 +- .../org/baeldung/endpoints/MyHealthCheck.java | 8 +- .../jsoncomponent/UserCombinedSerializer.java | 6 +- .../jsoncomponent/UserJsonDeserializer.java | 3 +- .../jsoncomponent/UserJsonSerializer.java | 3 +- .../baeldung/main/SpringBootApplication.java | 2 +- .../monitor/jmx/MonitoringConfig.java | 3 +- .../baeldung/service/LoginServiceImpl.java | 3 +- .../session/exception/Application.java | 2 +- .../repository/FooRepositoryImpl.java | 6 +- .../baeldung/websocket/client/Message.java | 3 +- .../client/MyStompSessionHandler.java | 14 +- .../websocket/client/StompClient.java | 4 +- ...otWithServletComponentIntegrationTest.java | 10 +- ...ithoutServletComponentIntegrationTest.java | 4 +- .../AutoconfigurationIntegrationTest.java | 2 +- .../DisplayBeanIntegrationTest.java | 18 +- .../java/com/baeldung/intro/AppLiveTest.java | 16 +- .../toggle/ToggleIntegrationTest.java | 9 +- .../utils/UtilsControllerIntegrationTest.java | 8 +- .../MyStompSessionHandlerIntegrationTest.java | 7 +- .../SpringBootApplicationIntegrationTest.java | 34 ++- .../SpringBootMailIntegrationTest.java | 8 +- .../EmployeeControllerIntegrationTest.java | 16 +- .../EmployeeRepositoryIntegrationTest.java | 4 +- ...EmployeeRestControllerIntegrationTest.java | 16 +- .../EmployeeServiceImplIntegrationTest.java | 25 +- .../DetailsServiceClientIntegrationTest.java | 3 +- .../UserJsonSerializerIntegrationTest.java | 1 - .../security/CustomAccessDeniedHandler.java | 2 +- .../baeldung/spring/SecSecurityConfig.java | 4 +- .../RedirectionSecurityIntegrationTest.java | 57 ++-- 194 files changed, 1147 insertions(+), 1005 deletions(-) diff --git a/core-java/src/main/java/com/baeldung/concurrent/blockingqueue/NumbersProducer.java b/core-java/src/main/java/com/baeldung/concurrent/blockingqueue/NumbersProducer.java index 9dcd0a3e47..b301e994d5 100644 --- a/core-java/src/main/java/com/baeldung/concurrent/blockingqueue/NumbersProducer.java +++ b/core-java/src/main/java/com/baeldung/concurrent/blockingqueue/NumbersProducer.java @@ -19,13 +19,15 @@ public class NumbersProducer implements Runnable { try { generateNumbers(); } catch (InterruptedException e) { - Thread.currentThread().interrupt(); + Thread.currentThread() + .interrupt(); } } private void generateNumbers() throws InterruptedException { for (int i = 0; i < 100; i++) { - numbersQueue.put(ThreadLocalRandom.current().nextInt(100)); + numbersQueue.put(ThreadLocalRandom.current() + .nextInt(100)); } for (int j = 0; j < poisonPillPerProducer; j++) { numbersQueue.put(poisonPill); diff --git a/core-java/src/main/java/com/baeldung/concurrent/delayqueue/DelayObject.java b/core-java/src/main/java/com/baeldung/concurrent/delayqueue/DelayObject.java index 5f72758e71..312eb929ed 100644 --- a/core-java/src/main/java/com/baeldung/concurrent/delayqueue/DelayObject.java +++ b/core-java/src/main/java/com/baeldung/concurrent/delayqueue/DelayObject.java @@ -27,9 +27,6 @@ public class DelayObject implements Delayed { @Override public String toString() { - return "{" + - "data='" + data + '\'' + - ", startTime=" + startTime + - '}'; + return "{" + "data='" + data + '\'' + ", startTime=" + startTime + '}'; } } \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/designpatterns/adapter/LuxuryCarsSpeed.java b/core-java/src/main/java/com/baeldung/designpatterns/adapter/LuxuryCarsSpeed.java index 278329b994..0b97b8228c 100644 --- a/core-java/src/main/java/com/baeldung/designpatterns/adapter/LuxuryCarsSpeed.java +++ b/core-java/src/main/java/com/baeldung/designpatterns/adapter/LuxuryCarsSpeed.java @@ -4,11 +4,11 @@ public class LuxuryCarsSpeed { public double bugattiVeyronInMPH() { return 268; } - + public double mcLarenInMPH() { return 241; } - + public double astonMartinInMPH() { return 220; } diff --git a/core-java/src/main/java/com/baeldung/designpatterns/adapter/LuxuryCarsSpeedAdapter.java b/core-java/src/main/java/com/baeldung/designpatterns/adapter/LuxuryCarsSpeedAdapter.java index 84f7be2729..d9255f0910 100644 --- a/core-java/src/main/java/com/baeldung/designpatterns/adapter/LuxuryCarsSpeedAdapter.java +++ b/core-java/src/main/java/com/baeldung/designpatterns/adapter/LuxuryCarsSpeedAdapter.java @@ -2,6 +2,8 @@ package com.baeldung.designpatterns.adapter; public interface LuxuryCarsSpeedAdapter { public double bugattiVeyronInKMPH(); + public double mcLarenInKMPH(); + public double astonMartinInKMPH(); } diff --git a/core-java/src/main/java/com/baeldung/designpatterns/bridge/Blue.java b/core-java/src/main/java/com/baeldung/designpatterns/bridge/Blue.java index 97a4a9508c..ed3f75b4a1 100644 --- a/core-java/src/main/java/com/baeldung/designpatterns/bridge/Blue.java +++ b/core-java/src/main/java/com/baeldung/designpatterns/bridge/Blue.java @@ -5,7 +5,7 @@ import static com.baeldung.designpatterns.util.LogerUtil.LOG; public class Blue implements Color { @Override - public void fillColor() { + public void fillColor() { LOG.info("Color : Blue"); } diff --git a/core-java/src/main/java/com/baeldung/designpatterns/decorator/DecoratorPatternDriver.java b/core-java/src/main/java/com/baeldung/designpatterns/decorator/DecoratorPatternDriver.java index f70991da6b..70b4f801cd 100644 --- a/core-java/src/main/java/com/baeldung/designpatterns/decorator/DecoratorPatternDriver.java +++ b/core-java/src/main/java/com/baeldung/designpatterns/decorator/DecoratorPatternDriver.java @@ -5,16 +5,14 @@ import static com.baeldung.designpatterns.util.LogerUtil.LOG; public class DecoratorPatternDriver { public static void main(String[] args) { - //christmas tree with just one Garland + // christmas tree with just one Garland ChristmasTree tree1 = new Garland(new ChristmasTreeImpl()); LOG.info(tree1.decorate()); - - //christmas tree with two Garlands and one Bubble lights - ChristmasTree tree2 = new BubbleLights(new Garland( - new Garland(new ChristmasTreeImpl())) - ); + + // christmas tree with two Garlands and one Bubble lights + ChristmasTree tree2 = new BubbleLights(new Garland(new Garland(new ChristmasTreeImpl()))); LOG.info(tree2.decorate()); - + } } diff --git a/core-java/src/main/java/com/baeldung/designpatterns/proxy/ExpensiveObjectImpl.java b/core-java/src/main/java/com/baeldung/designpatterns/proxy/ExpensiveObjectImpl.java index 7014d3811c..de31e22b30 100644 --- a/core-java/src/main/java/com/baeldung/designpatterns/proxy/ExpensiveObjectImpl.java +++ b/core-java/src/main/java/com/baeldung/designpatterns/proxy/ExpensiveObjectImpl.java @@ -7,14 +7,14 @@ public class ExpensiveObjectImpl implements ExpensiveObject { public ExpensiveObjectImpl() { heavyInitialConfiguration(); } - + @Override public void process() { LOG.info("processing complete."); } - + private void heavyInitialConfiguration() { LOG.info("Loading initial configuration..."); } - + } \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/forkjoin/CustomRecursiveAction.java b/core-java/src/main/java/com/baeldung/forkjoin/CustomRecursiveAction.java index ae79787570..ebe59e33b1 100644 --- a/core-java/src/main/java/com/baeldung/forkjoin/CustomRecursiveAction.java +++ b/core-java/src/main/java/com/baeldung/forkjoin/CustomRecursiveAction.java @@ -43,6 +43,7 @@ public class CustomRecursiveAction extends RecursiveAction { private void processing(String work) { String result = work.toUpperCase(); - logger.info("This result - (" + result + ") - was processed by " + Thread.currentThread().getName()); + logger.info("This result - (" + result + ") - was processed by " + Thread.currentThread() + .getName()); } } diff --git a/core-java/src/main/java/com/baeldung/java/reflection/Greeter.java b/core-java/src/main/java/com/baeldung/java/reflection/Greeter.java index ede269528a..57aefdd169 100644 --- a/core-java/src/main/java/com/baeldung/java/reflection/Greeter.java +++ b/core-java/src/main/java/com/baeldung/java/reflection/Greeter.java @@ -5,6 +5,6 @@ import java.lang.annotation.RetentionPolicy; @Retention(RetentionPolicy.RUNTIME) public @interface Greeter { - - public String greet() default ""; + + public String greet() default ""; } diff --git a/core-java/src/main/java/com/baeldung/map/iteration/MapIteration.java b/core-java/src/main/java/com/baeldung/map/iteration/MapIteration.java index 2bc078cdb0..b0c32e1487 100644 --- a/core-java/src/main/java/com/baeldung/map/iteration/MapIteration.java +++ b/core-java/src/main/java/com/baeldung/map/iteration/MapIteration.java @@ -44,7 +44,8 @@ public class MapIteration { } public void iterateUsingIteratorAndEntry(Map map) { - Iterator> iterator = map.entrySet().iterator(); + Iterator> iterator = map.entrySet() + .iterator(); while (iterator.hasNext()) { Map.Entry pair = iterator.next(); System.out.println(pair.getKey() + ":" + pair.getValue()); @@ -58,7 +59,9 @@ public class MapIteration { } public void iterateUsingStreamAPI(Map map) { - map.entrySet().stream().forEach(e -> System.out.println(e.getKey() + ":" + e.getValue())); + map.entrySet() + .stream() + .forEach(e -> System.out.println(e.getKey() + ":" + e.getValue())); } public void iterateKeys(Map map) { diff --git a/core-java/src/main/java/com/baeldung/maths/BigIntegerImpl.java b/core-java/src/main/java/com/baeldung/maths/BigIntegerImpl.java index dc509429f9..9f46345e04 100644 --- a/core-java/src/main/java/com/baeldung/maths/BigIntegerImpl.java +++ b/core-java/src/main/java/com/baeldung/maths/BigIntegerImpl.java @@ -8,7 +8,7 @@ public class BigIntegerImpl { BigInteger numStarsMilkyWay = new BigInteger("8731409320171337804361260816606476"); BigInteger numStarsAndromeda = new BigInteger("5379309320171337804361260816606476"); - + BigInteger totalStars = numStarsMilkyWay.add(numStarsAndromeda); } diff --git a/core-java/src/main/java/com/baeldung/networking/cookies/PersistentCookieStore.java b/core-java/src/main/java/com/baeldung/networking/cookies/PersistentCookieStore.java index 5d30491cfe..4f34972b1e 100644 --- a/core-java/src/main/java/com/baeldung/networking/cookies/PersistentCookieStore.java +++ b/core-java/src/main/java/com/baeldung/networking/cookies/PersistentCookieStore.java @@ -9,7 +9,8 @@ public class PersistentCookieStore implements CookieStore, Runnable { public PersistentCookieStore() { store = new CookieManager().getCookieStore(); // deserialize cookies into store - Runtime.getRuntime().addShutdownHook(new Thread(this)); + Runtime.getRuntime() + .addShutdownHook(new Thread(this)); } @Override diff --git a/core-java/src/main/java/com/baeldung/printscreen/Screenshot.java b/core-java/src/main/java/com/baeldung/printscreen/Screenshot.java index 7f87b47476..11716b961d 100644 --- a/core-java/src/main/java/com/baeldung/printscreen/Screenshot.java +++ b/core-java/src/main/java/com/baeldung/printscreen/Screenshot.java @@ -14,7 +14,8 @@ public class Screenshot { } public void getScreenshot(int timeToWait) throws Exception { - Rectangle rectangle = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()); + Rectangle rectangle = new Rectangle(Toolkit.getDefaultToolkit() + .getScreenSize()); Robot robot = new Robot(); BufferedImage img = robot.createScreenCapture(rectangle); ImageIO.write(img, "jpg", new File(path)); diff --git a/core-java/src/main/java/com/baeldung/uuid/UUIDGenerator.java b/core-java/src/main/java/com/baeldung/uuid/UUIDGenerator.java index 23baf5d5b4..dcf186de93 100644 --- a/core-java/src/main/java/com/baeldung/uuid/UUIDGenerator.java +++ b/core-java/src/main/java/com/baeldung/uuid/UUIDGenerator.java @@ -6,16 +6,16 @@ import java.security.NoSuchAlgorithmException; import java.util.UUID; public class UUIDGenerator { - + /** * These are predefined UUID for name spaces */ - private static final String NAMESPACE_DNS = "6ba7b810-9dad-11d1-80b4-00c04fd430c8"; - private static final String NAMESPACE_URL = "6ba7b811-9dad-11d1-80b4-00c04fd430c8"; - private static final String NAMESPACE_OID = "6ba7b812-9dad-11d1-80b4-00c04fd430c8"; - private static final String NAMESPACE_X500 = "6ba7b814-9dad-11d1-80b4-00c04fd430c8"; + private static final String NAMESPACE_DNS = "6ba7b810-9dad-11d1-80b4-00c04fd430c8"; + private static final String NAMESPACE_URL = "6ba7b811-9dad-11d1-80b4-00c04fd430c8"; + private static final String NAMESPACE_OID = "6ba7b812-9dad-11d1-80b4-00c04fd430c8"; + private static final String NAMESPACE_X500 = "6ba7b814-9dad-11d1-80b4-00c04fd430c8"; - private static final char[] hexArray = "0123456789ABCDEF".toCharArray(); + private static final char[] hexArray = "0123456789ABCDEF".toCharArray(); public static void main(String[] args) { try { @@ -35,7 +35,7 @@ public class UUIDGenerator { UUID uuid = UUID.randomUUID(); return uuid; } - + /** * Type 3 UUID Generation * @@ -47,7 +47,7 @@ public class UUIDGenerator { UUID uuid = UUID.nameUUIDFromBytes(bytes); return uuid; } - + /** * Type 5 UUID Generation * @@ -59,8 +59,7 @@ public class UUIDGenerator { UUID uuid = type5UUIDFromBytes(bytes); return uuid; } - - + public static UUID type5UUIDFromBytes(byte[] name) { MessageDigest md; try { @@ -69,27 +68,26 @@ public class UUIDGenerator { throw new InternalError("MD5 not supported", nsae); } byte[] bytes = md.digest(name); - bytes[6] &= 0x0f; /* clear version */ - bytes[6] |= 0x50; /* set to version 5 */ - bytes[8] &= 0x3f; /* clear variant */ - bytes[8] |= 0x80; /* set to IETF variant */ + bytes[6] &= 0x0f; /* clear version */ + bytes[6] |= 0x50; /* set to version 5 */ + bytes[8] &= 0x3f; /* clear variant */ + bytes[8] |= 0x80; /* set to IETF variant */ return constructType5UUID(bytes); } - + private static UUID constructType5UUID(byte[] data) { long msb = 0; long lsb = 0; assert data.length == 16 : "data must be 16 bytes in length"; - - for (int i=0; i<8; i++) + + for (int i = 0; i < 8; i++) msb = (msb << 8) | (data[i] & 0xff); - - for (int i=8; i<16; i++) + + for (int i = 8; i < 16; i++) lsb = (lsb << 8) | (data[i] & 0xff); return new UUID(msb, lsb); } - /** * Unique Keys Generation Using Message Digest and Type 4 UUID * diff --git a/core-java/src/test/java/com/baeldung/completablefuture/CompletableFutureLongRunningUnitTest.java b/core-java/src/test/java/com/baeldung/completablefuture/CompletableFutureLongRunningUnitTest.java index 0c3a13d176..0a6d94e126 100644 --- a/core-java/src/test/java/com/baeldung/completablefuture/CompletableFutureLongRunningUnitTest.java +++ b/core-java/src/test/java/com/baeldung/completablefuture/CompletableFutureLongRunningUnitTest.java @@ -15,7 +15,6 @@ public class CompletableFutureLongRunningUnitTest { private static final Logger LOG = LoggerFactory.getLogger(CompletableFutureLongRunningUnitTest.class); - @Test public void whenRunningCompletableFutureAsynchronously_thenGetMethodWaitsForResult() throws InterruptedException, ExecutionException { Future completableFuture = calculateAsync(); @@ -27,11 +26,12 @@ public class CompletableFutureLongRunningUnitTest { private Future calculateAsync() throws InterruptedException { CompletableFuture completableFuture = new CompletableFuture<>(); - Executors.newCachedThreadPool().submit(() -> { - Thread.sleep(500); - completableFuture.complete("Hello"); - return null; - }); + Executors.newCachedThreadPool() + .submit(() -> { + Thread.sleep(500); + completableFuture.complete("Hello"); + return null; + }); return completableFuture; } @@ -47,11 +47,12 @@ public class CompletableFutureLongRunningUnitTest { private Future calculateAsyncWithCancellation() throws InterruptedException { CompletableFuture completableFuture = new CompletableFuture<>(); - Executors.newCachedThreadPool().submit(() -> { - Thread.sleep(500); - completableFuture.cancel(false); - return null; - }); + Executors.newCachedThreadPool() + .submit(() -> { + Thread.sleep(500); + completableFuture.cancel(false); + return null; + }); return completableFuture; } @@ -98,21 +99,24 @@ public class CompletableFutureLongRunningUnitTest { @Test public void whenUsingThenCompose_thenFuturesExecuteSequentially() throws ExecutionException, InterruptedException { - CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> "Hello").thenCompose(s -> CompletableFuture.supplyAsync(() -> s + " World")); + CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> "Hello") + .thenCompose(s -> CompletableFuture.supplyAsync(() -> s + " World")); assertEquals("Hello World", completableFuture.get()); } @Test public void whenUsingThenCombine_thenWaitForExecutionOfBothFutures() throws ExecutionException, InterruptedException { - CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> "Hello").thenCombine(CompletableFuture.supplyAsync(() -> " World"), (s1, s2) -> s1 + s2); + CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> "Hello") + .thenCombine(CompletableFuture.supplyAsync(() -> " World"), (s1, s2) -> s1 + s2); assertEquals("Hello World", completableFuture.get()); } @Test public void whenUsingThenAcceptBoth_thenWaitForExecutionOfBothFutures() throws ExecutionException, InterruptedException { - CompletableFuture.supplyAsync(() -> "Hello").thenAcceptBoth(CompletableFuture.supplyAsync(() -> " World"), (s1, s2) -> LOG.debug(s1 + s2)); + CompletableFuture.supplyAsync(() -> "Hello") + .thenAcceptBoth(CompletableFuture.supplyAsync(() -> " World"), (s1, s2) -> LOG.debug(s1 + s2)); } @Test @@ -131,7 +135,9 @@ public class CompletableFutureLongRunningUnitTest { assertTrue(future2.isDone()); assertTrue(future3.isDone()); - String combined = Stream.of(future1, future2, future3).map(CompletableFuture::join).collect(Collectors.joining(" ")); + String combined = Stream.of(future1, future2, future3) + .map(CompletableFuture::join) + .collect(Collectors.joining(" ")); assertEquals("Hello Beautiful World", combined); } @@ -147,7 +153,8 @@ public class CompletableFutureLongRunningUnitTest { throw new RuntimeException("Computation error!"); } return "Hello, " + name; - }).handle((s, t) -> s != null ? s : "Hello, Stranger!"); + }) + .handle((s, t) -> s != null ? s : "Hello, Stranger!"); assertEquals("Hello, Stranger!", completableFuture.get()); } diff --git a/core-java/src/test/java/com/baeldung/datetime/UseLocalDateTimeUnitTest.java b/core-java/src/test/java/com/baeldung/datetime/UseLocalDateTimeUnitTest.java index a10ec66f20..e7a76d1ab9 100644 --- a/core-java/src/test/java/com/baeldung/datetime/UseLocalDateTimeUnitTest.java +++ b/core-java/src/test/java/com/baeldung/datetime/UseLocalDateTimeUnitTest.java @@ -15,7 +15,9 @@ public class UseLocalDateTimeUnitTest { @Test public void givenString_whenUsingParse_thenLocalDateTime() { - assertEquals(LocalDate.of(2016, Month.MAY, 10), useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30").toLocalDate()); - assertEquals(LocalTime.of(6, 30), useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30").toLocalTime()); + assertEquals(LocalDate.of(2016, Month.MAY, 10), useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30") + .toLocalDate()); + assertEquals(LocalTime.of(6, 30), useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30") + .toLocalTime()); } } diff --git a/core-java/src/test/java/com/baeldung/datetime/UseLocalDateUnitTest.java b/core-java/src/test/java/com/baeldung/datetime/UseLocalDateUnitTest.java index e158c0fd67..90e858f9ac 100644 --- a/core-java/src/test/java/com/baeldung/datetime/UseLocalDateUnitTest.java +++ b/core-java/src/test/java/com/baeldung/datetime/UseLocalDateUnitTest.java @@ -15,12 +15,14 @@ public class UseLocalDateUnitTest { @Test public void givenValues_whenUsingFactoryOf_thenLocalDate() { - assertEquals("2016-05-10", useLocalDate.getLocalDateUsingFactoryOfMethod(2016, 5, 10).toString()); + assertEquals("2016-05-10", useLocalDate.getLocalDateUsingFactoryOfMethod(2016, 5, 10) + .toString()); } @Test public void givenString_whenUsingParse_thenLocalDate() { - assertEquals("2016-05-10", useLocalDate.getLocalDateUsingParseMethod("2016-05-10").toString()); + assertEquals("2016-05-10", useLocalDate.getLocalDateUsingParseMethod("2016-05-10") + .toString()); } @Test @@ -30,12 +32,14 @@ public class UseLocalDateUnitTest { @Test public void givenDate_whenUsingPlus_thenNextDay() { - assertEquals(LocalDate.now().plusDays(1), useLocalDate.getNextDay(LocalDate.now())); + assertEquals(LocalDate.now() + .plusDays(1), useLocalDate.getNextDay(LocalDate.now())); } @Test public void givenDate_whenUsingMinus_thenPreviousDay() { - assertEquals(LocalDate.now().minusDays(1), useLocalDate.getPreviousDay(LocalDate.now())); + assertEquals(LocalDate.now() + .minusDays(1), useLocalDate.getPreviousDay(LocalDate.now())); } @Test @@ -45,7 +49,8 @@ public class UseLocalDateUnitTest { @Test public void givenToday_whenUsingWithTemporalAdjuster_thenFirstDayOfMonth() { - assertEquals(1, useLocalDate.getFirstDayOfMonth().getDayOfMonth()); + assertEquals(1, useLocalDate.getFirstDayOfMonth() + .getDayOfMonth()); } @Test diff --git a/core-java/src/test/java/com/baeldung/functionalinterface/FunctionalInterfaceUnitTest.java b/core-java/src/test/java/com/baeldung/functionalinterface/FunctionalInterfaceUnitTest.java index 811088cc0c..e91cbfcb75 100644 --- a/core-java/src/test/java/com/baeldung/functionalinterface/FunctionalInterfaceUnitTest.java +++ b/core-java/src/test/java/com/baeldung/functionalinterface/FunctionalInterfaceUnitTest.java @@ -21,7 +21,6 @@ public class FunctionalInterfaceUnitTest { private static final Logger LOG = LoggerFactory.getLogger(FunctionalInterfaceUnitTest.class); - @Test public void whenPassingLambdaToComputeIfAbsent_thenTheValueGetsComputedAndPutIntoMap() { Map nameMap = new HashMap<>(); @@ -83,7 +82,8 @@ public class FunctionalInterfaceUnitTest { return result; }); - List fibonacci5 = fibonacci.limit(5).collect(Collectors.toList()); + List fibonacci5 = fibonacci.limit(5) + .collect(Collectors.toList()); assertEquals(new Integer(1), fibonacci5.get(0)); assertEquals(new Integer(1), fibonacci5.get(1)); @@ -112,7 +112,9 @@ public class FunctionalInterfaceUnitTest { public void whenUsingPredicateInFilter_thenListValuesAreFilteredOut() { List names = Arrays.asList("Angela", "Aaron", "Bob", "Claire", "David"); - List namesWithA = names.stream().filter(name -> name.startsWith("A")).collect(Collectors.toList()); + List namesWithA = names.stream() + .filter(name -> name.startsWith("A")) + .collect(Collectors.toList()); assertEquals(2, namesWithA.size()); assertTrue(namesWithA.contains("Angela")); @@ -135,7 +137,8 @@ public class FunctionalInterfaceUnitTest { List values = Arrays.asList(3, 5, 8, 9, 12); - int sum = values.stream().reduce(0, (i1, i2) -> i1 + i2); + int sum = values.stream() + .reduce(0, (i1, i2) -> i1 + i2); assertEquals(37, sum); diff --git a/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapAggregateStatusManualTest.java b/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapAggregateStatusManualTest.java index ec865f71c4..2971f14c41 100644 --- a/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapAggregateStatusManualTest.java +++ b/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapAggregateStatusManualTest.java @@ -47,7 +47,8 @@ public class ConcurrentMapAggregateStatusManualTest { executorService.awaitTermination(1, TimeUnit.MINUTES); for (int i = 1; i <= MAX_SIZE; i++) { - assertEquals("map size should be consistently reliable", i, mapSizes.get(i - 1).intValue()); + assertEquals("map size should be consistently reliable", i, mapSizes.get(i - 1) + .intValue()); } assertEquals(MAX_SIZE, concurrentMap.size()); } @@ -69,7 +70,8 @@ public class ConcurrentMapAggregateStatusManualTest { executorService.shutdown(); executorService.awaitTermination(1, TimeUnit.MINUTES); - assertNotEquals("map size collected with concurrent updates not reliable", MAX_SIZE, mapSizes.get(MAX_SIZE - 1).intValue()); + assertNotEquals("map size collected with concurrent updates not reliable", MAX_SIZE, mapSizes.get(MAX_SIZE - 1) + .intValue()); assertEquals(MAX_SIZE, concurrentMap.size()); } diff --git a/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurretMapMemoryConsistencyManualTest.java b/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurretMapMemoryConsistencyManualTest.java index 43cbb2d293..e4fac66fe3 100644 --- a/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurretMapMemoryConsistencyManualTest.java +++ b/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurretMapMemoryConsistencyManualTest.java @@ -16,8 +16,12 @@ public class ConcurretMapMemoryConsistencyManualTest { public void givenConcurrentMap_whenSumParallel_thenCorrect() throws Exception { Map map = new ConcurrentHashMap<>(); List sumList = parallelSum100(map, 1000); - assertEquals(1, sumList.stream().distinct().count()); - long wrongResultCount = sumList.stream().filter(num -> num != 100).count(); + assertEquals(1, sumList.stream() + .distinct() + .count()); + long wrongResultCount = sumList.stream() + .filter(num -> num != 100) + .count(); assertEquals(0, wrongResultCount); } @@ -25,8 +29,12 @@ public class ConcurretMapMemoryConsistencyManualTest { public void givenHashtable_whenSumParallel_thenCorrect() throws Exception { Map map = new Hashtable<>(); List sumList = parallelSum100(map, 1000); - assertEquals(1, sumList.stream().distinct().count()); - long wrongResultCount = sumList.stream().filter(num -> num != 100).count(); + assertEquals(1, sumList.stream() + .distinct() + .count()); + long wrongResultCount = sumList.stream() + .filter(num -> num != 100) + .count(); assertEquals(0, wrongResultCount); } @@ -34,8 +42,12 @@ public class ConcurretMapMemoryConsistencyManualTest { public void givenHashMap_whenSumParallel_thenError() throws Exception { Map map = new HashMap<>(); List sumList = parallelSum100(map, 100); - assertNotEquals(1, sumList.stream().distinct().count()); - long wrongResultCount = sumList.stream().filter(num -> num != 100).count(); + assertNotEquals(1, sumList.stream() + .distinct() + .count()); + long wrongResultCount = sumList.stream() + .filter(num -> num != 100) + .count(); assertTrue(wrongResultCount > 0); } diff --git a/core-java/src/test/java/com/baeldung/java8/Java8GroupingByCollectorUnitTest.java b/core-java/src/test/java/com/baeldung/java8/Java8GroupingByCollectorUnitTest.java index 4452b4db9a..eea019da2c 100644 --- a/core-java/src/test/java/com/baeldung/java8/Java8GroupingByCollectorUnitTest.java +++ b/core-java/src/test/java/com/baeldung/java8/Java8GroupingByCollectorUnitTest.java @@ -13,35 +13,26 @@ import static org.junit.Assert.*; public class Java8GroupingByCollectorUnitTest { - private static final List posts = Arrays.asList( - new BlogPost("News item 1", "Author 1", BlogPostType.NEWS, 15), - new BlogPost("Tech review 1", "Author 2", BlogPostType.REVIEW, 5), - new BlogPost("Programming guide", "Author 1", BlogPostType.GUIDE, 20), - new BlogPost("News item 2", "Author 2", BlogPostType.NEWS, 35), - new BlogPost("Tech review 2", "Author 1", BlogPostType.REVIEW, 15)); + private static final List posts = Arrays.asList(new BlogPost("News item 1", "Author 1", BlogPostType.NEWS, 15), new BlogPost("Tech review 1", "Author 2", BlogPostType.REVIEW, 5), + new BlogPost("Programming guide", "Author 1", BlogPostType.GUIDE, 20), new BlogPost("News item 2", "Author 2", BlogPostType.NEWS, 35), new BlogPost("Tech review 2", "Author 1", BlogPostType.REVIEW, 15)); @Test public void givenAListOfPosts_whenGroupedByType_thenGetAMapBetweenTypeAndPosts() { - Map> postsPerType = posts - .stream() - .collect(groupingBy(BlogPost::getType)); + Map> postsPerType = posts.stream() + .collect(groupingBy(BlogPost::getType)); - assertEquals(2, postsPerType - .get(BlogPostType.NEWS) - .size()); - assertEquals(1, postsPerType - .get(BlogPostType.GUIDE) - .size()); - assertEquals(2, postsPerType - .get(BlogPostType.REVIEW) - .size()); + assertEquals(2, postsPerType.get(BlogPostType.NEWS) + .size()); + assertEquals(1, postsPerType.get(BlogPostType.GUIDE) + .size()); + assertEquals(2, postsPerType.get(BlogPostType.REVIEW) + .size()); } @Test public void givenAListOfPosts_whenGroupedByTypeAndTheirTitlesAreJoinedInAString_thenGetAMapBetweenTypeAndCsvTitles() { - Map postsPerType = posts - .stream() - .collect(groupingBy(BlogPost::getType, mapping(BlogPost::getTitle, joining(", ", "Post titles: [", "]")))); + Map postsPerType = posts.stream() + .collect(groupingBy(BlogPost::getType, mapping(BlogPost::getTitle, joining(", ", "Post titles: [", "]")))); assertEquals("Post titles: [News item 1, News item 2]", postsPerType.get(BlogPostType.NEWS)); assertEquals("Post titles: [Programming guide]", postsPerType.get(BlogPostType.GUIDE)); @@ -50,174 +41,135 @@ public class Java8GroupingByCollectorUnitTest { @Test public void givenAListOfPosts_whenGroupedByTypeAndSumTheLikes_thenGetAMapBetweenTypeAndPostLikes() { - Map likesPerType = posts - .stream() - .collect(groupingBy(BlogPost::getType, summingInt(BlogPost::getLikes))); + Map likesPerType = posts.stream() + .collect(groupingBy(BlogPost::getType, summingInt(BlogPost::getLikes))); - assertEquals(50, likesPerType - .get(BlogPostType.NEWS) - .intValue()); - assertEquals(20, likesPerType - .get(BlogPostType.REVIEW) - .intValue()); - assertEquals(20, likesPerType - .get(BlogPostType.GUIDE) - .intValue()); + assertEquals(50, likesPerType.get(BlogPostType.NEWS) + .intValue()); + assertEquals(20, likesPerType.get(BlogPostType.REVIEW) + .intValue()); + assertEquals(20, likesPerType.get(BlogPostType.GUIDE) + .intValue()); } @Test public void givenAListOfPosts_whenGroupedByTypeInAnEnumMap_thenGetAnEnumMapBetweenTypeAndPosts() { - EnumMap> postsPerType = posts - .stream() - .collect(groupingBy(BlogPost::getType, () -> new EnumMap<>(BlogPostType.class), toList())); + EnumMap> postsPerType = posts.stream() + .collect(groupingBy(BlogPost::getType, () -> new EnumMap<>(BlogPostType.class), toList())); - assertEquals(2, postsPerType - .get(BlogPostType.NEWS) - .size()); - assertEquals(1, postsPerType - .get(BlogPostType.GUIDE) - .size()); - assertEquals(2, postsPerType - .get(BlogPostType.REVIEW) - .size()); + assertEquals(2, postsPerType.get(BlogPostType.NEWS) + .size()); + assertEquals(1, postsPerType.get(BlogPostType.GUIDE) + .size()); + assertEquals(2, postsPerType.get(BlogPostType.REVIEW) + .size()); } @Test public void givenAListOfPosts_whenGroupedByTypeInSets_thenGetAMapBetweenTypesAndSetsOfPosts() { - Map> postsPerType = posts - .stream() - .collect(groupingBy(BlogPost::getType, toSet())); + Map> postsPerType = posts.stream() + .collect(groupingBy(BlogPost::getType, toSet())); - assertEquals(2, postsPerType - .get(BlogPostType.NEWS) - .size()); - assertEquals(1, postsPerType - .get(BlogPostType.GUIDE) - .size()); - assertEquals(2, postsPerType - .get(BlogPostType.REVIEW) - .size()); + assertEquals(2, postsPerType.get(BlogPostType.NEWS) + .size()); + assertEquals(1, postsPerType.get(BlogPostType.GUIDE) + .size()); + assertEquals(2, postsPerType.get(BlogPostType.REVIEW) + .size()); } @Test public void givenAListOfPosts_whenGroupedByTypeConcurrently_thenGetAMapBetweenTypeAndPosts() { - ConcurrentMap> postsPerType = posts - .parallelStream() - .collect(groupingByConcurrent(BlogPost::getType)); + ConcurrentMap> postsPerType = posts.parallelStream() + .collect(groupingByConcurrent(BlogPost::getType)); - assertEquals(2, postsPerType - .get(BlogPostType.NEWS) - .size()); - assertEquals(1, postsPerType - .get(BlogPostType.GUIDE) - .size()); - assertEquals(2, postsPerType - .get(BlogPostType.REVIEW) - .size()); + assertEquals(2, postsPerType.get(BlogPostType.NEWS) + .size()); + assertEquals(1, postsPerType.get(BlogPostType.GUIDE) + .size()); + assertEquals(2, postsPerType.get(BlogPostType.REVIEW) + .size()); } @Test public void givenAListOfPosts_whenGroupedByTypeAndAveragingLikes_thenGetAMapBetweenTypeAndAverageNumberOfLikes() { - Map averageLikesPerType = posts - .stream() - .collect(groupingBy(BlogPost::getType, averagingInt(BlogPost::getLikes))); + Map averageLikesPerType = posts.stream() + .collect(groupingBy(BlogPost::getType, averagingInt(BlogPost::getLikes))); - assertEquals(25, averageLikesPerType - .get(BlogPostType.NEWS) - .intValue()); - assertEquals(20, averageLikesPerType - .get(BlogPostType.GUIDE) - .intValue()); - assertEquals(10, averageLikesPerType - .get(BlogPostType.REVIEW) - .intValue()); + assertEquals(25, averageLikesPerType.get(BlogPostType.NEWS) + .intValue()); + assertEquals(20, averageLikesPerType.get(BlogPostType.GUIDE) + .intValue()); + assertEquals(10, averageLikesPerType.get(BlogPostType.REVIEW) + .intValue()); } @Test public void givenAListOfPosts_whenGroupedByTypeAndCounted_thenGetAMapBetweenTypeAndNumberOfPosts() { - Map numberOfPostsPerType = posts - .stream() - .collect(groupingBy(BlogPost::getType, counting())); + Map numberOfPostsPerType = posts.stream() + .collect(groupingBy(BlogPost::getType, counting())); - assertEquals(2, numberOfPostsPerType - .get(BlogPostType.NEWS) - .intValue()); - assertEquals(1, numberOfPostsPerType - .get(BlogPostType.GUIDE) - .intValue()); - assertEquals(2, numberOfPostsPerType - .get(BlogPostType.REVIEW) - .intValue()); + assertEquals(2, numberOfPostsPerType.get(BlogPostType.NEWS) + .intValue()); + assertEquals(1, numberOfPostsPerType.get(BlogPostType.GUIDE) + .intValue()); + assertEquals(2, numberOfPostsPerType.get(BlogPostType.REVIEW) + .intValue()); } @Test public void givenAListOfPosts_whenGroupedByTypeAndMaxingLikes_thenGetAMapBetweenTypeAndMaximumNumberOfLikes() { - Map> maxLikesPerPostType = posts - .stream() - .collect(groupingBy(BlogPost::getType, maxBy(comparingInt(BlogPost::getLikes)))); + Map> maxLikesPerPostType = posts.stream() + .collect(groupingBy(BlogPost::getType, maxBy(comparingInt(BlogPost::getLikes)))); - assertTrue(maxLikesPerPostType - .get(BlogPostType.NEWS) - .isPresent()); - assertEquals(35, maxLikesPerPostType - .get(BlogPostType.NEWS) - .get() - .getLikes()); + assertTrue(maxLikesPerPostType.get(BlogPostType.NEWS) + .isPresent()); + assertEquals(35, maxLikesPerPostType.get(BlogPostType.NEWS) + .get() + .getLikes()); - assertTrue(maxLikesPerPostType - .get(BlogPostType.GUIDE) - .isPresent()); - assertEquals(20, maxLikesPerPostType - .get(BlogPostType.GUIDE) - .get() - .getLikes()); + assertTrue(maxLikesPerPostType.get(BlogPostType.GUIDE) + .isPresent()); + assertEquals(20, maxLikesPerPostType.get(BlogPostType.GUIDE) + .get() + .getLikes()); - assertTrue(maxLikesPerPostType - .get(BlogPostType.REVIEW) - .isPresent()); - assertEquals(15, maxLikesPerPostType - .get(BlogPostType.REVIEW) - .get() - .getLikes()); + assertTrue(maxLikesPerPostType.get(BlogPostType.REVIEW) + .isPresent()); + assertEquals(15, maxLikesPerPostType.get(BlogPostType.REVIEW) + .get() + .getLikes()); } @Test public void givenAListOfPosts_whenGroupedByAuthorAndThenByType_thenGetAMapBetweenAuthorAndMapsBetweenTypeAndBlogPosts() { - Map>> map = posts - .stream() - .collect(groupingBy(BlogPost::getAuthor, groupingBy(BlogPost::getType))); + Map>> map = posts.stream() + .collect(groupingBy(BlogPost::getAuthor, groupingBy(BlogPost::getType))); - assertEquals(1, map - .get("Author 1") - .get(BlogPostType.NEWS) - .size()); - assertEquals(1, map - .get("Author 1") - .get(BlogPostType.GUIDE) - .size()); - assertEquals(1, map - .get("Author 1") - .get(BlogPostType.REVIEW) - .size()); + assertEquals(1, map.get("Author 1") + .get(BlogPostType.NEWS) + .size()); + assertEquals(1, map.get("Author 1") + .get(BlogPostType.GUIDE) + .size()); + assertEquals(1, map.get("Author 1") + .get(BlogPostType.REVIEW) + .size()); - assertEquals(1, map - .get("Author 2") - .get(BlogPostType.NEWS) - .size()); - assertEquals(1, map - .get("Author 2") - .get(BlogPostType.REVIEW) - .size()); - assertNull(map - .get("Author 2") - .get(BlogPostType.GUIDE)); + assertEquals(1, map.get("Author 2") + .get(BlogPostType.NEWS) + .size()); + assertEquals(1, map.get("Author 2") + .get(BlogPostType.REVIEW) + .size()); + assertNull(map.get("Author 2") + .get(BlogPostType.GUIDE)); } @Test public void givenAListOfPosts_whenGroupedByTypeAndSummarizingLikes_thenGetAMapBetweenTypeAndSummary() { - Map likeStatisticsPerType = posts - .stream() - .collect(groupingBy(BlogPost::getType, summarizingInt(BlogPost::getLikes))); + Map likeStatisticsPerType = posts.stream() + .collect(groupingBy(BlogPost::getType, summarizingInt(BlogPost::getLikes))); IntSummaryStatistics newsLikeStatistics = likeStatisticsPerType.get(BlogPostType.NEWS); diff --git a/core-java/src/test/java/com/baeldung/java8/Java8MapAndFlatMap.java b/core-java/src/test/java/com/baeldung/java8/Java8MapAndFlatMap.java index 7098f88f30..a0bd1cf093 100644 --- a/core-java/src/test/java/com/baeldung/java8/Java8MapAndFlatMap.java +++ b/core-java/src/test/java/com/baeldung/java8/Java8MapAndFlatMap.java @@ -17,8 +17,8 @@ public class Java8MapAndFlatMap { @Test public void givenStream_whenCalledMap_thenProduceList() { List myList = Stream.of("a", "b") - .map(String::toUpperCase) - .collect(Collectors.toList()); + .map(String::toUpperCase) + .collect(Collectors.toList()); assertEquals(asList("A", "B"), myList); } @@ -27,9 +27,9 @@ public class Java8MapAndFlatMap { List> list = Arrays.asList(Arrays.asList("a"), Arrays.asList("b")); System.out.println(list); - System.out.println(list - .stream().flatMap(Collection::stream) - .collect(Collectors.toList())); + System.out.println(list.stream() + .flatMap(Collection::stream) + .collect(Collectors.toList())); } @Test @@ -40,13 +40,11 @@ public class Java8MapAndFlatMap { @Test public void givenOptional_whenCalledFlatMap_thenProduceFlattenedOptional() { - assertEquals(Optional.of(Optional.of("STRING")), Optional - .of("string") - .map(s -> Optional.of("STRING"))); + assertEquals(Optional.of(Optional.of("STRING")), Optional.of("string") + .map(s -> Optional.of("STRING"))); - assertEquals(Optional.of("STRING"), Optional - .of("string") - .flatMap(s -> Optional.of("STRING"))); + assertEquals(Optional.of("STRING"), Optional.of("string") + .flatMap(s -> Optional.of("STRING"))); } } diff --git a/core-java/src/test/java/com/baeldung/java8/JavaFolderSizeUnitTest.java b/core-java/src/test/java/com/baeldung/java8/JavaFolderSizeUnitTest.java index 1f3b380772..7f83e379cd 100644 --- a/core-java/src/test/java/com/baeldung/java8/JavaFolderSizeUnitTest.java +++ b/core-java/src/test/java/com/baeldung/java8/JavaFolderSizeUnitTest.java @@ -55,7 +55,12 @@ public class JavaFolderSizeUnitTest { @Test public void whenGetFolderSizeUsingJava8_thenCorrect() throws IOException { final Path folder = Paths.get(path); - final long size = Files.walk(folder).filter(p -> p.toFile().isFile()).mapToLong(p -> p.toFile().length()).sum(); + final long size = Files.walk(folder) + .filter(p -> p.toFile() + .isFile()) + .mapToLong(p -> p.toFile() + .length()) + .sum(); assertEquals(EXPECTED_SIZE, size); } @@ -72,8 +77,12 @@ public class JavaFolderSizeUnitTest { public void whenGetFolderSizeUsingGuava_thenCorrect() { final File folder = new File(path); - final Iterable files = com.google.common.io.Files.fileTreeTraverser().breadthFirstTraversal(folder); - final long size = StreamSupport.stream(files.spliterator(), false).filter(File::isFile).mapToLong(File::length).sum(); + final Iterable files = com.google.common.io.Files.fileTreeTraverser() + .breadthFirstTraversal(folder); + final long size = StreamSupport.stream(files.spliterator(), false) + .filter(File::isFile) + .mapToLong(File::length) + .sum(); assertEquals(EXPECTED_SIZE, size); } diff --git a/core-java/src/test/java/com/baeldung/java8/comparator/Java8ComparatorUnitTest.java b/core-java/src/test/java/com/baeldung/java8/comparator/Java8ComparatorUnitTest.java index 26536ba705..1cac428285 100644 --- a/core-java/src/test/java/com/baeldung/java8/comparator/Java8ComparatorUnitTest.java +++ b/core-java/src/test/java/com/baeldung/java8/comparator/Java8ComparatorUnitTest.java @@ -1,4 +1,5 @@ package com.baeldung.java8.comparator; + import java.util.Arrays; import java.util.Comparator; @@ -25,44 +26,32 @@ public class Java8ComparatorUnitTest { @Before public void initData() { - employees = new Employee[] { new Employee("John", 25, 3000, 9922001), new Employee("Ace", 22, 2000, 5924001), - new Employee("Keith", 35, 4000, 3924401) }; - employeesArrayWithNulls = new Employee[] { new Employee("John", 25, 3000, 9922001), null, new Employee("Ace", 22, 2000, 5924001), - null, new Employee("Keith", 35, 4000, 3924401) }; + employees = new Employee[] { new Employee("John", 25, 3000, 9922001), new Employee("Ace", 22, 2000, 5924001), new Employee("Keith", 35, 4000, 3924401) }; + employeesArrayWithNulls = new Employee[] { new Employee("John", 25, 3000, 9922001), null, new Employee("Ace", 22, 2000, 5924001), null, new Employee("Keith", 35, 4000, 3924401) }; - sortedEmployeesByName = new Employee[] { new Employee("Ace", 22, 2000, 5924001), - new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) }; - sortedEmployeesByNameDesc = new Employee[] { new Employee("Keith", 35, 4000, 3924401), new Employee("John", 25, 3000, 9922001), - new Employee("Ace", 22, 2000, 5924001) }; + sortedEmployeesByName = new Employee[] { new Employee("Ace", 22, 2000, 5924001), new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) }; + sortedEmployeesByNameDesc = new Employee[] { new Employee("Keith", 35, 4000, 3924401), new Employee("John", 25, 3000, 9922001), new Employee("Ace", 22, 2000, 5924001) }; - sortedEmployeesByAge = new Employee[] { new Employee("Ace", 22, 2000, 5924001), - new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) }; + sortedEmployeesByAge = new Employee[] { new Employee("Ace", 22, 2000, 5924001), new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) }; - sortedEmployeesByMobile = new Employee[] { new Employee("Keith", 35, 4000, 3924401), new Employee("Ace", 22, 2000, 5924001), - new Employee("John", 25, 3000, 9922001), }; + sortedEmployeesByMobile = new Employee[] { new Employee("Keith", 35, 4000, 3924401), new Employee("Ace", 22, 2000, 5924001), new Employee("John", 25, 3000, 9922001), }; - sortedEmployeesBySalary = new Employee[] { new Employee("Ace", 22, 2000, 5924001), new Employee("John", 25, 3000, 9922001), - new Employee("Keith", 35, 4000, 3924401), }; + sortedEmployeesBySalary = new Employee[] { new Employee("Ace", 22, 2000, 5924001), new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401), }; - sortedEmployeesArray_WithNullsFirst = new Employee[] { null, null, new Employee("Ace", 22, 2000, 5924001), - new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) }; - sortedEmployeesArray_WithNullsLast = new Employee[] { new Employee("Ace", 22, 2000, 5924001), - new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401), null, null }; + sortedEmployeesArray_WithNullsFirst = new Employee[] { null, null, new Employee("Ace", 22, 2000, 5924001), new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) }; + sortedEmployeesArray_WithNullsLast = new Employee[] { new Employee("Ace", 22, 2000, 5924001), new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401), null, null }; - someMoreEmployees = new Employee[] { new Employee("Jake", 25, 3000, 9922001), new Employee("Jake", 22, 2000, 5924001), - new Employee("Ace", 22, 3000, 6423001), new Employee("Keith", 35, 4000, 3924401) }; + someMoreEmployees = new Employee[] { new Employee("Jake", 25, 3000, 9922001), new Employee("Jake", 22, 2000, 5924001), new Employee("Ace", 22, 3000, 6423001), new Employee("Keith", 35, 4000, 3924401) }; - sortedEmployeesByAgeName = new Employee[] { new Employee("Ace", 22, 3000, 6423001), - new Employee("Jake", 22, 2000, 5924001), new Employee("Jake", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) }; - sortedEmployeesByNameAge = new Employee[] { new Employee("Ace", 22, 3000, 6423001), - new Employee("Jake", 22, 2000, 5924001), new Employee("Jake", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) }; + sortedEmployeesByAgeName = new Employee[] { new Employee("Ace", 22, 3000, 6423001), new Employee("Jake", 22, 2000, 5924001), new Employee("Jake", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) }; + sortedEmployeesByNameAge = new Employee[] { new Employee("Ace", 22, 3000, 6423001), new Employee("Jake", 22, 2000, 5924001), new Employee("Jake", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) }; } @Test public void whenComparing_thenSortedByName() { Comparator employeeNameComparator = Comparator.comparing(Employee::getName); Arrays.sort(employees, employeeNameComparator); -// System.out.println(Arrays.toString(employees)); + // System.out.println(Arrays.toString(employees)); assertTrue(Arrays.equals(employees, sortedEmployeesByName)); } @@ -72,16 +61,16 @@ public class Java8ComparatorUnitTest { return s2.compareTo(s1); }); Arrays.sort(employees, employeeNameComparator); -// System.out.println(Arrays.toString(employees)); + // System.out.println(Arrays.toString(employees)); assertTrue(Arrays.equals(employees, sortedEmployeesByNameDesc)); } - + @Test public void whenReversed_thenSortedByNameDesc() { - Comparator employeeNameComparator = Comparator.comparing(Employee::getName); - Comparator employeeNameComparatorReversed = employeeNameComparator.reversed(); + Comparator employeeNameComparator = Comparator.comparing(Employee::getName); + Comparator employeeNameComparatorReversed = employeeNameComparator.reversed(); Arrays.sort(employees, employeeNameComparatorReversed); -// System.out.println(Arrays.toString(employees)); + // System.out.println(Arrays.toString(employees)); assertTrue(Arrays.equals(employees, sortedEmployeesByNameDesc)); } @@ -89,7 +78,7 @@ public class Java8ComparatorUnitTest { public void whenComparingInt_thenSortedByAge() { Comparator employeeAgeComparator = Comparator.comparingInt(Employee::getAge); Arrays.sort(employees, employeeAgeComparator); -// System.out.println(Arrays.toString(employees)); + // System.out.println(Arrays.toString(employees)); assertTrue(Arrays.equals(employees, sortedEmployeesByAge)); } @@ -97,7 +86,7 @@ public class Java8ComparatorUnitTest { public void whenComparingLong_thenSortedByMobile() { Comparator employeeMobileComparator = Comparator.comparingLong(Employee::getMobile); Arrays.sort(employees, employeeMobileComparator); -// System.out.println(Arrays.toString(employees)); + // System.out.println(Arrays.toString(employees)); assertTrue(Arrays.equals(employees, sortedEmployeesByMobile)); } @@ -105,7 +94,7 @@ public class Java8ComparatorUnitTest { public void whenComparingDouble_thenSortedBySalary() { Comparator employeeSalaryComparator = Comparator.comparingDouble(Employee::getSalary); Arrays.sort(employees, employeeSalaryComparator); -// System.out.println(Arrays.toString(employees)); + // System.out.println(Arrays.toString(employees)); assertTrue(Arrays.equals(employees, sortedEmployeesBySalary)); } @@ -113,7 +102,7 @@ public class Java8ComparatorUnitTest { public void whenNaturalOrder_thenSortedByName() { Comparator employeeNameComparator = Comparator. naturalOrder(); Arrays.sort(employees, employeeNameComparator); -// System.out.println(Arrays.toString(employees)); + // System.out.println(Arrays.toString(employees)); assertTrue(Arrays.equals(employees, sortedEmployeesByName)); } @@ -121,7 +110,7 @@ public class Java8ComparatorUnitTest { public void whenReverseOrder_thenSortedByNameDesc() { Comparator employeeNameComparator = Comparator. reverseOrder(); Arrays.sort(employees, employeeNameComparator); -// System.out.println(Arrays.toString(employees)); + // System.out.println(Arrays.toString(employees)); assertTrue(Arrays.equals(employees, sortedEmployeesByNameDesc)); } @@ -130,7 +119,7 @@ public class Java8ComparatorUnitTest { Comparator employeeNameComparator = Comparator.comparing(Employee::getName); Comparator employeeNameComparator_nullFirst = Comparator.nullsFirst(employeeNameComparator); Arrays.sort(employeesArrayWithNulls, employeeNameComparator_nullFirst); -// System.out.println(Arrays.toString(employeesArrayWithNulls)); + // System.out.println(Arrays.toString(employeesArrayWithNulls)); assertTrue(Arrays.equals(employeesArrayWithNulls, sortedEmployeesArray_WithNullsFirst)); } @@ -139,27 +128,28 @@ public class Java8ComparatorUnitTest { Comparator employeeNameComparator = Comparator.comparing(Employee::getName); Comparator employeeNameComparator_nullLast = Comparator.nullsLast(employeeNameComparator); Arrays.sort(employeesArrayWithNulls, employeeNameComparator_nullLast); -// System.out.println(Arrays.toString(employeesArrayWithNulls)); + // System.out.println(Arrays.toString(employeesArrayWithNulls)); assertTrue(Arrays.equals(employeesArrayWithNulls, sortedEmployeesArray_WithNullsLast)); } @Test public void whenThenComparing_thenSortedByAgeName() { - Comparator employee_Age_Name_Comparator = Comparator.comparing(Employee::getAge).thenComparing(Employee::getName); + Comparator employee_Age_Name_Comparator = Comparator.comparing(Employee::getAge) + .thenComparing(Employee::getName); Arrays.sort(someMoreEmployees, employee_Age_Name_Comparator); -// System.out.println(Arrays.toString(someMoreEmployees)); + // System.out.println(Arrays.toString(someMoreEmployees)); assertTrue(Arrays.equals(someMoreEmployees, sortedEmployeesByAgeName)); } @Test public void whenThenComparing_thenSortedByNameAge() { - Comparator employee_Name_Age_Comparator = Comparator.comparing(Employee::getName).thenComparingInt(Employee::getAge); + Comparator employee_Name_Age_Comparator = Comparator.comparing(Employee::getName) + .thenComparingInt(Employee::getAge); Arrays.sort(someMoreEmployees, employee_Name_Age_Comparator); -// System.out.println(Arrays.toString(someMoreEmployees)); + // System.out.println(Arrays.toString(someMoreEmployees)); assertTrue(Arrays.equals(someMoreEmployees, sortedEmployeesByNameAge)); } - } diff --git a/core-java/src/test/java/com/baeldung/java8/optional/OptionalUnitTest.java b/core-java/src/test/java/com/baeldung/java8/optional/OptionalUnitTest.java index 0085de6327..4cb2551fae 100644 --- a/core-java/src/test/java/com/baeldung/java8/optional/OptionalUnitTest.java +++ b/core-java/src/test/java/com/baeldung/java8/optional/OptionalUnitTest.java @@ -17,7 +17,6 @@ public class OptionalUnitTest { private static final Logger LOG = LoggerFactory.getLogger(OptionalUnitTest.class); - // creating Optional @Test public void whenCreatesEmptyOptional_thenCorrect() { @@ -94,9 +93,11 @@ public class OptionalUnitTest { public void whenOptionalFilterWorks_thenCorrect() { Integer year = 2016; Optional yearOptional = Optional.of(year); - boolean is2016 = yearOptional.filter(y -> y == 2016).isPresent(); + boolean is2016 = yearOptional.filter(y -> y == 2016) + .isPresent(); assertTrue(is2016); - boolean is2017 = yearOptional.filter(y -> y == 2017).isPresent(); + boolean is2017 = yearOptional.filter(y -> y == 2017) + .isPresent(); assertFalse(is2017); } @@ -128,7 +129,11 @@ public class OptionalUnitTest { } public boolean priceIsInRange2(Modem modem2) { - return Optional.ofNullable(modem2).map(Modem::getPrice).filter(p -> p >= 10).filter(p -> p <= 15).isPresent(); + return Optional.ofNullable(modem2) + .map(Modem::getPrice) + .filter(p -> p >= 10) + .filter(p -> p <= 15) + .isPresent(); } // Transforming Value With map() @@ -137,7 +142,8 @@ public class OptionalUnitTest { List companyNames = Arrays.asList("paypal", "oracle", "", "microsoft", "", "apple"); Optional> listOptional = Optional.of(companyNames); - int size = listOptional.map(List::size).orElse(0); + int size = listOptional.map(List::size) + .orElse(0); assertEquals(6, size); } @@ -146,7 +152,8 @@ public class OptionalUnitTest { String name = "baeldung"; Optional nameOptional = Optional.of(name); - int len = nameOptional.map(String::length).orElse(0); + int len = nameOptional.map(String::length) + .orElse(0); assertEquals(8, len); } @@ -154,10 +161,13 @@ public class OptionalUnitTest { public void givenOptional_whenMapWorksWithFilter_thenCorrect() { String password = " password "; Optional passOpt = Optional.of(password); - boolean correctPassword = passOpt.filter(pass -> pass.equals("password")).isPresent(); + boolean correctPassword = passOpt.filter(pass -> pass.equals("password")) + .isPresent(); assertFalse(correctPassword); - correctPassword = passOpt.map(String::trim).filter(pass -> pass.equals("password")).isPresent(); + correctPassword = passOpt.map(String::trim) + .filter(pass -> pass.equals("password")) + .isPresent(); assertTrue(correctPassword); } @@ -172,7 +182,8 @@ public class OptionalUnitTest { String name1 = nameOptional.orElseThrow(IllegalArgumentException::new); assertEquals("john", name1); - String name = personOptional.flatMap(Person::getName).orElseThrow(IllegalArgumentException::new); + String name = personOptional.flatMap(Person::getName) + .orElseThrow(IllegalArgumentException::new); assertEquals("john", name); } @@ -182,7 +193,9 @@ public class OptionalUnitTest { person.setPassword("password"); Optional personOptional = Optional.of(person); - String password = personOptional.flatMap(Person::getPassword).filter(cleanPass -> cleanPass.equals("password")).orElseThrow(IllegalArgumentException::new); + String password = personOptional.flatMap(Person::getPassword) + .filter(cleanPass -> cleanPass.equals("password")) + .orElseThrow(IllegalArgumentException::new); assertEquals("password", password); } @@ -190,7 +203,8 @@ public class OptionalUnitTest { @Test public void whenOrElseWorks_thenCorrect() { String nullName = null; - String name = Optional.ofNullable(nullName).orElse("john"); + String name = Optional.ofNullable(nullName) + .orElse("john"); assertEquals("john", name); } @@ -198,7 +212,8 @@ public class OptionalUnitTest { @Test public void whenOrElseGetWorks_thenCorrect() { String nullName = null; - String name = Optional.ofNullable(nullName).orElseGet(() -> "john"); + String name = Optional.ofNullable(nullName) + .orElseGet(() -> "john"); assertEquals("john", name); } @@ -207,11 +222,13 @@ public class OptionalUnitTest { public void whenOrElseGetAndOrElseOverlap_thenCorrect() { String text = null; LOG.debug("Using orElseGet:"); - String defaultText = Optional.ofNullable(text).orElseGet(this::getMyDefault); + String defaultText = Optional.ofNullable(text) + .orElseGet(this::getMyDefault); assertEquals("Default Value", defaultText); LOG.debug("Using orElse:"); - defaultText = Optional.ofNullable(text).orElse(getMyDefault()); + defaultText = Optional.ofNullable(text) + .orElse(getMyDefault()); assertEquals("Default Value", defaultText); } @@ -219,11 +236,13 @@ public class OptionalUnitTest { public void whenOrElseGetAndOrElseDiffer_thenCorrect() { String text = "Text present"; LOG.debug("Using orElseGet:"); - String defaultText = Optional.ofNullable(text).orElseGet(this::getMyDefault); + String defaultText = Optional.ofNullable(text) + .orElseGet(this::getMyDefault); assertEquals("Text present", defaultText); LOG.debug("Using orElse:"); - defaultText = Optional.ofNullable(text).orElse(getMyDefault()); + defaultText = Optional.ofNullable(text) + .orElse(getMyDefault()); assertEquals("Text present", defaultText); } @@ -231,7 +250,8 @@ public class OptionalUnitTest { @Test(expected = IllegalArgumentException.class) public void whenOrElseThrowWorks_thenCorrect() { String nullName = null; - String name = Optional.ofNullable(nullName).orElseThrow(IllegalArgumentException::new); + String name = Optional.ofNullable(nullName) + .orElseThrow(IllegalArgumentException::new); } public String getMyDefault() { diff --git a/core-java/src/test/java/com/baeldung/list/flattennestedlist/FlattenNestedListUnitTest.java b/core-java/src/test/java/com/baeldung/list/flattennestedlist/FlattenNestedListUnitTest.java index 3c8f519082..543c680597 100644 --- a/core-java/src/test/java/com/baeldung/list/flattennestedlist/FlattenNestedListUnitTest.java +++ b/core-java/src/test/java/com/baeldung/list/flattennestedlist/FlattenNestedListUnitTest.java @@ -43,6 +43,8 @@ public class FlattenNestedListUnitTest { } private List flattenListOfListsStream(List> list) { - return list.stream().flatMap(Collection::stream).collect(Collectors.toList()); + return list.stream() + .flatMap(Collection::stream) + .collect(Collectors.toList()); } } diff --git a/core-java/src/test/java/com/baeldung/maths/RoundTest.java b/core-java/src/test/java/com/baeldung/maths/RoundTest.java index 5ce9523e21..9e3c049c96 100644 --- a/core-java/src/test/java/com/baeldung/maths/RoundTest.java +++ b/core-java/src/test/java/com/baeldung/maths/RoundTest.java @@ -15,56 +15,56 @@ public class RoundTest { private double expected = 2.03d; @Test - public void givenDecimalNumber_whenRoundToNDecimalPlaces_thenGetExpectedResult() { + public void givenDecimalNumber_whenRoundToNDecimalPlaces_thenGetExpectedResult() { Assert.assertEquals(expected, Round.round(value, places), delta); Assert.assertEquals(expected, Round.roundNotPrecise(value, places), delta); Assert.assertEquals(expected, Round.roundAvoid(value, places), delta); Assert.assertEquals(expected, Precision.round(value, places), delta); Assert.assertEquals(expected, DoubleRounder.round(value, places), delta); - + places = 3; expected = 2.035d; - + Assert.assertEquals(expected, Round.round(value, places), delta); Assert.assertEquals(expected, Round.roundNotPrecise(value, places), delta); Assert.assertEquals(expected, Round.roundAvoid(value, places), delta); Assert.assertEquals(expected, Precision.round(value, places), delta); Assert.assertEquals(expected, DoubleRounder.round(value, places), delta); - + value = 1000.0d; places = 17; expected = 1000.0d; - + Assert.assertEquals(expected, Round.round(value, places), delta); Assert.assertEquals(expected, Round.roundNotPrecise(value, places), delta); Assert.assertNotEquals(expected, Round.roundAvoid(value, places), delta); // Returns: 92.23372036854776 ! Assert.assertEquals(expected, Precision.round(value, places), delta); Assert.assertEquals(expected, DoubleRounder.round(value, places), delta); - + value = 256.025d; places = 2; expected = 256.03d; - + Assert.assertEquals(expected, Round.round(value, places), delta); Assert.assertNotEquals(expected, Round.roundNotPrecise(value, places), delta); // Returns: 256.02 ! Assert.assertNotEquals(expected, Round.roundAvoid(value, places), delta); // Returns: 256.02 ! Assert.assertEquals(expected, Precision.round(value, places), delta); Assert.assertNotEquals(expected, DoubleRounder.round(value, places), delta); // Returns: 256.02 ! - - value = 260.775d; + + value = 260.775d; places = 2; expected = 260.78d; - + Assert.assertEquals(expected, Round.round(value, places), delta); Assert.assertNotEquals(expected, Round.roundNotPrecise(value, places), delta); // Returns: 260.77 ! Assert.assertNotEquals(expected, Round.roundAvoid(value, places), delta); // Returns: 260.77 ! Assert.assertEquals(expected, Precision.round(value, places), delta); Assert.assertNotEquals(expected, DoubleRounder.round(value, places), delta); // Returns: 260.77 ! - + value = 90080070060.1d; places = 9; expected = 90080070060.1d; - + Assert.assertEquals(expected, Round.round(value, places), delta); Assert.assertEquals(expected, Round.roundNotPrecise(value, places), delta); Assert.assertNotEquals(expected, Round.roundAvoid(value, places), delta); // Returns: 9.223372036854776E9 ! diff --git a/core-java/src/test/java/com/baeldung/socket/EchoIntegrationTest.java b/core-java/src/test/java/com/baeldung/socket/EchoIntegrationTest.java index 2bf6d142bb..70c6e88c49 100644 --- a/core-java/src/test/java/com/baeldung/socket/EchoIntegrationTest.java +++ b/core-java/src/test/java/com/baeldung/socket/EchoIntegrationTest.java @@ -14,7 +14,8 @@ public class EchoIntegrationTest { @BeforeClass public static void start() throws InterruptedException { - Executors.newSingleThreadExecutor().submit(() -> new EchoServer().start(PORT)); + Executors.newSingleThreadExecutor() + .submit(() -> new EchoServer().start(PORT)); Thread.sleep(500); } diff --git a/core-java/src/test/java/com/baeldung/socket/GreetServerIntegrationTest.java b/core-java/src/test/java/com/baeldung/socket/GreetServerIntegrationTest.java index 06b37d8539..4367ed26a2 100644 --- a/core-java/src/test/java/com/baeldung/socket/GreetServerIntegrationTest.java +++ b/core-java/src/test/java/com/baeldung/socket/GreetServerIntegrationTest.java @@ -17,7 +17,8 @@ public class GreetServerIntegrationTest { @BeforeClass public static void start() throws InterruptedException { - Executors.newSingleThreadExecutor().submit(() -> new GreetServer().start(PORT)); + Executors.newSingleThreadExecutor() + .submit(() -> new GreetServer().start(PORT)); Thread.sleep(500); } diff --git a/core-java/src/test/java/org/baeldung/java/JavaIoUnitTest.java b/core-java/src/test/java/org/baeldung/java/JavaIoUnitTest.java index 3ab8e1de91..5da68aa746 100644 --- a/core-java/src/test/java/org/baeldung/java/JavaIoUnitTest.java +++ b/core-java/src/test/java/org/baeldung/java/JavaIoUnitTest.java @@ -96,9 +96,12 @@ public class JavaIoUnitTest { // utils private final void logMemory() { - logger.info("Max Memory: {} Mb", Runtime.getRuntime().maxMemory() / 1048576); - logger.info("Total Memory: {} Mb", Runtime.getRuntime().totalMemory() / 1048576); - logger.info("Free Memory: {} Mb", Runtime.getRuntime().freeMemory() / 1048576); + logger.info("Max Memory: {} Mb", Runtime.getRuntime() + .maxMemory() / 1048576); + logger.info("Total Memory: {} Mb", Runtime.getRuntime() + .totalMemory() / 1048576); + logger.info("Free Memory: {} Mb", Runtime.getRuntime() + .freeMemory() / 1048576); } } diff --git a/core-java/src/test/java/org/baeldung/java/JavaRandomUnitTest.java b/core-java/src/test/java/org/baeldung/java/JavaRandomUnitTest.java index a11659547e..f17531e744 100644 --- a/core-java/src/test/java/org/baeldung/java/JavaRandomUnitTest.java +++ b/core-java/src/test/java/org/baeldung/java/JavaRandomUnitTest.java @@ -13,7 +13,6 @@ public class JavaRandomUnitTest { private static final Logger LOG = LoggerFactory.getLogger(JavaRandomUnitTest.class); - // tests - random long @Test @@ -25,7 +24,8 @@ public class JavaRandomUnitTest { @Test public void givenUsingApacheCommons_whenGeneratingRandomLongUnbounded_thenCorrect() { - final long generatedLong = new RandomDataGenerator().getRandomGenerator().nextLong(); + final long generatedLong = new RandomDataGenerator().getRandomGenerator() + .nextLong(); LOG.debug("{}", generatedLong); } @@ -68,7 +68,8 @@ public class JavaRandomUnitTest { @Test public void givenUsingApache_whenGeneratingRandomIntegerUnbounded_thenCorrect() { - final Integer generatedInteger = new RandomDataGenerator().getRandomGenerator().nextInt(); + final Integer generatedInteger = new RandomDataGenerator().getRandomGenerator() + .nextInt(); LOG.debug("{}", generatedInteger); } @@ -93,7 +94,8 @@ public class JavaRandomUnitTest { @Test public void givenUsingApache_whenGeneratingRandomFloatUnbounded_thenCorrect() { - final float generatedFloat = new RandomDataGenerator().getRandomGenerator().nextFloat(); + final float generatedFloat = new RandomDataGenerator().getRandomGenerator() + .nextFloat(); LOG.debug("{}", generatedFloat); } @@ -111,7 +113,8 @@ public class JavaRandomUnitTest { public void givenUsingApache_whenGeneratingRandomFloatBounded_thenCorrect() { final float leftLimit = 1F; final float rightLimit = 10F; - final float randomFloat = new RandomDataGenerator().getRandomGenerator().nextFloat(); + final float randomFloat = new RandomDataGenerator().getRandomGenerator() + .nextFloat(); final float generatedFloat = leftLimit + randomFloat * (rightLimit - leftLimit); LOG.debug("{}", generatedFloat); @@ -128,7 +131,8 @@ public class JavaRandomUnitTest { @Test public void givenUsingApache_whenGeneratingRandomDoubleUnbounded_thenCorrect() { - final double generatedDouble = new RandomDataGenerator().getRandomGenerator().nextDouble(); + final double generatedDouble = new RandomDataGenerator().getRandomGenerator() + .nextDouble(); LOG.debug("{}", generatedDouble); } diff --git a/core-java/src/test/java/org/baeldung/java/JavaTimerLongRunningUnitTest.java b/core-java/src/test/java/org/baeldung/java/JavaTimerLongRunningUnitTest.java index 7a03070e82..826106a09e 100644 --- a/core-java/src/test/java/org/baeldung/java/JavaTimerLongRunningUnitTest.java +++ b/core-java/src/test/java/org/baeldung/java/JavaTimerLongRunningUnitTest.java @@ -15,7 +15,6 @@ public class JavaTimerLongRunningUnitTest { private static final Logger LOG = LoggerFactory.getLogger(JavaTimerLongRunningUnitTest.class); - // tests @Test @@ -23,7 +22,8 @@ public class JavaTimerLongRunningUnitTest { final TimerTask timerTask = new TimerTask() { @Override public void run() { - LOG.debug("Task performed on: " + new Date() + "\n" + "Thread's name: " + Thread.currentThread().getName()); + LOG.debug("Task performed on: " + new Date() + "\n" + "Thread's name: " + Thread.currentThread() + .getName()); } }; final Timer timer = new Timer("Timer"); diff --git a/core-java/src/test/java/org/baeldung/java/sorting/Employee.java b/core-java/src/test/java/org/baeldung/java/sorting/Employee.java index 477092bfcb..99af49c8d3 100644 --- a/core-java/src/test/java/org/baeldung/java/sorting/Employee.java +++ b/core-java/src/test/java/org/baeldung/java/sorting/Employee.java @@ -38,7 +38,8 @@ public class Employee implements Comparable { @Override public boolean equals(Object obj) { - return ((Employee) obj).getName().equals(getName()); + return ((Employee) obj).getName() + .equals(getName()); } @Override @@ -49,7 +50,13 @@ public class Employee implements Comparable { @Override public String toString() { - return new StringBuffer().append("(").append(getName()).append(getAge()).append(",").append(getSalary()).append(")").toString(); + return new StringBuffer().append("(") + .append(getName()) + .append(getAge()) + .append(",") + .append(getSalary()) + .append(")") + .toString(); } } diff --git a/core-java/src/test/java/org/baeldung/java/sorting/JavaSortingUnitTest.java b/core-java/src/test/java/org/baeldung/java/sorting/JavaSortingUnitTest.java index 277e037615..ca9c9b4b5d 100644 --- a/core-java/src/test/java/org/baeldung/java/sorting/JavaSortingUnitTest.java +++ b/core-java/src/test/java/org/baeldung/java/sorting/JavaSortingUnitTest.java @@ -113,7 +113,8 @@ public class JavaSortingUnitTest { sortedMap.put(entry.getKey(), entry.getValue()); } - assertTrue(Arrays.equals(sortedMap.keySet().toArray(), sortedKeys)); + assertTrue(Arrays.equals(sortedMap.keySet() + .toArray(), sortedKeys)); } @Test @@ -127,7 +128,8 @@ public class JavaSortingUnitTest { sortedMap.put(entry.getKey(), entry.getValue()); } - assertTrue(Arrays.equals(sortedMap.values().toArray(), sortedValues)); + assertTrue(Arrays.equals(sortedMap.values() + .toArray(), sortedValues)); } @Test diff --git a/feign/src/main/java/com/baeldung/feign/BookControllerFeignClientBuilder.java b/feign/src/main/java/com/baeldung/feign/BookControllerFeignClientBuilder.java index 56cf4071b4..31d377622d 100644 --- a/feign/src/main/java/com/baeldung/feign/BookControllerFeignClientBuilder.java +++ b/feign/src/main/java/com/baeldung/feign/BookControllerFeignClientBuilder.java @@ -14,6 +14,12 @@ public class BookControllerFeignClientBuilder { private BookClient bookClient = createClient(BookClient.class, "http://localhost:8081/api/books"); private static T createClient(Class type, String uri) { - return Feign.builder().client(new OkHttpClient()).encoder(new GsonEncoder()).decoder(new GsonDecoder()).logger(new Slf4jLogger(type)).logLevel(Logger.Level.FULL).target(type, uri); + return Feign.builder() + .client(new OkHttpClient()) + .encoder(new GsonEncoder()) + .decoder(new GsonDecoder()) + .logger(new Slf4jLogger(type)) + .logLevel(Logger.Level.FULL) + .target(type, uri); } } diff --git a/feign/src/test/java/com/baeldung/feign/clients/BookClientLiveTest.java b/feign/src/test/java/com/baeldung/feign/clients/BookClientLiveTest.java index a17dbf7a2e..bee440bd9e 100644 --- a/feign/src/test/java/com/baeldung/feign/clients/BookClientLiveTest.java +++ b/feign/src/test/java/com/baeldung/feign/clients/BookClientLiveTest.java @@ -34,25 +34,31 @@ public class BookClientLiveTest { @Test public void givenBookClient_shouldRunSuccessfully() throws Exception { - List books = bookClient.findAll().stream().map(BookResource::getBook).collect(Collectors.toList()); + List books = bookClient.findAll() + .stream() + .map(BookResource::getBook) + .collect(Collectors.toList()); assertTrue(books.size() > 2); log.info("{}", books); } @Test public void givenBookClient_shouldFindOneBook() throws Exception { - Book book = bookClient.findByIsbn("0151072558").getBook(); + Book book = bookClient.findByIsbn("0151072558") + .getBook(); assertThat(book.getAuthor(), containsString("Orwell")); log.info("{}", book); } @Test public void givenBookClient_shouldPostBook() throws Exception { - String isbn = UUID.randomUUID().toString(); + String isbn = UUID.randomUUID() + .toString(); Book book = new Book(isbn, "Me", "It's me!", null, null); bookClient.create(book); - book = bookClient.findByIsbn(isbn).getBook(); + book = bookClient.findByIsbn(isbn) + .getBook(); assertThat(book.getAuthor(), is("Me")); log.info("{}", book); } diff --git a/jackson/src/main/java/com/baeldung/jackson/deserialization/jacksoninject/Author.java b/jackson/src/main/java/com/baeldung/jackson/deserialization/jacksoninject/Author.java index 0330498089..db8b594509 100644 --- a/jackson/src/main/java/com/baeldung/jackson/deserialization/jacksoninject/Author.java +++ b/jackson/src/main/java/com/baeldung/jackson/deserialization/jacksoninject/Author.java @@ -9,7 +9,8 @@ public class Author extends Person { List items = new ArrayList<>(); - public Author(){} + public Author() { + } public Author(String firstName, String lastName) { super(firstName, lastName); diff --git a/jackson/src/main/java/com/baeldung/jackson/deserialization/jacksoninject/Person.java b/jackson/src/main/java/com/baeldung/jackson/deserialization/jacksoninject/Person.java index 3add362007..9ba91e9170 100644 --- a/jackson/src/main/java/com/baeldung/jackson/deserialization/jacksoninject/Person.java +++ b/jackson/src/main/java/com/baeldung/jackson/deserialization/jacksoninject/Person.java @@ -11,7 +11,7 @@ public class Person { private String firstName; private String lastName; - public Person(){ + public Person() { } diff --git a/jackson/src/main/java/com/baeldung/jackson/deserialization/jsoncreator/Author.java b/jackson/src/main/java/com/baeldung/jackson/deserialization/jsoncreator/Author.java index 34fbd16c1c..d48c95b255 100644 --- a/jackson/src/main/java/com/baeldung/jackson/deserialization/jsoncreator/Author.java +++ b/jackson/src/main/java/com/baeldung/jackson/deserialization/jsoncreator/Author.java @@ -1,6 +1,5 @@ package com.baeldung.jackson.deserialization.jsoncreator; - import com.baeldung.jackson.domain.Person; import com.baeldung.jackson.domain.Item; import com.fasterxml.jackson.annotation.JsonCreator; @@ -14,9 +13,7 @@ public class Author extends Person { List items = new ArrayList<>(); @JsonCreator - public Author( - @JsonProperty("christianName") String firstName, - @JsonProperty("surname") String lastName) { + public Author(@JsonProperty("christianName") String firstName, @JsonProperty("surname") String lastName) { super(firstName, lastName); } diff --git a/jackson/src/main/java/com/baeldung/jackson/deserialization/jsondeserialize/Book.java b/jackson/src/main/java/com/baeldung/jackson/deserialization/jsondeserialize/Book.java index 8e93ab5ce7..dc0d0ee623 100644 --- a/jackson/src/main/java/com/baeldung/jackson/deserialization/jsondeserialize/Book.java +++ b/jackson/src/main/java/com/baeldung/jackson/deserialization/jsondeserialize/Book.java @@ -13,7 +13,8 @@ public class Book extends Item { private Date published; private BigDecimal pages; - public Book() {} + public Book() { + } public Book(String title, Author author) { super(title, author); diff --git a/jackson/src/main/java/com/baeldung/jackson/deserialization/jsondeserialize/CustomDateDeserializer.java b/jackson/src/main/java/com/baeldung/jackson/deserialization/jsondeserialize/CustomDateDeserializer.java index c9d6ae39fa..93bbfd0069 100644 --- a/jackson/src/main/java/com/baeldung/jackson/deserialization/jsondeserialize/CustomDateDeserializer.java +++ b/jackson/src/main/java/com/baeldung/jackson/deserialization/jsondeserialize/CustomDateDeserializer.java @@ -11,8 +11,7 @@ import java.util.Date; public class CustomDateDeserializer extends StdDeserializer { - private static SimpleDateFormat formatter = - new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); + private static SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); public CustomDateDeserializer() { this(null); @@ -23,8 +22,7 @@ public class CustomDateDeserializer extends StdDeserializer { } @Override - public Date deserialize(JsonParser jsonparser, DeserializationContext context) - throws IOException { + public Date deserialize(JsonParser jsonparser, DeserializationContext context) throws IOException { String date = jsonparser.getText(); try { return formatter.parse(date); diff --git a/jackson/src/main/java/com/baeldung/jackson/deserialization/jsondeserialize/Item.java b/jackson/src/main/java/com/baeldung/jackson/deserialization/jsondeserialize/Item.java index ab4689dec8..fc27a586ac 100644 --- a/jackson/src/main/java/com/baeldung/jackson/deserialization/jsondeserialize/Item.java +++ b/jackson/src/main/java/com/baeldung/jackson/deserialization/jsondeserialize/Item.java @@ -19,7 +19,8 @@ public class Item { private List authors = new ArrayList<>(); private float price; - public Item(){} + public Item() { + } public Item(String title, Author author) { this.id = UUID.randomUUID(); diff --git a/jackson/src/main/java/com/baeldung/jackson/deserialization/jsonsetter/Author.java b/jackson/src/main/java/com/baeldung/jackson/deserialization/jsonsetter/Author.java index c63b63f515..3f9ae70a88 100644 --- a/jackson/src/main/java/com/baeldung/jackson/deserialization/jsonsetter/Author.java +++ b/jackson/src/main/java/com/baeldung/jackson/deserialization/jsonsetter/Author.java @@ -18,7 +18,8 @@ public class Author extends Person { private List items = new ArrayList<>(); - public Author(){} + public Author() { + } public Author(String firstName, String lastName) { super(firstName, lastName); diff --git a/jackson/src/main/java/com/baeldung/jackson/domain/Book.java b/jackson/src/main/java/com/baeldung/jackson/domain/Book.java index 6e486ffbd3..a5963e33ba 100644 --- a/jackson/src/main/java/com/baeldung/jackson/domain/Book.java +++ b/jackson/src/main/java/com/baeldung/jackson/domain/Book.java @@ -15,7 +15,7 @@ public class Book extends Item { private Date published; private BigDecimal pages; - public Book(){ + public Book() { } public Book(String title, Author author) { diff --git a/jackson/src/main/java/com/baeldung/jackson/domain/Course.java b/jackson/src/main/java/com/baeldung/jackson/domain/Course.java index 15049ded09..672b0bc250 100644 --- a/jackson/src/main/java/com/baeldung/jackson/domain/Course.java +++ b/jackson/src/main/java/com/baeldung/jackson/domain/Course.java @@ -10,7 +10,9 @@ import java.util.List; */ public class Course extends Item { - public enum Medium {CLASSROOM, ONLINE} + public enum Medium { + CLASSROOM, ONLINE + } public enum Level { BEGINNER("Beginner", 1), INTERMEDIATE("Intermediate", 2), ADVANCED("Advanced", 3); diff --git a/jackson/src/main/java/com/baeldung/jackson/domain/Item.java b/jackson/src/main/java/com/baeldung/jackson/domain/Item.java index fc861d2f3c..d9d1350a8e 100644 --- a/jackson/src/main/java/com/baeldung/jackson/domain/Item.java +++ b/jackson/src/main/java/com/baeldung/jackson/domain/Item.java @@ -17,7 +17,8 @@ public class Item { private List authors = new ArrayList<>(); private float price; - public Item(){} + public Item() { + } public Item(String title, Author author) { this.id = UUID.randomUUID(); diff --git a/jackson/src/main/java/com/baeldung/jackson/domain/Person.java b/jackson/src/main/java/com/baeldung/jackson/domain/Person.java index 2f66a1acfe..785efff755 100644 --- a/jackson/src/main/java/com/baeldung/jackson/domain/Person.java +++ b/jackson/src/main/java/com/baeldung/jackson/domain/Person.java @@ -14,7 +14,8 @@ public class Person { private String firstName; private String lastName; - public Person(){} + public Person() { + } public Person(String firstName, String lastName) { this.id = UUID.randomUUID(); diff --git a/jackson/src/main/java/com/baeldung/jackson/entities/ClassWithAMap.java b/jackson/src/main/java/com/baeldung/jackson/entities/ClassWithAMap.java index 54ebff8a56..107d75eb0d 100644 --- a/jackson/src/main/java/com/baeldung/jackson/entities/ClassWithAMap.java +++ b/jackson/src/main/java/com/baeldung/jackson/entities/ClassWithAMap.java @@ -9,16 +9,16 @@ import com.fasterxml.jackson.databind.annotation.JsonDeserialize; public class ClassWithAMap { - @JsonProperty("map") - @JsonDeserialize(keyUsing = MyPairDeserializer.class) - private final Map map; + @JsonProperty("map") + @JsonDeserialize(keyUsing = MyPairDeserializer.class) + private final Map map; - @JsonCreator - public ClassWithAMap(Map map) { - this.map = map; - } + @JsonCreator + public ClassWithAMap(Map map) { + this.map = map; + } - public Map getMap() { - return map; - } + public Map getMap() { + return map; + } } \ No newline at end of file diff --git a/jackson/src/main/java/com/baeldung/jackson/entities/MyPair.java b/jackson/src/main/java/com/baeldung/jackson/entities/MyPair.java index ebe41890fe..ca5960e0cf 100644 --- a/jackson/src/main/java/com/baeldung/jackson/entities/MyPair.java +++ b/jackson/src/main/java/com/baeldung/jackson/entities/MyPair.java @@ -4,77 +4,77 @@ import com.fasterxml.jackson.annotation.JsonValue; public class MyPair { - private String first; - private String second; + private String first; + private String second; - public MyPair(String first, String second) { - this.first = first; - this.second = second; - } + public MyPair(String first, String second) { + this.first = first; + this.second = second; + } - public MyPair(String both) { - String[] pairs = both.split("and"); - this.first = pairs[0].trim(); - this.second = pairs[1].trim(); - } + public MyPair(String both) { + String[] pairs = both.split("and"); + this.first = pairs[0].trim(); + this.second = pairs[1].trim(); + } - @Override - @JsonValue - public String toString() { - return first + " and " + second; - } + @Override + @JsonValue + public String toString() { + return first + " and " + second; + } - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((first == null) ? 0 : first.hashCode()); - result = prime * result + ((second == null) ? 0 : second.hashCode()); - return result; - } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((first == null) ? 0 : first.hashCode()); + result = prime * result + ((second == null) ? 0 : second.hashCode()); + return result; + } - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (!(obj instanceof MyPair)) { - return false; - } - MyPair other = (MyPair) obj; - if (first == null) { - if (other.first != null) { - return false; - } - } else if (!first.equals(other.first)) { - return false; - } - if (second == null) { - if (other.second != null) { - return false; - } - } else if (!second.equals(other.second)) { - return false; - } - return true; - } + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (!(obj instanceof MyPair)) { + return false; + } + MyPair other = (MyPair) obj; + if (first == null) { + if (other.first != null) { + return false; + } + } else if (!first.equals(other.first)) { + return false; + } + if (second == null) { + if (other.second != null) { + return false; + } + } else if (!second.equals(other.second)) { + return false; + } + return true; + } - public String getFirst() { - return first; - } + public String getFirst() { + return first; + } - public void setFirst(String first) { - this.first = first; - } + public void setFirst(String first) { + this.first = first; + } - public String getSecond() { - return second; - } + public String getSecond() { + return second; + } - public void setSecond(String second) { - this.second = second; - } + public void setSecond(String second) { + this.second = second; + } } \ No newline at end of file diff --git a/jackson/src/main/java/com/baeldung/jackson/format/User.java b/jackson/src/main/java/com/baeldung/jackson/format/User.java index 101ef09a4a..e655deb93b 100755 --- a/jackson/src/main/java/com/baeldung/jackson/format/User.java +++ b/jackson/src/main/java/com/baeldung/jackson/format/User.java @@ -13,28 +13,25 @@ public class User extends Person { private String firstName; private String lastName; - @JsonFormat(shape = JsonFormat.Shape.STRING, - pattern = "yyyy-MM-dd@HH:mm:ss.SSSZ") + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd@HH:mm:ss.SSSZ") private Date createdDate; - public User(String firstName,String lastName) { - super(firstName, lastName); - this.createdDate = new Date(); + public User(String firstName, String lastName) { + super(firstName, lastName); + this.createdDate = new Date(); } public Date getCreatedDate() { return createdDate; } - @JsonFormat(shape = JsonFormat.Shape.STRING, - pattern = "yyyy-MM-dd@HH:mm:ss.SSSZ", - locale = "en_GB") + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd@HH:mm:ss.SSSZ", locale = "en_GB") public Date getCurrentDate() { - return new Date(); + return new Date(); } @JsonFormat(shape = JsonFormat.Shape.NUMBER) public Date getDateNum() { - return new Date(); + return new Date(); } } diff --git a/jackson/src/main/java/com/baeldung/jackson/inclusion/jsonignore/Person.java b/jackson/src/main/java/com/baeldung/jackson/inclusion/jsonignore/Person.java index 8c18522627..0037d83148 100644 --- a/jackson/src/main/java/com/baeldung/jackson/inclusion/jsonignore/Person.java +++ b/jackson/src/main/java/com/baeldung/jackson/inclusion/jsonignore/Person.java @@ -17,7 +17,8 @@ public class Person { private String firstName; private String lastName; - public Person(){} + public Person() { + } public Person(String firstName, String lastName) { this.id = UUID.randomUUID(); diff --git a/jackson/src/main/java/com/baeldung/jackson/inclusion/jsonignoreproperties/Course.java b/jackson/src/main/java/com/baeldung/jackson/inclusion/jsonignoreproperties/Course.java index e6d62eee3d..70b4dd9842 100644 --- a/jackson/src/main/java/com/baeldung/jackson/inclusion/jsonignoreproperties/Course.java +++ b/jackson/src/main/java/com/baeldung/jackson/inclusion/jsonignoreproperties/Course.java @@ -12,10 +12,12 @@ import java.util.List; * @author Alex Theedom www.readlearncode.com * @version 1.0 */ -@JsonIgnoreProperties({"medium"}) +@JsonIgnoreProperties({ "medium" }) public class Course extends Item { - public enum Medium {CLASSROOM, ONLINE} + public enum Medium { + CLASSROOM, ONLINE + } public enum Level { BEGINNER("Beginner", 1), INTERMEDIATE("Intermediate", 2), ADVANCED("Advanced", 3); diff --git a/jackson/src/main/java/com/baeldung/jackson/inheritance/ItemIdAddedToUser.java b/jackson/src/main/java/com/baeldung/jackson/inheritance/ItemIdAddedToUser.java index 11aa8ddb1a..db0412b09b 100644 --- a/jackson/src/main/java/com/baeldung/jackson/inheritance/ItemIdAddedToUser.java +++ b/jackson/src/main/java/com/baeldung/jackson/inheritance/ItemIdAddedToUser.java @@ -12,10 +12,7 @@ public class ItemIdAddedToUser extends Event { private final Long quantity; @JsonCreator - public ItemIdAddedToUser(@JsonProperty("id") String id, - @JsonProperty("timestamp") Long timestamp, - @JsonProperty("itemId") String itemId, - @JsonProperty("quantity") Long quantity) { + public ItemIdAddedToUser(@JsonProperty("id") String id, @JsonProperty("timestamp") Long timestamp, @JsonProperty("itemId") String itemId, @JsonProperty("quantity") Long quantity) { super(id, timestamp); this.itemId = itemId; this.quantity = quantity; diff --git a/jackson/src/main/java/com/baeldung/jackson/inheritance/ItemIdRemovedFromUser.java b/jackson/src/main/java/com/baeldung/jackson/inheritance/ItemIdRemovedFromUser.java index 682394ddf3..ab3b9bf34f 100644 --- a/jackson/src/main/java/com/baeldung/jackson/inheritance/ItemIdRemovedFromUser.java +++ b/jackson/src/main/java/com/baeldung/jackson/inheritance/ItemIdRemovedFromUser.java @@ -10,10 +10,7 @@ public class ItemIdRemovedFromUser extends Event { private final Long quantity; @JsonCreator - public ItemIdRemovedFromUser(@JsonProperty("id") String id, - @JsonProperty("timestamp") Long timestamp, - @JsonProperty("itemId") String itemId, - @JsonProperty("quantity") Long quantity) { + public ItemIdRemovedFromUser(@JsonProperty("id") String id, @JsonProperty("timestamp") Long timestamp, @JsonProperty("itemId") String itemId, @JsonProperty("quantity") Long quantity) { super(id, timestamp); this.itemId = itemId; this.quantity = quantity; diff --git a/jackson/src/main/java/com/baeldung/jackson/miscellaneous/custom/Course.java b/jackson/src/main/java/com/baeldung/jackson/miscellaneous/custom/Course.java index 8825677e86..a44492b9f7 100644 --- a/jackson/src/main/java/com/baeldung/jackson/miscellaneous/custom/Course.java +++ b/jackson/src/main/java/com/baeldung/jackson/miscellaneous/custom/Course.java @@ -13,7 +13,9 @@ import java.util.List; @CustomCourseAnnotation public class Course extends Item { - public enum Medium {CLASSROOM, ONLINE} + public enum Medium { + CLASSROOM, ONLINE + } public enum Level { BEGINNER("Beginner", 1), INTERMEDIATE("Intermediate", 2), ADVANCED("Advanced", 3); diff --git a/jackson/src/main/java/com/baeldung/jackson/miscellaneous/custom/CustomCourseAnnotation.java b/jackson/src/main/java/com/baeldung/jackson/miscellaneous/custom/CustomCourseAnnotation.java index 37b0bf357e..d7f72ca6ec 100644 --- a/jackson/src/main/java/com/baeldung/jackson/miscellaneous/custom/CustomCourseAnnotation.java +++ b/jackson/src/main/java/com/baeldung/jackson/miscellaneous/custom/CustomCourseAnnotation.java @@ -14,7 +14,7 @@ import java.lang.annotation.RetentionPolicy; @Retention(RetentionPolicy.RUNTIME) @JacksonAnnotationsInside @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonPropertyOrder({"title", "price", "id", "duration", "authors", "level"}) -@JsonIgnoreProperties({"prerequisite"}) +@JsonPropertyOrder({ "title", "price", "id", "duration", "authors", "level" }) +@JsonIgnoreProperties({ "prerequisite" }) public @interface CustomCourseAnnotation { } diff --git a/jackson/src/main/java/com/baeldung/jackson/miscellaneous/custom/Item.java b/jackson/src/main/java/com/baeldung/jackson/miscellaneous/custom/Item.java index 930c4afb58..6625283dec 100644 --- a/jackson/src/main/java/com/baeldung/jackson/miscellaneous/custom/Item.java +++ b/jackson/src/main/java/com/baeldung/jackson/miscellaneous/custom/Item.java @@ -20,7 +20,8 @@ public class Item { private List authors = new ArrayList<>(); private float price; - public Item(){} + public Item() { + } public Item(String title, Author author) { this.id = UUID.randomUUID(); diff --git a/jackson/src/main/java/com/baeldung/jackson/miscellaneous/disable/Author.java b/jackson/src/main/java/com/baeldung/jackson/miscellaneous/disable/Author.java index 8df3aec051..0638e32925 100644 --- a/jackson/src/main/java/com/baeldung/jackson/miscellaneous/disable/Author.java +++ b/jackson/src/main/java/com/baeldung/jackson/miscellaneous/disable/Author.java @@ -16,7 +16,7 @@ import java.util.List; * @version 1.0 */ @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonPropertyOrder({"lastName", "items", "firstName", "id"}) +@JsonPropertyOrder({ "lastName", "items", "firstName", "id" }) public class Author extends Person { @JsonIgnore diff --git a/jackson/src/main/java/com/baeldung/jackson/polymorphism/Order.java b/jackson/src/main/java/com/baeldung/jackson/polymorphism/Order.java index 1eab9f5d02..1813148b2b 100644 --- a/jackson/src/main/java/com/baeldung/jackson/polymorphism/Order.java +++ b/jackson/src/main/java/com/baeldung/jackson/polymorphism/Order.java @@ -18,12 +18,8 @@ public class Order { private Type type; private int internalAudit; - @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, - include = JsonTypeInfo.As.PROPERTY, - property = "ordertype") - @JsonSubTypes({ - @JsonSubTypes.Type(value = InternalType.class, name = "internal") - }) + @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "ordertype") + @JsonSubTypes({ @JsonSubTypes.Type(value = InternalType.class, name = "internal") }) public static class Type { public long id; public String name; diff --git a/jackson/src/main/java/com/baeldung/jackson/serialization/ActorJacksonSerializer.java b/jackson/src/main/java/com/baeldung/jackson/serialization/ActorJacksonSerializer.java index 32a6358003..2340de5957 100644 --- a/jackson/src/main/java/com/baeldung/jackson/serialization/ActorJacksonSerializer.java +++ b/jackson/src/main/java/com/baeldung/jackson/serialization/ActorJacksonSerializer.java @@ -24,8 +24,11 @@ public class ActorJacksonSerializer extends StdSerializer { jsonGenerator.writeStartObject(); jsonGenerator.writeStringField("imdbId", actor.getImdbId()); jsonGenerator.writeObjectField("dateOfBirth", actor.getDateOfBirth() != null ? sdf.format(actor.getDateOfBirth()) : null); - jsonGenerator.writeNumberField("N° Film: ", actor.getFilmography() != null ? actor.getFilmography().size() : null); - jsonGenerator.writeStringField("filmography", actor.getFilmography().stream().collect(Collectors.joining("-"))); + jsonGenerator.writeNumberField("N° Film: ", actor.getFilmography() != null ? actor.getFilmography() + .size() : null); + jsonGenerator.writeStringField("filmography", actor.getFilmography() + .stream() + .collect(Collectors.joining("-"))); jsonGenerator.writeEndObject(); } } \ No newline at end of file diff --git a/jackson/src/main/java/com/baeldung/jackson/serialization/MyPairDeserializer.java b/jackson/src/main/java/com/baeldung/jackson/serialization/MyPairDeserializer.java index 0aa6db98d0..43bdc1c500 100644 --- a/jackson/src/main/java/com/baeldung/jackson/serialization/MyPairDeserializer.java +++ b/jackson/src/main/java/com/baeldung/jackson/serialization/MyPairDeserializer.java @@ -9,10 +9,9 @@ import com.fasterxml.jackson.databind.KeyDeserializer; public class MyPairDeserializer extends KeyDeserializer { - @Override - public MyPair deserializeKey(String key, DeserializationContext ctxt) - throws IOException, JsonProcessingException { + @Override + public MyPair deserializeKey(String key, DeserializationContext ctxt) throws IOException, JsonProcessingException { - return new MyPair(key); - } + return new MyPair(key); + } } \ No newline at end of file diff --git a/jackson/src/main/java/com/baeldung/jackson/serialization/MyPairSerializer.java b/jackson/src/main/java/com/baeldung/jackson/serialization/MyPairSerializer.java index 68afb6c193..fee1cafe16 100644 --- a/jackson/src/main/java/com/baeldung/jackson/serialization/MyPairSerializer.java +++ b/jackson/src/main/java/com/baeldung/jackson/serialization/MyPairSerializer.java @@ -12,14 +12,12 @@ import com.fasterxml.jackson.databind.SerializerProvider; public class MyPairSerializer extends JsonSerializer { - private final ObjectMapper mapper = new ObjectMapper(); + private final ObjectMapper mapper = new ObjectMapper(); - @Override - public void serialize(MyPair value, JsonGenerator gen, - SerializerProvider serializers) throws IOException, - JsonProcessingException { - StringWriter writer = new StringWriter(); - mapper.writeValue(writer, value); - gen.writeFieldName(writer.toString()); - } + @Override + public void serialize(MyPair value, JsonGenerator gen, SerializerProvider serializers) throws IOException, JsonProcessingException { + StringWriter writer = new StringWriter(); + mapper.writeValue(writer, value); + gen.writeFieldName(writer.toString()); + } } \ No newline at end of file diff --git a/jackson/src/main/java/com/baeldung/jackson/serialization/jsongetter/Author.java b/jackson/src/main/java/com/baeldung/jackson/serialization/jsongetter/Author.java index 13453edeb2..8d89fefce7 100644 --- a/jackson/src/main/java/com/baeldung/jackson/serialization/jsongetter/Author.java +++ b/jackson/src/main/java/com/baeldung/jackson/serialization/jsongetter/Author.java @@ -1,6 +1,5 @@ package com.baeldung.jackson.serialization.jsongetter; - import com.baeldung.jackson.domain.Item; import com.baeldung.jackson.domain.Person; import com.fasterxml.jackson.annotation.JsonGetter; diff --git a/jackson/src/main/java/com/baeldung/jackson/serialization/jsonpropertyorder/Author.java b/jackson/src/main/java/com/baeldung/jackson/serialization/jsonpropertyorder/Author.java index c5214f3305..dadf893cf9 100644 --- a/jackson/src/main/java/com/baeldung/jackson/serialization/jsonpropertyorder/Author.java +++ b/jackson/src/main/java/com/baeldung/jackson/serialization/jsonpropertyorder/Author.java @@ -1,6 +1,5 @@ package com.baeldung.jackson.serialization.jsonpropertyorder; - import com.baeldung.jackson.domain.Item; import com.fasterxml.jackson.annotation.JsonPropertyOrder; @@ -13,7 +12,7 @@ import java.util.List; * @author Alex Theedom www.readlearncode.com * @version 1.0 */ -@JsonPropertyOrder({"items", "firstName", "lastName", "id"}) +@JsonPropertyOrder({ "items", "firstName", "lastName", "id" }) public class Author extends Person { List items = new ArrayList<>(); diff --git a/jackson/src/main/java/com/baeldung/jackson/serialization/jsonserialize/Book.java b/jackson/src/main/java/com/baeldung/jackson/serialization/jsonserialize/Book.java index e682f7c394..0ecc4e72ce 100644 --- a/jackson/src/main/java/com/baeldung/jackson/serialization/jsonserialize/Book.java +++ b/jackson/src/main/java/com/baeldung/jackson/serialization/jsonserialize/Book.java @@ -19,7 +19,8 @@ public class Book extends Item { private Date published; private BigDecimal pages; - public Book(){} + public Book() { + } public Book(String title, Author author) { super(title, author); diff --git a/jackson/src/main/java/com/baeldung/jackson/serialization/jsonserialize/CustomDateSerializer.java b/jackson/src/main/java/com/baeldung/jackson/serialization/jsonserialize/CustomDateSerializer.java index 8e6d20cfe0..131f4f3695 100644 --- a/jackson/src/main/java/com/baeldung/jackson/serialization/jsonserialize/CustomDateSerializer.java +++ b/jackson/src/main/java/com/baeldung/jackson/serialization/jsonserialize/CustomDateSerializer.java @@ -17,8 +17,7 @@ import java.util.Date; */ public class CustomDateSerializer extends StdSerializer { - private static SimpleDateFormat formatter = - new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); + private static SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); public CustomDateSerializer() { this(null); @@ -29,8 +28,7 @@ public class CustomDateSerializer extends StdSerializer { } @Override - public void serialize(Date value, JsonGenerator gen, SerializerProvider arg2) - throws IOException, JsonProcessingException { + public void serialize(Date value, JsonGenerator gen, SerializerProvider arg2) throws IOException, JsonProcessingException { gen.writeString(formatter.format(value)); } } diff --git a/jackson/src/main/java/com/baeldung/jackson/serialization/jsonserialize/Item.java b/jackson/src/main/java/com/baeldung/jackson/serialization/jsonserialize/Item.java index ed6ac25184..56cfa85793 100644 --- a/jackson/src/main/java/com/baeldung/jackson/serialization/jsonserialize/Item.java +++ b/jackson/src/main/java/com/baeldung/jackson/serialization/jsonserialize/Item.java @@ -19,7 +19,8 @@ public class Item { private List authors = new ArrayList<>(); private float price; - public Item(){} + public Item() { + } public Item(String title, Author author) { this.id = UUID.randomUUID(); diff --git a/jackson/src/main/java/com/baeldung/jackson/serialization/jsonvalue/Course.java b/jackson/src/main/java/com/baeldung/jackson/serialization/jsonvalue/Course.java index eb7cb097e5..a3fdc2d8eb 100644 --- a/jackson/src/main/java/com/baeldung/jackson/serialization/jsonvalue/Course.java +++ b/jackson/src/main/java/com/baeldung/jackson/serialization/jsonvalue/Course.java @@ -14,7 +14,9 @@ import java.util.List; */ public class Course extends Item { - public enum Medium {CLASSROOM, ONLINE} + public enum Medium { + CLASSROOM, ONLINE + } public enum Level { BEGINNER("Beginner", 1), INTERMEDIATE("Intermediate", 2), ADVANCED("Advanced", 3); diff --git a/jackson/src/test/java/com/baeldung/jackson/annotation/extra/ExtraAnnotationUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/annotation/extra/ExtraAnnotationUnitTest.java index c4e0a2ecdb..647c451659 100644 --- a/jackson/src/test/java/com/baeldung/jackson/annotation/extra/ExtraAnnotationUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/annotation/extra/ExtraAnnotationUnitTest.java @@ -47,9 +47,10 @@ public class ExtraAnnotationUnitTest { ObjectMapper mapper = new ObjectMapper(); BeanWithoutAppend bean = new BeanWithoutAppend(2, "Bean Without Append Annotation"); - ObjectWriter writer = mapper.writerFor(BeanWithoutAppend.class).withAttribute("version", "1.0"); + ObjectWriter writer = mapper.writerFor(BeanWithoutAppend.class) + .withAttribute("version", "1.0"); String jsonString = writer.writeValueAsString(bean); - + assertThat(jsonString, not(containsString("version"))); assertThat(jsonString, not(containsString("1.0"))); } @@ -59,9 +60,10 @@ public class ExtraAnnotationUnitTest { ObjectMapper mapper = new ObjectMapper(); BeanWithAppend bean = new BeanWithAppend(2, "Bean With Append Annotation"); - ObjectWriter writer = mapper.writerFor(BeanWithAppend.class).withAttribute("version", "1.0"); + ObjectWriter writer = mapper.writerFor(BeanWithAppend.class) + .withAttribute("version", "1.0"); String jsonString = writer.writeValueAsString(bean); - + assertThat(jsonString, containsString("version")); assertThat(jsonString, containsString("1.0")); } @@ -71,7 +73,7 @@ public class ExtraAnnotationUnitTest { ObjectMapper mapper = new ObjectMapper(); NamingBean bean = new NamingBean(3, "Naming Bean"); String jsonString = mapper.writeValueAsString(bean); - + assertThat(jsonString, containsString("bean_name")); } diff --git a/jackson/src/test/java/com/baeldung/jackson/annotation/extra/IdentityReferenceBeans.java b/jackson/src/test/java/com/baeldung/jackson/annotation/extra/IdentityReferenceBeans.java index 495bb7de43..0a8736d9a5 100644 --- a/jackson/src/test/java/com/baeldung/jackson/annotation/extra/IdentityReferenceBeans.java +++ b/jackson/src/test/java/com/baeldung/jackson/annotation/extra/IdentityReferenceBeans.java @@ -4,7 +4,6 @@ import com.fasterxml.jackson.annotation.JsonIdentityInfo; import com.fasterxml.jackson.annotation.JsonIdentityReference; import com.fasterxml.jackson.annotation.ObjectIdGenerators; - public class IdentityReferenceBeans { @JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id") public static class BeanWithoutIdentityReference { @@ -32,7 +31,7 @@ public class IdentityReferenceBeans { this.name = name; } } - + @JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id") @JsonIdentityReference(alwaysAsId = true) public static class BeanWithIdentityReference { diff --git a/jackson/src/test/java/com/baeldung/jackson/bidirection/CustomListSerializer.java b/jackson/src/test/java/com/baeldung/jackson/bidirection/CustomListSerializer.java index 75e0a4ecb7..c6babdee01 100644 --- a/jackson/src/test/java/com/baeldung/jackson/bidirection/CustomListSerializer.java +++ b/jackson/src/test/java/com/baeldung/jackson/bidirection/CustomListSerializer.java @@ -20,6 +20,7 @@ public class CustomListSerializer extends StdSerializer public CustomListSerializer(final Class> t) { super(t); } + @Override public void serialize(final List items, final JsonGenerator generator, final SerializerProvider provider) throws IOException, JsonProcessingException { final List ids = new ArrayList(); diff --git a/jackson/src/test/java/com/baeldung/jackson/date/CustomLocalDateTimeSerializer.java b/jackson/src/test/java/com/baeldung/jackson/date/CustomLocalDateTimeSerializer.java index dbcf42488e..ac7d772f0f 100644 --- a/jackson/src/test/java/com/baeldung/jackson/date/CustomLocalDateTimeSerializer.java +++ b/jackson/src/test/java/com/baeldung/jackson/date/CustomLocalDateTimeSerializer.java @@ -11,7 +11,6 @@ import com.fasterxml.jackson.databind.ser.std.StdSerializer; public class CustomLocalDateTimeSerializer extends StdSerializer { - private static final long serialVersionUID = -7449444168934819290L; private static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"); diff --git a/jackson/src/test/java/com/baeldung/jackson/deserialization/ItemDeserializer.java b/jackson/src/test/java/com/baeldung/jackson/deserialization/ItemDeserializer.java index e9c89b8c78..bbc3f31a6c 100644 --- a/jackson/src/test/java/com/baeldung/jackson/deserialization/ItemDeserializer.java +++ b/jackson/src/test/java/com/baeldung/jackson/deserialization/ItemDeserializer.java @@ -28,9 +28,11 @@ public class ItemDeserializer extends StdDeserializer { */ @Override public Item deserialize(final JsonParser jp, final DeserializationContext ctxt) throws IOException, JsonProcessingException { - final JsonNode node = jp.getCodec().readTree(jp); + final JsonNode node = jp.getCodec() + .readTree(jp); final int id = (Integer) ((IntNode) node.get("id")).numberValue(); - final String itemName = node.get("itemName").asText(); + final String itemName = node.get("itemName") + .asText(); final int userId = (Integer) ((IntNode) node.get("createdBy")).numberValue(); return new Item(id, itemName, new User(userId, null)); diff --git a/jackson/src/test/java/com/baeldung/jackson/deserialization/ItemDeserializerOnClass.java b/jackson/src/test/java/com/baeldung/jackson/deserialization/ItemDeserializerOnClass.java index 2036780e99..eaba9a7173 100644 --- a/jackson/src/test/java/com/baeldung/jackson/deserialization/ItemDeserializerOnClass.java +++ b/jackson/src/test/java/com/baeldung/jackson/deserialization/ItemDeserializerOnClass.java @@ -28,9 +28,11 @@ public class ItemDeserializerOnClass extends StdDeserializer */ @Override public ItemWithSerializer deserialize(final JsonParser jp, final DeserializationContext ctxt) throws IOException, JsonProcessingException { - final JsonNode node = jp.getCodec().readTree(jp); + final JsonNode node = jp.getCodec() + .readTree(jp); final int id = (Integer) ((IntNode) node.get("id")).numberValue(); - final String itemName = node.get("itemName").asText(); + final String itemName = node.get("itemName") + .asText(); final int userId = (Integer) ((IntNode) node.get("owner")).numberValue(); return new ItemWithSerializer(id, itemName, new User(userId, null)); diff --git a/jackson/src/test/java/com/baeldung/jackson/deserialization/JacksonMapDeserializeUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/deserialization/JacksonMapDeserializeUnitTest.java index 4d5db699a0..1c3e95241a 100644 --- a/jackson/src/test/java/com/baeldung/jackson/deserialization/JacksonMapDeserializeUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/deserialization/JacksonMapDeserializeUnitTest.java @@ -16,54 +16,49 @@ import com.fasterxml.jackson.databind.ObjectMapper; public class JacksonMapDeserializeUnitTest { - private Map map; - private Map cmap; - final ObjectMapper mapper = new ObjectMapper(); + private Map map; + private Map cmap; + final ObjectMapper mapper = new ObjectMapper(); - @Test - public void whenSimpleMapDeserialize_thenCorrect() - throws JsonParseException, JsonMappingException, IOException { + @Test + public void whenSimpleMapDeserialize_thenCorrect() throws JsonParseException, JsonMappingException, IOException { - final String jsonInput = "{\"key\": \"value\"}"; - TypeReference> typeRef = new TypeReference>() { - }; + final String jsonInput = "{\"key\": \"value\"}"; + TypeReference> typeRef = new TypeReference>() { + }; - final Map map = mapper.readValue(jsonInput, typeRef); + final Map map = mapper.readValue(jsonInput, typeRef); - Assert.assertEquals("value", map.get("key")); - } + Assert.assertEquals("value", map.get("key")); + } - @Test - public void whenObjectStringMapDeserialize_thenCorrect() - throws JsonParseException, JsonMappingException, IOException { + @Test + public void whenObjectStringMapDeserialize_thenCorrect() throws JsonParseException, JsonMappingException, IOException { - final String jsonInput = "{\"Abbott and Costello\":\"Comedy\"}"; + final String jsonInput = "{\"Abbott and Costello\":\"Comedy\"}"; - TypeReference> typeRef = new TypeReference>() { - }; + TypeReference> typeRef = new TypeReference>() { + }; - map = mapper.readValue(jsonInput, typeRef); + map = mapper.readValue(jsonInput, typeRef); - Assert.assertEquals("Comedy", map.get(new MyPair("Abbott", "Costello"))); + Assert.assertEquals("Comedy", map.get(new MyPair("Abbott", "Costello"))); - ClassWithAMap classWithMap = mapper.readValue(jsonInput, - ClassWithAMap.class); + ClassWithAMap classWithMap = mapper.readValue(jsonInput, ClassWithAMap.class); - Assert.assertEquals("Comedy", - classWithMap.getMap().get(new MyPair("Abbott", "Costello"))); - } + Assert.assertEquals("Comedy", classWithMap.getMap() + .get(new MyPair("Abbott", "Costello"))); + } - @Test - public void whenObjectObjectMapDeserialize_thenCorrect() - throws JsonParseException, JsonMappingException, IOException { + @Test + public void whenObjectObjectMapDeserialize_thenCorrect() throws JsonParseException, JsonMappingException, IOException { - final String jsonInput = "{\"Abbott and Costello\" : \"Comedy and 1940s\"}"; - TypeReference> typeRef = new TypeReference>() { - }; + final String jsonInput = "{\"Abbott and Costello\" : \"Comedy and 1940s\"}"; + TypeReference> typeRef = new TypeReference>() { + }; - cmap = mapper.readValue(jsonInput, typeRef); + cmap = mapper.readValue(jsonInput, typeRef); - Assert.assertEquals(new MyPair("Comedy", "1940s"), - cmap.get(new MyPair("Abbott", "Costello"))); - } + Assert.assertEquals(new MyPair("Comedy", "1940s"), cmap.get(new MyPair("Abbott", "Costello"))); + } } diff --git a/jackson/src/test/java/com/baeldung/jackson/deserialization/jacksoninject/JacksonInjectUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/deserialization/jacksoninject/JacksonInjectUnitTest.java index 81bb14c533..96dbff6f3c 100644 --- a/jackson/src/test/java/com/baeldung/jackson/deserialization/jacksoninject/JacksonInjectUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/deserialization/jacksoninject/JacksonInjectUnitTest.java @@ -27,7 +27,9 @@ public class JacksonInjectUnitTest { // act InjectableValues inject = new InjectableValues.Std().addValue(UUID.class, id); - Author author = new ObjectMapper().reader(inject).forType(Author.class).readValue(authorJson); + Author author = new ObjectMapper().reader(inject) + .forType(Author.class) + .readValue(authorJson); // assert assertThat(author.getId()).isEqualTo(id); diff --git a/jackson/src/test/java/com/baeldung/jackson/deserialization/jsonanysetter/JsonAnySetterUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/deserialization/jsonanysetter/JsonAnySetterUnitTest.java index 7c338696e7..2e1f94bc3c 100644 --- a/jackson/src/test/java/com/baeldung/jackson/deserialization/jsonanysetter/JsonAnySetterUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/deserialization/jsonanysetter/JsonAnySetterUnitTest.java @@ -23,15 +23,28 @@ public class JsonAnySetterUnitTest { String json = "{\"USA\":10.00,\"UK\":15.00,\"China\":23.00,\"Brazil\":12.00,\"France\":8.00,\"Russia\":18.00}"; // act - Inventory inventory = new ObjectMapper().readerFor(Inventory.class).readValue(json); + Inventory inventory = new ObjectMapper().readerFor(Inventory.class) + .readValue(json); // assert - assertThat(from(json).getMap(".").get("USA")).isEqualTo(inventory.getCountryDeliveryCost().get("USA")); - assertThat(from(json).getMap(".").get("UK")).isEqualTo(inventory.getCountryDeliveryCost().get("UK")); - assertThat(from(json).getMap(".").get("China")).isEqualTo(inventory.getCountryDeliveryCost().get("China")); - assertThat(from(json).getMap(".").get("Brazil")).isEqualTo(inventory.getCountryDeliveryCost().get("Brazil")); - assertThat(from(json).getMap(".").get("France")).isEqualTo(inventory.getCountryDeliveryCost().get("France")); - assertThat(from(json).getMap(".").get("Russia")).isEqualTo(inventory.getCountryDeliveryCost().get("Russia")); + assertThat(from(json).getMap(".") + .get("USA")).isEqualTo(inventory.getCountryDeliveryCost() + .get("USA")); + assertThat(from(json).getMap(".") + .get("UK")).isEqualTo(inventory.getCountryDeliveryCost() + .get("UK")); + assertThat(from(json).getMap(".") + .get("China")).isEqualTo(inventory.getCountryDeliveryCost() + .get("China")); + assertThat(from(json).getMap(".") + .get("Brazil")).isEqualTo(inventory.getCountryDeliveryCost() + .get("Brazil")); + assertThat(from(json).getMap(".") + .get("France")).isEqualTo(inventory.getCountryDeliveryCost() + .get("France")); + assertThat(from(json).getMap(".") + .get("Russia")).isEqualTo(inventory.getCountryDeliveryCost() + .get("Russia")); } } \ No newline at end of file diff --git a/jackson/src/test/java/com/baeldung/jackson/deserialization/jsoncreator/JsonCreatorUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/deserialization/jsoncreator/JsonCreatorUnitTest.java index cc6b2a28aa..cc245dab66 100644 --- a/jackson/src/test/java/com/baeldung/jackson/deserialization/jsoncreator/JsonCreatorUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/deserialization/jsoncreator/JsonCreatorUnitTest.java @@ -20,14 +20,11 @@ public class JsonCreatorUnitTest { public void whenDeserializingUsingJsonCreator_thenCorrect() throws IOException { // arrange - String authorJson = - "{" + - " \"christianName\": \"Alex\"," + - " \"surname\": \"Theedom\"" + - "}"; + String authorJson = "{" + " \"christianName\": \"Alex\"," + " \"surname\": \"Theedom\"" + "}"; // act - final Author author = new ObjectMapper().readerFor(Author.class).readValue(authorJson); + final Author author = new ObjectMapper().readerFor(Author.class) + .readValue(authorJson); // assert assertThat(from(authorJson).getString("christianName")).isEqualTo(author.getFirstName()); diff --git a/jackson/src/test/java/com/baeldung/jackson/deserialization/jsondeserialize/JsonDeserializeUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/deserialization/jsondeserialize/JsonDeserializeUnitTest.java index dca2252431..1bcde998d6 100644 --- a/jackson/src/test/java/com/baeldung/jackson/deserialization/jsondeserialize/JsonDeserializeUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/deserialization/jsondeserialize/JsonDeserializeUnitTest.java @@ -24,7 +24,8 @@ public class JsonDeserializeUnitTest { String bookJson = "{\"id\":\"957c43f2-fa2e-42f9-bf75-6e3d5bb6960a\",\"title\":\"Effective Java\",\"authors\":[{\"id\":\"9bcd817d-0141-42e6-8f04-e5aaab0980b6\",\"firstName\":\"Joshua\",\"lastName\":\"Bloch\"}],\"price\":0,\"published\":\"25-12-2017 13:30:25\",\"pages\":null,\"isbn\":null}"; // act - Book book = new ObjectMapper().readerFor(Book.class).readValue(bookJson); + Book book = new ObjectMapper().readerFor(Book.class) + .readValue(bookJson); // assert SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); diff --git a/jackson/src/test/java/com/baeldung/jackson/deserialization/jsonsetter/JsonSetterUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/deserialization/jsonsetter/JsonSetterUnitTest.java index 42e105cd52..4379fe376c 100644 --- a/jackson/src/test/java/com/baeldung/jackson/deserialization/jsonsetter/JsonSetterUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/deserialization/jsonsetter/JsonSetterUnitTest.java @@ -23,10 +23,13 @@ public class JsonSetterUnitTest { String json = "{\"firstName\":\"Alex\",\"lastName\":\"Theedom\",\"publications\":[{\"title\":\"Professional Java EE Design Patterns\"}]}"; // act - Author author = new ObjectMapper().readerFor(Author.class).readValue(json); + Author author = new ObjectMapper().readerFor(Author.class) + .readValue(json); // assert - assertThat(from(json).getList("publications").size()).isEqualTo(author.getItems().size()); + assertThat(from(json).getList("publications") + .size()).isEqualTo(author.getItems() + .size()); } } \ No newline at end of file diff --git a/jackson/src/test/java/com/baeldung/jackson/dynamicIgnore/Address.java b/jackson/src/test/java/com/baeldung/jackson/dynamicIgnore/Address.java index c2d2e84d45..daca85f66a 100644 --- a/jackson/src/test/java/com/baeldung/jackson/dynamicIgnore/Address.java +++ b/jackson/src/test/java/com/baeldung/jackson/dynamicIgnore/Address.java @@ -1,6 +1,5 @@ package com.baeldung.jackson.dynamicIgnore; - public class Address implements Hidable { private String city; private String country; diff --git a/jackson/src/test/java/com/baeldung/jackson/dynamicIgnore/Hidable.java b/jackson/src/test/java/com/baeldung/jackson/dynamicIgnore/Hidable.java index edca786432..a32e6844a6 100644 --- a/jackson/src/test/java/com/baeldung/jackson/dynamicIgnore/Hidable.java +++ b/jackson/src/test/java/com/baeldung/jackson/dynamicIgnore/Hidable.java @@ -2,7 +2,6 @@ package com.baeldung.jackson.dynamicIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; - @JsonIgnoreProperties("hidden") public interface Hidable { boolean isHidden(); diff --git a/jackson/src/test/java/com/baeldung/jackson/dynamicIgnore/Person.java b/jackson/src/test/java/com/baeldung/jackson/dynamicIgnore/Person.java index 366f611edf..daa62b4be6 100644 --- a/jackson/src/test/java/com/baeldung/jackson/dynamicIgnore/Person.java +++ b/jackson/src/test/java/com/baeldung/jackson/dynamicIgnore/Person.java @@ -1,6 +1,5 @@ package com.baeldung.jackson.dynamicIgnore; - public class Person implements Hidable { private String name; private Address address; @@ -13,7 +12,6 @@ public class Person implements Hidable { this.hidden = hidden; } - public String getName() { return name; } @@ -29,6 +27,7 @@ public class Person implements Hidable { public void setAddress(final Address address) { this.address = address; } + @Override public boolean isHidden() { return hidden; diff --git a/jackson/src/test/java/com/baeldung/jackson/format/JsonFormatUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/format/JsonFormatUnitTest.java index 7ce03ff625..cf166fdc36 100755 --- a/jackson/src/test/java/com/baeldung/jackson/format/JsonFormatUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/format/JsonFormatUnitTest.java @@ -22,18 +22,16 @@ public class JsonFormatUnitTest { @Test public void whenSerializedDateFormat_thenCorrect() throws JsonProcessingException { - User user = new User("Jay", "Sridhar"); + User user = new User("Jay", "Sridhar"); - String result = new ObjectMapper().writeValueAsString(user); + String result = new ObjectMapper().writeValueAsString(user); - // Expected to match: "2016-12-19@09:34:42.628+0000" - assertThat(from(result).getString("createdDate")) - .matches("\\d{4}\\-\\d{2}\\-\\d{2}@\\d{2}:\\d{2}:\\d{2}\\.\\d{3}\\+\\d{4}"); + // Expected to match: "2016-12-19@09:34:42.628+0000" + assertThat(from(result).getString("createdDate")).matches("\\d{4}\\-\\d{2}\\-\\d{2}@\\d{2}:\\d{2}:\\d{2}\\.\\d{3}\\+\\d{4}"); - // Expected to be close to current time - long now = new Date().getTime(); - assertThat(from(result).getLong("dateNum")) - .isCloseTo(now, withPercentage(10.0)); + // Expected to be close to current time + long now = new Date().getTime(); + assertThat(from(result).getLong("dateNum")).isCloseTo(now, withPercentage(10.0)); } } diff --git a/jackson/src/test/java/com/baeldung/jackson/general/jsonfilter/JsonFilterUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/general/jsonfilter/JsonFilterUnitTest.java index 3eeec8dcee..6fcc57faa7 100644 --- a/jackson/src/test/java/com/baeldung/jackson/general/jsonfilter/JsonFilterUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/general/jsonfilter/JsonFilterUnitTest.java @@ -23,11 +23,11 @@ public class JsonFilterUnitTest { // arrange Author author = new Author("Alex", "Theedom"); - FilterProvider filters = new SimpleFilterProvider() - .addFilter("authorFilter", SimpleBeanPropertyFilter.filterOutAllExcept("lastName")); + FilterProvider filters = new SimpleFilterProvider().addFilter("authorFilter", SimpleBeanPropertyFilter.filterOutAllExcept("lastName")); // act - String result = new ObjectMapper().writer(filters).writeValueAsString(author); + String result = new ObjectMapper().writer(filters) + .writeValueAsString(author); // assert assertThat(from(result).getList("items")).isNull(); diff --git a/jackson/src/test/java/com/baeldung/jackson/general/jsonformat/Book.java b/jackson/src/test/java/com/baeldung/jackson/general/jsonformat/Book.java index cacd11c804..e2eb4aa48a 100644 --- a/jackson/src/test/java/com/baeldung/jackson/general/jsonformat/Book.java +++ b/jackson/src/test/java/com/baeldung/jackson/general/jsonformat/Book.java @@ -17,9 +17,7 @@ public class Book extends Item { private String ISBN; - @JsonFormat( - shape = JsonFormat.Shape.STRING, - pattern = "dd-MM-yyyy HH:mm:ss") + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy HH:mm:ss") private Date published; private BigDecimal pages; diff --git a/jackson/src/test/java/com/baeldung/jackson/general/jsonformat/JsonFormatUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/general/jsonformat/JsonFormatUnitTest.java index 0fcfe94cf8..1fe217cef6 100644 --- a/jackson/src/test/java/com/baeldung/jackson/general/jsonformat/JsonFormatUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/general/jsonformat/JsonFormatUnitTest.java @@ -31,10 +31,7 @@ public class JsonFormatUnitTest { String toParse = "20-12-2014 14:30:00"; Date date = df.parse(toParse); - Book book = new Book( - "Design Patterns: Elements of Reusable Object-oriented Software", - new Author("The", "GoF") - ); + Book book = new Book("Design Patterns: Elements of Reusable Object-oriented Software", new Author("The", "GoF")); book.setPublished(date); // act diff --git a/jackson/src/test/java/com/baeldung/jackson/general/jsonidentityinfo/Author.java b/jackson/src/test/java/com/baeldung/jackson/general/jsonidentityinfo/Author.java index ebe1a69c4e..1f36b95b2a 100644 --- a/jackson/src/test/java/com/baeldung/jackson/general/jsonidentityinfo/Author.java +++ b/jackson/src/test/java/com/baeldung/jackson/general/jsonidentityinfo/Author.java @@ -12,9 +12,7 @@ import java.util.List; * @author Alex Theedom www.readlearncode.com * @version 1.0 */ -@JsonIdentityInfo( - generator = ObjectIdGenerators.PropertyGenerator.class, - property = "id") +@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id") public class Author extends Person { private List items = new ArrayList<>(); diff --git a/jackson/src/test/java/com/baeldung/jackson/general/jsonidentityinfo/Course.java b/jackson/src/test/java/com/baeldung/jackson/general/jsonidentityinfo/Course.java index 3db6d3dddb..80dd9c275e 100644 --- a/jackson/src/test/java/com/baeldung/jackson/general/jsonidentityinfo/Course.java +++ b/jackson/src/test/java/com/baeldung/jackson/general/jsonidentityinfo/Course.java @@ -1,6 +1,5 @@ package com.baeldung.jackson.general.jsonidentityinfo; - import java.util.List; /** @@ -11,7 +10,9 @@ import java.util.List; */ public class Course extends Item { - public enum Medium {CLASSROOM, ONLINE} + public enum Medium { + CLASSROOM, ONLINE + } public enum Level { BEGINNER("Beginner", 1), INTERMEDIATE("Intermediate", 2), ADVANCED("Advanced", 3); diff --git a/jackson/src/test/java/com/baeldung/jackson/general/jsonidentityinfo/Item.java b/jackson/src/test/java/com/baeldung/jackson/general/jsonidentityinfo/Item.java index f252da4b1b..bad6562122 100644 --- a/jackson/src/test/java/com/baeldung/jackson/general/jsonidentityinfo/Item.java +++ b/jackson/src/test/java/com/baeldung/jackson/general/jsonidentityinfo/Item.java @@ -13,9 +13,7 @@ import java.util.UUID; * @author Alex Theedom www.readlearncode.com * @version 1.0 */ -@JsonIdentityInfo( - generator = ObjectIdGenerators.PropertyGenerator.class, - property = "id") +@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id") public class Item { private UUID id; @@ -23,7 +21,8 @@ public class Item { private List authors = new ArrayList<>(); private float price; - public Item(){} + public Item() { + } public Item(String title, Author author) { this.id = UUID.randomUUID(); diff --git a/jackson/src/test/java/com/baeldung/jackson/general/jsonidentityinfo/Person.java b/jackson/src/test/java/com/baeldung/jackson/general/jsonidentityinfo/Person.java index 8a5b4b75e1..ea80814124 100644 --- a/jackson/src/test/java/com/baeldung/jackson/general/jsonidentityinfo/Person.java +++ b/jackson/src/test/java/com/baeldung/jackson/general/jsonidentityinfo/Person.java @@ -14,7 +14,8 @@ public class Person { private String firstName; private String lastName; - public Person(){} + public Person() { + } public Person(String firstName, String lastName) { this.id = UUID.randomUUID(); diff --git a/jackson/src/test/java/com/baeldung/jackson/general/jsonproperty/Item.java b/jackson/src/test/java/com/baeldung/jackson/general/jsonproperty/Item.java index 1deae26b21..d7ee430d51 100644 --- a/jackson/src/test/java/com/baeldung/jackson/general/jsonproperty/Item.java +++ b/jackson/src/test/java/com/baeldung/jackson/general/jsonproperty/Item.java @@ -19,7 +19,8 @@ public class Item { private List authors = new ArrayList<>(); private float price; - public Item(){} + public Item() { + } public Item(String title, Author author) { this.id = UUID.randomUUID(); diff --git a/jackson/src/test/java/com/baeldung/jackson/general/jsonproperty/JsonPropertyUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/general/jsonproperty/JsonPropertyUnitTest.java index 94046f8a56..0b88e7fc47 100644 --- a/jackson/src/test/java/com/baeldung/jackson/general/jsonproperty/JsonPropertyUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/general/jsonproperty/JsonPropertyUnitTest.java @@ -21,10 +21,7 @@ public class JsonPropertyUnitTest { public void whenSerializingUsingJsonProperty_thenCorrect() throws JsonProcessingException { // arrange - Book book = new Book( - "Design Patterns: Elements of Reusable Object-oriented Software", - new Author("The", "GoF") - ); + Book book = new Book("Design Patterns: Elements of Reusable Object-oriented Software", new Author("The", "GoF")); book.configureBinding("Hardback"); // act @@ -62,12 +59,12 @@ public class JsonPropertyUnitTest { String result = "{\"id\":\"cd941587-d1ae-4c2a-9a36-29533bf50411\",\"title\":\"Design Patterns: Elements of Reusable Object-oriented Software\",\"authors\":[{\"id\":\"c8e26318-2f5b-4fa2-9fdc-6e99be021fca\",\"firstName\":\"The\",\"lastName\":\"GoF\"}],\"binding\":\"Hardback\"}"; // act - Book book = new ObjectMapper().readerFor(Book.class).readValue(result); + Book book = new ObjectMapper().readerFor(Book.class) + .readValue(result); // assert assertThat(book.coverBinding()).isEqualTo("Hardback"); } - } \ No newline at end of file diff --git a/jackson/src/test/java/com/baeldung/jackson/general/jsonunwrapped/JsonUnwrappedUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/general/jsonunwrapped/JsonUnwrappedUnitTest.java index 491f706db4..5130e037d5 100644 --- a/jackson/src/test/java/com/baeldung/jackson/general/jsonunwrapped/JsonUnwrappedUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/general/jsonunwrapped/JsonUnwrappedUnitTest.java @@ -1,6 +1,5 @@ package com.baeldung.jackson.general.jsonunwrapped; - import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; diff --git a/jackson/src/test/java/com/baeldung/jackson/general/jsonview/JsonViewUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/general/jsonview/JsonViewUnitTest.java index 8ac10cac8b..ab609008ce 100644 --- a/jackson/src/test/java/com/baeldung/jackson/general/jsonview/JsonViewUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/general/jsonview/JsonViewUnitTest.java @@ -22,7 +22,8 @@ public class JsonViewUnitTest { Order order = new Order(120); // act - String result = new ObjectMapper().writerWithView(Views.Internal.class).writeValueAsString(order); + String result = new ObjectMapper().writerWithView(Views.Internal.class) + .writeValueAsString(order); // assert assertThat(from(result).getUUID("id")).isNotNull(); @@ -49,7 +50,8 @@ public class JsonViewUnitTest { Order order = new Order(120); // act - String result = new ObjectMapper().writerWithView(Views.Public.class).writeValueAsString(order); + String result = new ObjectMapper().writerWithView(Views.Public.class) + .writeValueAsString(order); // assert assertThat(from(result).getUUID("id")).isNotNull(); @@ -68,5 +70,4 @@ public class JsonViewUnitTest { } - } \ No newline at end of file diff --git a/jackson/src/test/java/com/baeldung/jackson/general/reference/Course.java b/jackson/src/test/java/com/baeldung/jackson/general/reference/Course.java index 9d99d632e7..251d25a517 100644 --- a/jackson/src/test/java/com/baeldung/jackson/general/reference/Course.java +++ b/jackson/src/test/java/com/baeldung/jackson/general/reference/Course.java @@ -1,6 +1,5 @@ package com.baeldung.jackson.general.reference; - import java.util.List; /** @@ -11,7 +10,9 @@ import java.util.List; */ public class Course extends Item { - public enum Medium {CLASSROOM, ONLINE} + public enum Medium { + CLASSROOM, ONLINE + } public enum Level { BEGINNER("Beginner", 1), INTERMEDIATE("Intermediate", 2), ADVANCED("Advanced", 3); diff --git a/jackson/src/test/java/com/baeldung/jackson/general/reference/Item.java b/jackson/src/test/java/com/baeldung/jackson/general/reference/Item.java index 08bada3646..5dd66a8ca3 100644 --- a/jackson/src/test/java/com/baeldung/jackson/general/reference/Item.java +++ b/jackson/src/test/java/com/baeldung/jackson/general/reference/Item.java @@ -21,7 +21,8 @@ public class Item { private List authors = new ArrayList<>(); private float price; - public Item(){} + public Item() { + } public Item(String title, Author author) { this.id = UUID.randomUUID(); diff --git a/jackson/src/test/java/com/baeldung/jackson/general/reference/Person.java b/jackson/src/test/java/com/baeldung/jackson/general/reference/Person.java index 5bb20f7aff..95c0b35b8b 100644 --- a/jackson/src/test/java/com/baeldung/jackson/general/reference/Person.java +++ b/jackson/src/test/java/com/baeldung/jackson/general/reference/Person.java @@ -14,7 +14,8 @@ public class Person { private String firstName; private String lastName; - public Person(){} + public Person() { + } public Person(String firstName, String lastName) { this.id = UUID.randomUUID(); diff --git a/jackson/src/test/java/com/baeldung/jackson/general/reference/ReferenceUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/general/reference/ReferenceUnitTest.java index c0aece9636..7a52a69656 100644 --- a/jackson/src/test/java/com/baeldung/jackson/general/reference/ReferenceUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/general/reference/ReferenceUnitTest.java @@ -36,7 +36,7 @@ public class ReferenceUnitTest { /* Without references defined it throws StackOverflowError. Authors excluded. - + { "id": "9c45d9b3-4888-4c24-8b74-65ef35627cd7", "firstName": "Alex", diff --git a/jackson/src/test/java/com/baeldung/jackson/inclusion/jsonautodetect/JsonAutoDetectUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/inclusion/jsonautodetect/JsonAutoDetectUnitTest.java index ef9d6e0e29..a3e29776a9 100644 --- a/jackson/src/test/java/com/baeldung/jackson/inclusion/jsonautodetect/JsonAutoDetectUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/inclusion/jsonautodetect/JsonAutoDetectUnitTest.java @@ -37,7 +37,7 @@ public class JsonAutoDetectUnitTest { }, "internalAudit": 1234567890 } - + Without @JsonAutoDetect { "id": "c94774d9-de8f-4244-85d5-624bd3a4567a", diff --git a/jackson/src/test/java/com/baeldung/jackson/inclusion/jsoninclude/JsonIncludeUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/inclusion/jsoninclude/JsonIncludeUnitTest.java index f85dd66764..ca4c4b751a 100644 --- a/jackson/src/test/java/com/baeldung/jackson/inclusion/jsoninclude/JsonIncludeUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/inclusion/jsoninclude/JsonIncludeUnitTest.java @@ -28,7 +28,6 @@ public class JsonIncludeUnitTest { assertThat(from(result).getString("firstName")).isEqualTo("Alex"); assertThat(result).doesNotContain("lastName"); - /* { "id": "e8bb4802-6e0c-4fa5-9f68-c233272399cd", diff --git a/jackson/src/test/java/com/baeldung/jackson/inheritance/ItemIdRemovedFromUserUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/inheritance/ItemIdRemovedFromUserUnitTest.java index a0ba23fb71..0f312ec37e 100644 --- a/jackson/src/test/java/com/baeldung/jackson/inheritance/ItemIdRemovedFromUserUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/inheritance/ItemIdRemovedFromUserUnitTest.java @@ -12,29 +12,29 @@ import static org.junit.Assert.assertTrue; public class ItemIdRemovedFromUserUnitTest { @Test public void givenRemoveItemJson_whenDeserialize_shouldHaveProperClassType() throws IOException { - //given + // given Event event = new ItemIdRemovedFromUser("1", 12345567L, "item_1", 2L); ObjectMapper objectMapper = new ObjectMapper(); String eventJson = objectMapper.writeValueAsString(event); - //when + // when Event result = new ObjectMapper().readValue(eventJson, Event.class); - //then + // then assertTrue(result instanceof ItemIdRemovedFromUser); assertEquals("item_1", ((ItemIdRemovedFromUser) result).getItemId()); } @Test public void givenAdddItemJson_whenSerialize_shouldIgnoreIdPropertyFromSuperclass() throws IOException { - //given + // given Event event = new ItemIdAddedToUser("1", 12345567L, "item_1", 2L); ObjectMapper objectMapper = new ObjectMapper(); - //when + // when String eventJson = objectMapper.writeValueAsString(event); - //then + // then assertFalse(eventJson.contains("id")); } diff --git a/jackson/src/test/java/com/baeldung/jackson/inheritance/SubTypeHandlingUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/inheritance/SubTypeHandlingUnitTest.java index a8c1e94e9b..b5b81fa4a3 100644 --- a/jackson/src/test/java/com/baeldung/jackson/inheritance/SubTypeHandlingUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/inheritance/SubTypeHandlingUnitTest.java @@ -21,12 +21,12 @@ public class SubTypeHandlingUnitTest { assertEquals("Mercedes-Benz", truck.getMake()); assertEquals("S500", truck.getModel()); } - + @Test - public void givenSubType_whenNotUsingNoArgsConstructors_thenSucceed() throws IOException{ + public void givenSubType_whenNotUsingNoArgsConstructors_thenSucceed() throws IOException { ObjectMapper mapper = new ObjectMapper(); mapper.enableDefaultTyping(); - + SubTypeConstructorStructure.Car car = new SubTypeConstructorStructure.Car("Mercedes-Benz", "S500", 5, 250.0); SubTypeConstructorStructure.Truck truck = new SubTypeConstructorStructure.Truck("Isuzu", "NQR", 7500.0); diff --git a/jackson/src/test/java/com/baeldung/jackson/inheritance/TypeInfoInclusionUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/inheritance/TypeInfoInclusionUnitTest.java index b436eda6e0..02297b9ee8 100644 --- a/jackson/src/test/java/com/baeldung/jackson/inheritance/TypeInfoInclusionUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/inheritance/TypeInfoInclusionUnitTest.java @@ -30,8 +30,10 @@ public class TypeInfoInclusionUnitTest { String jsonDataString = mapper.writeValueAsString(serializedFleet); TypeInfoStructure.Fleet deserializedFleet = mapper.readValue(jsonDataString, TypeInfoStructure.Fleet.class); - assertThat(deserializedFleet.getVehicles().get(0), instanceOf(TypeInfoStructure.Car.class)); - assertThat(deserializedFleet.getVehicles().get(1), instanceOf(TypeInfoStructure.Truck.class)); + assertThat(deserializedFleet.getVehicles() + .get(0), instanceOf(TypeInfoStructure.Car.class)); + assertThat(deserializedFleet.getVehicles() + .get(1), instanceOf(TypeInfoStructure.Truck.class)); } @Test @@ -51,7 +53,9 @@ public class TypeInfoInclusionUnitTest { String jsonDataString = mapper.writeValueAsString(serializedFleet); TypeInfoAnnotatedStructure.Fleet deserializedFleet = mapper.readValue(jsonDataString, TypeInfoAnnotatedStructure.Fleet.class); - assertThat(deserializedFleet.getVehicles().get(0), instanceOf(TypeInfoAnnotatedStructure.Car.class)); - assertThat(deserializedFleet.getVehicles().get(1), instanceOf(TypeInfoAnnotatedStructure.Truck.class)); + assertThat(deserializedFleet.getVehicles() + .get(0), instanceOf(TypeInfoAnnotatedStructure.Car.class)); + assertThat(deserializedFleet.getVehicles() + .get(1), instanceOf(TypeInfoAnnotatedStructure.Truck.class)); } } \ No newline at end of file diff --git a/jackson/src/test/java/com/baeldung/jackson/node/ExampleStructure.java b/jackson/src/test/java/com/baeldung/jackson/node/ExampleStructure.java index 14f9024d0b..a472c7af15 100644 --- a/jackson/src/test/java/com/baeldung/jackson/node/ExampleStructure.java +++ b/jackson/src/test/java/com/baeldung/jackson/node/ExampleStructure.java @@ -10,7 +10,8 @@ public class ExampleStructure { private static ObjectMapper mapper = new ObjectMapper(); static JsonNode getExampleRoot() throws IOException { - InputStream exampleInput = ExampleStructure.class.getClassLoader().getResourceAsStream("node_example.json"); + InputStream exampleInput = ExampleStructure.class.getClassLoader() + .getResourceAsStream("node_example.json"); JsonNode rootNode = mapper.readTree(exampleInput); return rootNode; } diff --git a/jackson/src/test/java/com/baeldung/jackson/node/NodeOperationUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/node/NodeOperationUnitTest.java index 3539f388f9..73328f465e 100644 --- a/jackson/src/test/java/com/baeldung/jackson/node/NodeOperationUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/node/NodeOperationUnitTest.java @@ -28,8 +28,10 @@ public class NodeOperationUnitTest { final JsonNode node = mapper.valueToTree(fromValue); - assertEquals(2016, node.get("id").intValue()); - assertEquals("baeldung.com", node.get("name").textValue()); + assertEquals(2016, node.get("id") + .intValue()); + assertEquals("baeldung.com", node.get("name") + .textValue()); } @Test @@ -72,12 +74,21 @@ public class NodeOperationUnitTest { public void givenANode_whenAddingIntoATree_thenCorrect() throws IOException { final JsonNode rootNode = ExampleStructure.getExampleRoot(); final ObjectNode addedNode = ((ObjectNode) rootNode).putObject("address"); - addedNode.put("city", "Seattle").put("state", "Washington").put("country", "United States"); + addedNode.put("city", "Seattle") + .put("state", "Washington") + .put("country", "United States"); - assertFalse(rootNode.path("address").isMissingNode()); - assertEquals("Seattle", rootNode.path("address").path("city").textValue()); - assertEquals("Washington", rootNode.path("address").path("state").textValue()); - assertEquals("United States", rootNode.path("address").path("country").textValue()); + assertFalse(rootNode.path("address") + .isMissingNode()); + assertEquals("Seattle", rootNode.path("address") + .path("city") + .textValue()); + assertEquals("Washington", rootNode.path("address") + .path("state") + .textValue()); + assertEquals("United States", rootNode.path("address") + .path("country") + .textValue()); } @Test @@ -88,8 +99,12 @@ public class NodeOperationUnitTest { final JsonNode rootNode = ExampleStructure.getExampleRoot(); ((ObjectNode) rootNode).set("name", newNode); - assertFalse(rootNode.path("name").path("nick").isMissingNode()); - assertEquals("cowtowncoder", rootNode.path("name").path("nick").textValue()); + assertFalse(rootNode.path("name") + .path("nick") + .isMissingNode()); + assertEquals("cowtowncoder", rootNode.path("name") + .path("nick") + .textValue()); } @Test @@ -97,7 +112,8 @@ public class NodeOperationUnitTest { final JsonNode rootNode = ExampleStructure.getExampleRoot(); ((ObjectNode) rootNode).remove("company"); - assertTrue(rootNode.path("company").isMissingNode()); + assertTrue(rootNode.path("company") + .isMissingNode()); } } diff --git a/jackson/src/test/java/com/baeldung/jackson/objectmapper/CustomCarDeserializer.java b/jackson/src/test/java/com/baeldung/jackson/objectmapper/CustomCarDeserializer.java index a3d0b377c6..10b22b8365 100644 --- a/jackson/src/test/java/com/baeldung/jackson/objectmapper/CustomCarDeserializer.java +++ b/jackson/src/test/java/com/baeldung/jackson/objectmapper/CustomCarDeserializer.java @@ -25,8 +25,6 @@ public class CustomCarDeserializer extends StdDeserializer { super(vc); } - - @Override public Car deserialize(final JsonParser parser, final DeserializationContext deserializer) throws IOException { final Car car = new Car(); diff --git a/jackson/src/test/java/com/baeldung/jackson/objectmapper/CustomCarSerializer.java b/jackson/src/test/java/com/baeldung/jackson/objectmapper/CustomCarSerializer.java index 37bae829b7..9db09c5081 100644 --- a/jackson/src/test/java/com/baeldung/jackson/objectmapper/CustomCarSerializer.java +++ b/jackson/src/test/java/com/baeldung/jackson/objectmapper/CustomCarSerializer.java @@ -8,8 +8,7 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.ser.std.StdSerializer; -public class CustomCarSerializer extends StdSerializer -{ +public class CustomCarSerializer extends StdSerializer { private static final long serialVersionUID = 1396140685442227917L; @@ -22,8 +21,7 @@ public class CustomCarSerializer extends StdSerializer } @Override - public void serialize(final Car car, final JsonGenerator jsonGenerator, final SerializerProvider serializer) throws IOException, JsonProcessingException - { + public void serialize(final Car car, final JsonGenerator jsonGenerator, final SerializerProvider serializer) throws IOException, JsonProcessingException { jsonGenerator.writeStartObject(); jsonGenerator.writeStringField("model: ", car.getType()); jsonGenerator.writeEndObject(); diff --git a/jackson/src/test/java/com/baeldung/jackson/objectmapper/JavaReadWriteJsonExampleUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/objectmapper/JavaReadWriteJsonExampleUnitTest.java index e6da19f440..2745e4f767 100644 --- a/jackson/src/test/java/com/baeldung/jackson/objectmapper/JavaReadWriteJsonExampleUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/objectmapper/JavaReadWriteJsonExampleUnitTest.java @@ -40,7 +40,8 @@ public class JavaReadWriteJsonExampleUnitTest { final ObjectMapper objectMapper = new ObjectMapper(); final JsonNode jsonNode = objectMapper.readTree(EXAMPLE_JSON); assertNotNull(jsonNode); - assertThat(jsonNode.get("color").asText(), containsString("Black")); + assertThat(jsonNode.get("color") + .asText(), containsString("Black")); } @Test diff --git a/jackson/src/test/java/com/baeldung/jackson/objectmapper/SerializationDeserializationFeatureUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/objectmapper/SerializationDeserializationFeatureUnitTest.java index 4ffec72a61..fcfee98123 100644 --- a/jackson/src/test/java/com/baeldung/jackson/objectmapper/SerializationDeserializationFeatureUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/objectmapper/SerializationDeserializationFeatureUnitTest.java @@ -18,7 +18,7 @@ import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; -public class SerializationDeserializationFeatureUnitTest { +public class SerializationDeserializationFeatureUnitTest { final String EXAMPLE_JSON = "{ \"color\" : \"Black\", \"type\" : \"BMW\" }"; final String JSON_CAR = "{ \"color\" : \"Black\", \"type\" : \"Fiat\", \"year\" : \"1970\" }"; final String JSON_ARRAY = "[{ \"color\" : \"Black\", \"type\" : \"BMW\" }, { \"color\" : \"Red\", \"type\" : \"BMW\" }]"; diff --git a/jackson/src/test/java/com/baeldung/jackson/polymorphism/PolymorphismUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/polymorphism/PolymorphismUnitTest.java index 5d2ba69767..e922cf9976 100644 --- a/jackson/src/test/java/com/baeldung/jackson/polymorphism/PolymorphismUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/polymorphism/PolymorphismUnitTest.java @@ -53,12 +53,14 @@ public class PolymorphismUnitTest { String orderJson = "{\"type\":{\"ordertype\":\"internal\",\"id\":100,\"name\":\"directors\"}}"; // act - Order order = new ObjectMapper().readerFor(Order.class).readValue(orderJson); + Order order = new ObjectMapper().readerFor(Order.class) + .readValue(orderJson); - // assert + // assert assertThat(from(orderJson).getString("type.ordertype")).isEqualTo("internal"); assertThat(((Order.InternalType) order.getType()).name).isEqualTo("directors"); assertThat(((Order.InternalType) order.getType()).id).isEqualTo(100); - assertThat(order.getType().getClass()).isEqualTo(Order.InternalType.class); + assertThat(order.getType() + .getClass()).isEqualTo(Order.InternalType.class); } } \ No newline at end of file diff --git a/jackson/src/test/java/com/baeldung/jackson/sandbox/JacksonPrettyPrintUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/sandbox/JacksonPrettyPrintUnitTest.java index a68af20f15..a75e8ef831 100644 --- a/jackson/src/test/java/com/baeldung/jackson/sandbox/JacksonPrettyPrintUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/sandbox/JacksonPrettyPrintUnitTest.java @@ -33,7 +33,8 @@ public class JacksonPrettyPrintUnitTest { final ObjectMapper mapper = new ObjectMapper(); try { final Object json = mapper.readValue(readFile(fileName, StandardCharsets.UTF_8), Object.class); - System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json)); + System.out.println(mapper.writerWithDefaultPrettyPrinter() + .writeValueAsString(json)); } catch (final IOException e) { e.printStackTrace(); } @@ -42,7 +43,8 @@ public class JacksonPrettyPrintUnitTest { static String readFile(final String path, final Charset encoding) throws IOException { final byte[] encoded = Files.readAllBytes(Paths.get(path)); - return encoding.decode(ByteBuffer.wrap(encoded)).toString(); + return encoding.decode(ByteBuffer.wrap(encoded)) + .toString(); } } diff --git a/jackson/src/test/java/com/baeldung/jackson/sandbox/SandboxUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/sandbox/SandboxUnitTest.java index 33aca2a1ed..6f22e2fa01 100644 --- a/jackson/src/test/java/com/baeldung/jackson/sandbox/SandboxUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/sandbox/SandboxUnitTest.java @@ -17,7 +17,10 @@ public class SandboxUnitTest { testElement.setX(10); testElement.setY("adasd"); final ObjectMapper om = new ObjectMapper(); - om.setVisibility(om.getSerializationConfig().getDefaultVisibilityChecker().withFieldVisibility(JsonAutoDetect.Visibility.ANY).withGetterVisibility(JsonAutoDetect.Visibility.NONE)); + om.setVisibility(om.getSerializationConfig() + .getDefaultVisibilityChecker() + .withFieldVisibility(JsonAutoDetect.Visibility.ANY) + .withGetterVisibility(JsonAutoDetect.Visibility.NONE)); final String serialized = om.writeValueAsString(testElement); System.err.println(serialized); diff --git a/jackson/src/test/java/com/baeldung/jackson/serialization/JacksonMapSerializeUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/serialization/JacksonMapSerializeUnitTest.java index 4935d35791..e67336f6f3 100644 --- a/jackson/src/test/java/com/baeldung/jackson/serialization/JacksonMapSerializeUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/serialization/JacksonMapSerializeUnitTest.java @@ -14,57 +14,53 @@ import com.fasterxml.jackson.databind.ser.std.MapSerializer; public class JacksonMapSerializeUnitTest { - @JsonSerialize(keyUsing = MyPairSerializer.class) - private Map map; + @JsonSerialize(keyUsing = MyPairSerializer.class) + private Map map; - @JsonSerialize(keyUsing = MapSerializer.class) - private Map cmap; + @JsonSerialize(keyUsing = MapSerializer.class) + private Map cmap; - @JsonSerialize(keyUsing = MyPairSerializer.class) - private MyPair mapKey; + @JsonSerialize(keyUsing = MyPairSerializer.class) + private MyPair mapKey; - @JsonSerialize(keyUsing = MyPairSerializer.class) - private MyPair mapValue; + @JsonSerialize(keyUsing = MyPairSerializer.class) + private MyPair mapValue; - final ObjectMapper mapper = new ObjectMapper(); + final ObjectMapper mapper = new ObjectMapper(); - @Test - public void whenSimpleMapSerialize_thenCorrect() - throws JsonProcessingException { + @Test + public void whenSimpleMapSerialize_thenCorrect() throws JsonProcessingException { - Map map = new HashMap<>(); - map.put("key", "value"); + Map map = new HashMap<>(); + map.put("key", "value"); - final String jsonResult = mapper.writeValueAsString(map); + final String jsonResult = mapper.writeValueAsString(map); - Assert.assertEquals("{\"key\":\"value\"}", jsonResult); - } + Assert.assertEquals("{\"key\":\"value\"}", jsonResult); + } - @Test - public void whenCustomObjectStringMapSerialize_thenCorrect() - throws JsonProcessingException { + @Test + public void whenCustomObjectStringMapSerialize_thenCorrect() throws JsonProcessingException { - map = new HashMap<>(); - MyPair key = new MyPair("Abbott", "Costello"); - map.put(key, "Comedy"); + map = new HashMap<>(); + MyPair key = new MyPair("Abbott", "Costello"); + map.put(key, "Comedy"); - final String jsonResult = mapper.writeValueAsString(map); + final String jsonResult = mapper.writeValueAsString(map); - Assert.assertEquals("{\"Abbott and Costello\":\"Comedy\"}", jsonResult); - } + Assert.assertEquals("{\"Abbott and Costello\":\"Comedy\"}", jsonResult); + } - @Test - public void whenCustomObjectObjectMapSerialize_thenCorrect() - throws JsonProcessingException { + @Test + public void whenCustomObjectObjectMapSerialize_thenCorrect() throws JsonProcessingException { - cmap = new HashMap<>(); - mapKey = new MyPair("Abbott", "Costello"); - mapValue = new MyPair("Comedy", "1940's"); - cmap.put(mapKey, mapValue); + cmap = new HashMap<>(); + mapKey = new MyPair("Abbott", "Costello"); + mapValue = new MyPair("Comedy", "1940's"); + cmap.put(mapKey, mapValue); - final String jsonResult = mapper.writeValueAsString(cmap); + final String jsonResult = mapper.writeValueAsString(cmap); - Assert.assertEquals("{\"Abbott and Costello\":\"Comedy and 1940's\"}", - jsonResult); - } + Assert.assertEquals("{\"Abbott and Costello\":\"Comedy and 1940's\"}", jsonResult); + } } diff --git a/jackson/src/test/java/com/baeldung/jackson/serialization/JacksonSerializeUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/serialization/JacksonSerializeUnitTest.java index fa6364ff92..a003c5b526 100644 --- a/jackson/src/test/java/com/baeldung/jackson/serialization/JacksonSerializeUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/serialization/JacksonSerializeUnitTest.java @@ -48,10 +48,13 @@ public class JacksonSerializeUnitTest { module.addSerializer(new ActorJacksonSerializer(ActorJackson.class)); final ObjectMapper mapper = new ObjectMapper(); - final String jsonResult = mapper.registerModule(module).writer(new DefaultPrettyPrinter()).writeValueAsString(movieWithNullValue); + final String jsonResult = mapper.registerModule(module) + .writer(new DefaultPrettyPrinter()) + .writeValueAsString(movieWithNullValue); final Object json = mapper.readValue("{\"actors\":[{\"imdbId\":\"nm2199632\",\"dateOfBirth\":\"21-09-1982\",\"N° Film: \":3,\"filmography\":\"Apocalypto-Beatdown-Wind Walkers\"}],\"imdbID\":null}", Object.class); - final String expectedOutput = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT).writeValueAsString(json); + final String expectedOutput = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT) + .writeValueAsString(json); Assert.assertEquals(jsonResult, expectedOutput); } diff --git a/jackson/src/test/java/com/baeldung/jackson/serialization/jsonrawvalue/JsonRawValueUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/serialization/jsonrawvalue/JsonRawValueUnitTest.java index 0671441d9a..f0f0913aee 100644 --- a/jackson/src/test/java/com/baeldung/jackson/serialization/jsonrawvalue/JsonRawValueUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/serialization/jsonrawvalue/JsonRawValueUnitTest.java @@ -28,7 +28,6 @@ public class JsonRawValueUnitTest { // assert assertThat(result.contains(customerConfig)); - /* { "firstName": "Alex", diff --git a/jackson/src/test/java/com/baeldung/jackson/streaming/JacksonStreamingAPIUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/streaming/JacksonStreamingAPIUnitTest.java index 2f8cf52afb..ff22682f37 100644 --- a/jackson/src/test/java/com/baeldung/jackson/streaming/JacksonStreamingAPIUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/streaming/JacksonStreamingAPIUnitTest.java @@ -1,6 +1,5 @@ package com.baeldung.jackson.streaming; - import com.fasterxml.jackson.core.*; import org.junit.Test; @@ -18,12 +17,12 @@ public class JacksonStreamingAPIUnitTest { @Test public void givenJsonGenerator_whenAppendJsonToIt_thenGenerateJson() throws IOException { - //given + // given ByteArrayOutputStream stream = new ByteArrayOutputStream(); JsonFactory jfactory = new JsonFactory(); JsonGenerator jGenerator = jfactory.createGenerator(stream, JsonEncoding.UTF8); - //when + // when jGenerator.writeStartObject(); jGenerator.writeStringField("name", "Tom"); jGenerator.writeNumberField("age", 25); @@ -35,14 +34,14 @@ public class JacksonStreamingAPIUnitTest { jGenerator.writeEndObject(); jGenerator.close(); - //then + // then String json = new String(stream.toByteArray(), "UTF-8"); assertEquals(json, "{\"name\":\"Tom\",\"age\":25,\"address\":[\"Poland\",\"5th avenue\"]}"); } @Test public void givenJson_whenReadItUsingStreamAPI_thenShouldCreateProperJsonObject() throws IOException { - //given + // given String json = "{\"name\":\"Tom\",\"age\":25,\"address\":[\"Poland\",\"5th avenue\"]}"; JsonFactory jfactory = new JsonFactory(); JsonParser jParser = jfactory.createParser(json); @@ -51,7 +50,7 @@ public class JacksonStreamingAPIUnitTest { Integer parsedAge = null; List addresses = new LinkedList<>(); - //when + // when while (jParser.nextToken() != JsonToken.END_OBJECT) { String fieldname = jParser.getCurrentName(); @@ -78,7 +77,7 @@ public class JacksonStreamingAPIUnitTest { } jParser.close(); - //then + // then assertEquals(parsedName, "Tom"); assertEquals(parsedAge, (Integer) 25); assertEquals(addresses, Arrays.asList("Poland", "5th avenue")); @@ -87,7 +86,7 @@ public class JacksonStreamingAPIUnitTest { @Test public void givenJson_whenWantToExtractPartOfIt_thenShouldExtractOnlyNeededFieldWithoutGoingThroughWholeJSON() throws IOException { - //given + // given String json = "{\"name\":\"Tom\",\"age\":25,\"address\":[\"Poland\",\"5th avenue\"]}"; JsonFactory jfactory = new JsonFactory(); JsonParser jParser = jfactory.createParser(json); @@ -96,7 +95,7 @@ public class JacksonStreamingAPIUnitTest { Integer parsedAge = null; List addresses = new LinkedList<>(); - //when + // when while (jParser.nextToken() != JsonToken.END_OBJECT) { String fieldname = jParser.getCurrentName(); @@ -110,7 +109,7 @@ public class JacksonStreamingAPIUnitTest { } jParser.close(); - //then + // then assertNull(parsedName); assertEquals(parsedAge, (Integer) 25); assertTrue(addresses.isEmpty()); diff --git a/jackson/src/test/java/com/baeldung/jackson/test/JacksonAnnotationUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/test/JacksonAnnotationUnitTest.java index e544ab670a..935777bad1 100644 --- a/jackson/src/test/java/com/baeldung/jackson/test/JacksonAnnotationUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/test/JacksonAnnotationUnitTest.java @@ -124,7 +124,8 @@ public class JacksonAnnotationUnitTest { public void whenDeserializingUsingJsonCreator_thenCorrect() throws IOException { final String json = "{\"id\":1,\"theName\":\"My bean\"}"; - final BeanWithCreator bean = new ObjectMapper().readerFor(BeanWithCreator.class).readValue(json); + final BeanWithCreator bean = new ObjectMapper().readerFor(BeanWithCreator.class) + .readValue(json); assertEquals("My bean", bean.name); } @@ -133,7 +134,9 @@ public class JacksonAnnotationUnitTest { final String json = "{\"name\":\"My bean\"}"; final InjectableValues inject = new InjectableValues.Std().addValue(int.class, 1); - final BeanWithInject bean = new ObjectMapper().reader(inject).forType(BeanWithInject.class).readValue(json); + final BeanWithInject bean = new ObjectMapper().reader(inject) + .forType(BeanWithInject.class) + .readValue(json); assertEquals("My bean", bean.name); assertEquals(1, bean.id); } @@ -142,16 +145,19 @@ public class JacksonAnnotationUnitTest { public void whenDeserializingUsingJsonAnySetter_thenCorrect() throws IOException { final String json = "{\"name\":\"My bean\",\"attr2\":\"val2\",\"attr1\":\"val1\"}"; - final ExtendableBean bean = new ObjectMapper().readerFor(ExtendableBean.class).readValue(json); + final ExtendableBean bean = new ObjectMapper().readerFor(ExtendableBean.class) + .readValue(json); assertEquals("My bean", bean.name); - assertEquals("val2", bean.getProperties().get("attr2")); + assertEquals("val2", bean.getProperties() + .get("attr2")); } @Test public void whenDeserializingUsingJsonSetter_thenCorrect() throws IOException { final String json = "{\"id\":1,\"name\":\"My bean\"}"; - final BeanWithGetter bean = new ObjectMapper().readerFor(BeanWithGetter.class).readValue(json); + final BeanWithGetter bean = new ObjectMapper().readerFor(BeanWithGetter.class) + .readValue(json); assertEquals("My bean", bean.getTheName()); } @@ -161,7 +167,8 @@ public class JacksonAnnotationUnitTest { final SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss"); - final EventWithSerializer event = new ObjectMapper().readerFor(EventWithSerializer.class).readValue(json); + final EventWithSerializer event = new ObjectMapper().readerFor(EventWithSerializer.class) + .readValue(json); assertEquals("20-12-2014 02:30:00", df.format(event.eventDate)); } @@ -232,7 +239,8 @@ public class JacksonAnnotationUnitTest { public void whenDeserializingPolymorphic_thenCorrect() throws IOException { final String json = "{\"animal\":{\"name\":\"lacy\",\"type\":\"cat\"}}"; - final Zoo zoo = new ObjectMapper().readerFor(Zoo.class).readValue(json); + final Zoo zoo = new ObjectMapper().readerFor(Zoo.class) + .readValue(json); assertEquals("lacy", zoo.animal.name); assertEquals(Zoo.Cat.class, zoo.animal.getClass()); @@ -247,7 +255,8 @@ public class JacksonAnnotationUnitTest { assertThat(result, containsString("My bean")); assertThat(result, containsString("1")); - final BeanWithGetter resultBean = new ObjectMapper().readerFor(BeanWithGetter.class).readValue(result); + final BeanWithGetter resultBean = new ObjectMapper().readerFor(BeanWithGetter.class) + .readValue(result); assertEquals("My bean", resultBean.getTheName()); } @@ -278,7 +287,8 @@ public class JacksonAnnotationUnitTest { public void whenSerializingUsingJsonView_thenCorrect() throws JsonProcessingException, JsonProcessingException { final Item item = new Item(2, "book", "John"); - final String result = new ObjectMapper().writerWithView(Views.Public.class).writeValueAsString(item); + final String result = new ObjectMapper().writerWithView(Views.Public.class) + .writeValueAsString(item); assertThat(result, containsString("book")); assertThat(result, containsString("2")); @@ -317,7 +327,8 @@ public class JacksonAnnotationUnitTest { final FilterProvider filters = new SimpleFilterProvider().addFilter("myFilter", SimpleBeanPropertyFilter.filterOutAllExcept("name")); - final String result = new ObjectMapper().writer(filters).writeValueAsString(bean); + final String result = new ObjectMapper().writer(filters) + .writeValueAsString(bean); assertThat(result, containsString("My bean")); assertThat(result, not(containsString("id"))); diff --git a/jackson/src/test/java/com/baeldung/jackson/test/JacksonBidirectionRelationUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/test/JacksonBidirectionRelationUnitTest.java index 523b42a96c..e55ca55ac9 100644 --- a/jackson/src/test/java/com/baeldung/jackson/test/JacksonBidirectionRelationUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/test/JacksonBidirectionRelationUnitTest.java @@ -93,7 +93,8 @@ public class JacksonBidirectionRelationUnitTest { public void givenBidirectionRelation_whenDeserializingUsingIdentity_thenCorrect() throws JsonProcessingException, IOException { final String json = "{\"id\":2,\"itemName\":\"book\",\"owner\":{\"id\":1,\"name\":\"John\",\"userItems\":[2]}}"; - final ItemWithIdentity item = new ObjectMapper().readerFor(ItemWithIdentity.class).readValue(json); + final ItemWithIdentity item = new ObjectMapper().readerFor(ItemWithIdentity.class) + .readValue(json); assertEquals(2, item.id); assertEquals("book", item.itemName); @@ -104,7 +105,8 @@ public class JacksonBidirectionRelationUnitTest { public void givenBidirectionRelation_whenUsingCustomDeserializer_thenCorrect() throws JsonProcessingException, IOException { final String json = "{\"id\":2,\"itemName\":\"book\",\"owner\":{\"id\":1,\"name\":\"John\",\"userItems\":[2]}}"; - final ItemWithSerializer item = new ObjectMapper().readerFor(ItemWithSerializer.class).readValue(json); + final ItemWithSerializer item = new ObjectMapper().readerFor(ItemWithSerializer.class) + .readValue(json); assertEquals(2, item.id); assertEquals("book", item.itemName); assertEquals("John", item.owner.name); @@ -116,7 +118,8 @@ public class JacksonBidirectionRelationUnitTest { final ItemWithView item = new ItemWithView(2, "book", user); user.addItem(item); - final String result = new ObjectMapper().writerWithView(Views.Public.class).writeValueAsString(item); + final String result = new ObjectMapper().writerWithView(Views.Public.class) + .writeValueAsString(item); assertThat(result, containsString("book")); assertThat(result, containsString("John")); @@ -129,7 +132,8 @@ public class JacksonBidirectionRelationUnitTest { final ItemWithView item = new ItemWithView(2, "book", user); user.addItem(item); - new ObjectMapper().writerWithView(Views.Internal.class).writeValueAsString(item); + new ObjectMapper().writerWithView(Views.Internal.class) + .writeValueAsString(item); } } \ No newline at end of file diff --git a/jackson/src/test/java/com/baeldung/jackson/test/JacksonCollectionDeserializationUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/test/JacksonCollectionDeserializationUnitTest.java index cd166386e6..0de3a1de82 100644 --- a/jackson/src/test/java/com/baeldung/jackson/test/JacksonCollectionDeserializationUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/test/JacksonCollectionDeserializationUnitTest.java @@ -66,7 +66,8 @@ public class JacksonCollectionDeserializationUnitTest { final String jsonArray = mapper.writeValueAsString(listOfDtos); // [{"stringValue":"a","intValue":1,"booleanValue":true},{"stringValue":"bc","intValue":3,"booleanValue":false}] - final CollectionType javaType = mapper.getTypeFactory().constructCollectionType(List.class, MyDto.class); + final CollectionType javaType = mapper.getTypeFactory() + .constructCollectionType(List.class, MyDto.class); final List asList = mapper.readValue(jsonArray, javaType); assertThat(asList.get(0), instanceOf(MyDto.class)); } diff --git a/jackson/src/test/java/com/baeldung/jackson/test/JacksonDateUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/test/JacksonDateUnitTest.java index f713494ac8..390030d0d4 100644 --- a/jackson/src/test/java/com/baeldung/jackson/test/JacksonDateUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/test/JacksonDateUnitTest.java @@ -130,7 +130,8 @@ public class JacksonDateUnitTest { final ObjectMapper mapper = new ObjectMapper(); mapper.setDateFormat(df); - final Event event = mapper.readerFor(Event.class).readValue(json); + final Event event = mapper.readerFor(Event.class) + .readValue(json); assertEquals("20-12-2014 02:30:00", df.format(event.eventDate)); } @@ -141,7 +142,8 @@ public class JacksonDateUnitTest { final SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss"); final ObjectMapper mapper = new ObjectMapper(); - final EventWithSerializer event = mapper.readerFor(EventWithSerializer.class).readValue(json); + final EventWithSerializer event = mapper.readerFor(EventWithSerializer.class) + .readValue(json); assertEquals("20-12-2014 02:30:00", df.format(event.eventDate)); } diff --git a/jackson/src/test/java/com/baeldung/jackson/test/JacksonExceptionsUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/test/JacksonExceptionsUnitTest.java index 4549a752eb..cd2c2925d6 100644 --- a/jackson/src/test/java/com/baeldung/jackson/test/JacksonExceptionsUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/test/JacksonExceptionsUnitTest.java @@ -34,7 +34,9 @@ public class JacksonExceptionsUnitTest { final String json = "{\"animal\":{\"name\":\"lacy\"}}"; final ObjectMapper mapper = new ObjectMapper(); - mapper.reader().forType(Zoo.class).readValue(json); + mapper.reader() + .forType(Zoo.class) + .readValue(json); } @Test @@ -42,7 +44,9 @@ public class JacksonExceptionsUnitTest { final String json = "{\"animal\":{\"name\":\"lacy\"}}"; final ObjectMapper mapper = new ObjectMapper(); - mapper.reader().forType(ZooConfigured.class).readValue(json); + mapper.reader() + .forType(ZooConfigured.class) + .readValue(json); } // JsonMappingException: No serializer found for class @@ -51,7 +55,8 @@ public class JacksonExceptionsUnitTest { final UserWithPrivateFields user = new UserWithPrivateFields(1, "John"); final ObjectMapper mapper = new ObjectMapper(); - mapper.writer().writeValueAsString(user); + mapper.writer() + .writeValueAsString(user); } @Test @@ -61,7 +66,8 @@ public class JacksonExceptionsUnitTest { final ObjectMapper mapper = new ObjectMapper(); mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY); - final String result = mapper.writer().writeValueAsString(user); + final String result = mapper.writer() + .writeValueAsString(user); assertThat(result, containsString("John")); } @@ -71,7 +77,9 @@ public class JacksonExceptionsUnitTest { final String json = "{\"id\":1,\"name\":\"John\"}"; final ObjectMapper mapper = new ObjectMapper(); - mapper.reader().forType(User.class).readValue(json); + mapper.reader() + .forType(User.class) + .readValue(json); } @Test @@ -79,7 +87,9 @@ public class JacksonExceptionsUnitTest { final String json = "{\"id\":1,\"name\":\"John\"}"; final ObjectMapper mapper = new ObjectMapper(); - final com.baeldung.jackson.dtos.User user = mapper.reader().forType(com.baeldung.jackson.dtos.User.class).readValue(json); + final com.baeldung.jackson.dtos.User user = mapper.reader() + .forType(com.baeldung.jackson.dtos.User.class) + .readValue(json); assertEquals("John", user.name); } @@ -91,7 +101,9 @@ public class JacksonExceptionsUnitTest { final ObjectMapper mapper = new ObjectMapper(); mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE); - mapper.reader().forType(com.baeldung.jackson.dtos.User.class).readValue(json); + mapper.reader() + .forType(com.baeldung.jackson.dtos.User.class) + .readValue(json); } @Test @@ -101,7 +113,9 @@ public class JacksonExceptionsUnitTest { final ObjectMapper mapper = new ObjectMapper(); mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE); - final UserWithRoot user = mapper.reader().forType(UserWithRoot.class).readValue(json); + final UserWithRoot user = mapper.reader() + .forType(UserWithRoot.class) + .readValue(json); assertEquals("John", user.name); } @@ -111,7 +125,9 @@ public class JacksonExceptionsUnitTest { final String json = "[{\"id\":1,\"name\":\"John\"},{\"id\":2,\"name\":\"Adam\"}]"; final ObjectMapper mapper = new ObjectMapper(); - mapper.reader().forType(com.baeldung.jackson.dtos.User.class).readValue(json); + mapper.reader() + .forType(com.baeldung.jackson.dtos.User.class) + .readValue(json); } @Test @@ -119,8 +135,10 @@ public class JacksonExceptionsUnitTest { final String json = "[{\"id\":1,\"name\":\"John\"},{\"id\":2,\"name\":\"Adam\"}]"; final ObjectMapper mapper = new ObjectMapper(); - final List users = mapper.reader().forType(new TypeReference>() { - }).readValue(json); + final List users = mapper.reader() + .forType(new TypeReference>() { + }) + .readValue(json); assertEquals(2, users.size()); } @@ -131,7 +149,9 @@ public class JacksonExceptionsUnitTest { final String json = "{\"id\":1,\"name\":\"John\", \"checked\":true}"; final ObjectMapper mapper = new ObjectMapper(); - mapper.reader().forType(com.baeldung.jackson.dtos.User.class).readValue(json); + mapper.reader() + .forType(com.baeldung.jackson.dtos.User.class) + .readValue(json); } @Test @@ -141,7 +161,9 @@ public class JacksonExceptionsUnitTest { final ObjectMapper mapper = new ObjectMapper(); mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); - final com.baeldung.jackson.dtos.User user = mapper.reader().forType(com.baeldung.jackson.dtos.User.class).readValue(json); + final com.baeldung.jackson.dtos.User user = mapper.reader() + .forType(com.baeldung.jackson.dtos.User.class) + .readValue(json); assertEquals("John", user.name); } @@ -151,7 +173,9 @@ public class JacksonExceptionsUnitTest { final String json = "{'id':1,'name':'John'}"; final ObjectMapper mapper = new ObjectMapper(); - mapper.reader().forType(com.baeldung.jackson.dtos.User.class).readValue(json); + mapper.reader() + .forType(com.baeldung.jackson.dtos.User.class) + .readValue(json); } @Test @@ -162,7 +186,9 @@ public class JacksonExceptionsUnitTest { factory.enable(JsonParser.Feature.ALLOW_SINGLE_QUOTES); final ObjectMapper mapper = new ObjectMapper(factory); - final com.baeldung.jackson.dtos.User user = mapper.reader().forType(com.baeldung.jackson.dtos.User.class).readValue(json); + final com.baeldung.jackson.dtos.User user = mapper.reader() + .forType(com.baeldung.jackson.dtos.User.class) + .readValue(json); assertEquals("John", user.name); } diff --git a/jackson/src/test/java/com/baeldung/jackson/test/JacksonJsonViewUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/test/JacksonJsonViewUnitTest.java index dd2690876c..7930195ab0 100644 --- a/jackson/src/test/java/com/baeldung/jackson/test/JacksonJsonViewUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/test/JacksonJsonViewUnitTest.java @@ -28,7 +28,8 @@ public class JacksonJsonViewUnitTest { final ObjectMapper mapper = new ObjectMapper(); mapper.disable(MapperFeature.DEFAULT_VIEW_INCLUSION); - final String result = mapper.writerWithView(Views.Public.class).writeValueAsString(user); + final String result = mapper.writerWithView(Views.Public.class) + .writeValueAsString(user); assertThat(result, containsString("John")); assertThat(result, not(containsString("1"))); @@ -39,7 +40,8 @@ public class JacksonJsonViewUnitTest { final Item item = new Item(2, "book", "John"); final ObjectMapper mapper = new ObjectMapper(); - final String result = mapper.writerWithView(Views.Public.class).writeValueAsString(item); + final String result = mapper.writerWithView(Views.Public.class) + .writeValueAsString(item); assertThat(result, containsString("book")); assertThat(result, containsString("2")); @@ -52,7 +54,8 @@ public class JacksonJsonViewUnitTest { final Item item = new Item(2, "book", "John"); final ObjectMapper mapper = new ObjectMapper(); - final String result = mapper.writerWithView(Views.Internal.class).writeValueAsString(item); + final String result = mapper.writerWithView(Views.Internal.class) + .writeValueAsString(item); assertThat(result, containsString("book")); assertThat(result, containsString("2")); @@ -66,7 +69,9 @@ public class JacksonJsonViewUnitTest { final ObjectMapper mapper = new ObjectMapper(); - final User user = mapper.readerWithView(Views.Public.class).forType(User.class).readValue(json); + final User user = mapper.readerWithView(Views.Public.class) + .forType(User.class) + .readValue(json); assertEquals(1, user.getId()); assertEquals("John", user.getName()); } @@ -79,7 +84,8 @@ public class JacksonJsonViewUnitTest { final ObjectMapper mapper = new ObjectMapper(); mapper.setSerializerFactory(serializerFactory); - final String result = mapper.writerWithView(Views.Public.class).writeValueAsString(user); + final String result = mapper.writerWithView(Views.Public.class) + .writeValueAsString(user); assertThat(result, containsString("JOHN")); assertThat(result, containsString("1")); } diff --git a/jackson/src/test/java/com/baeldung/jackson/test/JacksonSerializationIgnoreUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/test/JacksonSerializationIgnoreUnitTest.java index bc0e24cdfa..4230420132 100644 --- a/jackson/src/test/java/com/baeldung/jackson/test/JacksonSerializationIgnoreUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/test/JacksonSerializationIgnoreUnitTest.java @@ -109,7 +109,8 @@ public class JacksonSerializationIgnoreUnitTest { final MyDtoWithFilter dtoObject = new MyDtoWithFilter(); dtoObject.setIntValue(12); - final String dtoAsString = mapper.writer(filters).writeValueAsString(dtoObject); + final String dtoAsString = mapper.writer(filters) + .writeValueAsString(dtoObject); assertThat(dtoAsString, not(containsString("intValue"))); assertThat(dtoAsString, containsString("booleanValue")); @@ -123,7 +124,8 @@ public class JacksonSerializationIgnoreUnitTest { @Override public final void serializeAsField(final Object pojo, final JsonGenerator jgen, final SerializerProvider provider, final PropertyWriter writer) throws Exception { if (include(writer)) { - if (!writer.getName().equals("intValue")) { + if (!writer.getName() + .equals("intValue")) { writer.serializeAsField(pojo, jgen, provider); return; } @@ -153,7 +155,8 @@ public class JacksonSerializationIgnoreUnitTest { dtoObject.setIntValue(-1); final ObjectMapper mapper = new ObjectMapper(); - final String dtoAsString = mapper.writer(filters).writeValueAsString(dtoObject); + final String dtoAsString = mapper.writer(filters) + .writeValueAsString(dtoObject); assertThat(dtoAsString, not(containsString("intValue"))); assertThat(dtoAsString, containsString("booleanValue")); @@ -229,7 +232,8 @@ public class JacksonSerializationIgnoreUnitTest { @Test public final void givenAllowingMapObjectWithNullKey_whenWriting_thenCorrect() throws JsonProcessingException { final ObjectMapper mapper = new ObjectMapper(); - mapper.getSerializerProvider().setNullKeySerializer(new MyDtoNullKeySerializer()); + mapper.getSerializerProvider() + .setNullKeySerializer(new MyDtoNullKeySerializer()); final MyDto dtoObject1 = new MyDto(); dtoObject1.setStringValue("dtoObjectString1"); @@ -251,7 +255,8 @@ public class JacksonSerializationIgnoreUnitTest { @Test public final void givenAllowingMapObjectOneNullKey_whenWritingMapObjectWithTwoNullKeys_thenOverride() throws JsonProcessingException { final ObjectMapper mapper = new ObjectMapper(); - mapper.getSerializerProvider().setNullKeySerializer(new MyDtoNullKeySerializer()); + mapper.getSerializerProvider() + .setNullKeySerializer(new MyDtoNullKeySerializer()); final MyDto dtoObject1 = new MyDto(); dtoObject1.setStringValue("dtoObject1String"); diff --git a/jackson/src/test/java/com/baeldung/jackson/try1/RestLoaderRequestDeserializer.java b/jackson/src/test/java/com/baeldung/jackson/try1/RestLoaderRequestDeserializer.java index 529c05ddcc..52bb65033f 100644 --- a/jackson/src/test/java/com/baeldung/jackson/try1/RestLoaderRequestDeserializer.java +++ b/jackson/src/test/java/com/baeldung/jackson/try1/RestLoaderRequestDeserializer.java @@ -25,8 +25,10 @@ public class RestLoaderRequestDeserializer extends StdDeserializer clazz = Class.forName(className); diff --git a/jackson/src/test/java/com/baeldung/jackson/xml/XMLSerializeDeserializeUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/xml/XMLSerializeDeserializeUnitTest.java index b5e3449c68..adb0fe0413 100644 --- a/jackson/src/test/java/com/baeldung/jackson/xml/XMLSerializeDeserializeUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/xml/XMLSerializeDeserializeUnitTest.java @@ -35,8 +35,7 @@ public class XMLSerializeDeserializeUnitTest { @Test public void whenJavaGotFromXmlStr_thenCorrect() throws IOException { XmlMapper xmlMapper = new XmlMapper(); - SimpleBean value = xmlMapper.readValue( - "12", SimpleBean.class); + SimpleBean value = xmlMapper.readValue("12", SimpleBean.class); assertTrue(value.getX() == 1 && value.getY() == 2); } diff --git a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootAnnotatedApp.java b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootAnnotatedApp.java index d54fa5a7c1..774eb69889 100644 --- a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootAnnotatedApp.java +++ b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootAnnotatedApp.java @@ -16,7 +16,7 @@ import com.baeldung.autoconfiguration.MySQLAutoconfiguration; * @ServletComponentScan(basePackageClasses = {AttrListener.class, HelloFilter.class, HelloServlet.class, EchoServlet.class}) * */ -@SpringBootApplication(exclude=MySQLAutoconfiguration.class) +@SpringBootApplication(exclude = MySQLAutoconfiguration.class) @ServletComponentScan("com.baeldung.annotation.servletcomponentscan.components") public class SpringBootAnnotatedApp { diff --git a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootPlainApp.java b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootPlainApp.java index 44030f440b..580498e831 100644 --- a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootPlainApp.java +++ b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootPlainApp.java @@ -5,7 +5,7 @@ import org.springframework.context.annotation.ComponentScan; import com.baeldung.autoconfiguration.MySQLAutoconfiguration; -@SpringBootApplication(exclude=MySQLAutoconfiguration.class) +@SpringBootApplication(exclude = MySQLAutoconfiguration.class) @ComponentScan(basePackages = "com.baeldung.annotation.servletcomponentscan.components") public class SpringBootPlainApp { diff --git a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/AttrListener.java b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/AttrListener.java index bad39c52c4..95b4a1a191 100644 --- a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/AttrListener.java +++ b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/AttrListener.java @@ -9,9 +9,8 @@ public class AttrListener implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent servletContextEvent) { - servletContextEvent - .getServletContext() - .setAttribute("servlet-context-attr", "test"); + servletContextEvent.getServletContext() + .setAttribute("servlet-context-attr", "test"); System.out.println("context init"); } diff --git a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/EchoServlet.java b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/EchoServlet.java index 3419cd0eaf..a2995d1532 100644 --- a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/EchoServlet.java +++ b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/EchoServlet.java @@ -16,9 +16,8 @@ public class EchoServlet extends HttpServlet { @Override public void doPost(HttpServletRequest request, HttpServletResponse response) { try { - Path path = File - .createTempFile("echo", "tmp") - .toPath(); + Path path = File.createTempFile("echo", "tmp") + .toPath(); Files.copy(request.getInputStream(), path, StandardCopyOption.REPLACE_EXISTING); Files.copy(path, response.getOutputStream()); Files.delete(path); diff --git a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloFilter.java b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloFilter.java index dc2368c5b2..650dae9806 100644 --- a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloFilter.java +++ b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloFilter.java @@ -18,9 +18,8 @@ public class HelloFilter implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { - servletResponse - .getOutputStream() - .print(filterConfig.getInitParameter("msg")); + servletResponse.getOutputStream() + .print(filterConfig.getInitParameter("msg")); filterChain.doFilter(servletRequest, servletResponse); } diff --git a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloServlet.java b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloServlet.java index aeae7aecc9..3c27b8416f 100644 --- a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloServlet.java +++ b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloServlet.java @@ -8,22 +8,22 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; -@WebServlet(urlPatterns = "/hello", initParams = { @WebInitParam(name = "msg", value = "hello")}) +@WebServlet(urlPatterns = "/hello", initParams = { @WebInitParam(name = "msg", value = "hello") }) public class HelloServlet extends HttpServlet { private ServletConfig servletConfig; @Override - public void init(ServletConfig servletConfig){ + public void init(ServletConfig servletConfig) { this.servletConfig = servletConfig; } @Override public void doGet(HttpServletRequest request, HttpServletResponse response) { try { - response - .getOutputStream() - .write(servletConfig.getInitParameter("msg").getBytes()); + response.getOutputStream() + .write(servletConfig.getInitParameter("msg") + .getBytes()); } catch (IOException e) { e.printStackTrace(); } diff --git a/spring-boot/src/main/java/com/baeldung/autoconfiguration/MySQLAutoconfiguration.java b/spring-boot/src/main/java/com/baeldung/autoconfiguration/MySQLAutoconfiguration.java index 09f387902d..6dd127a8c3 100644 --- a/spring-boot/src/main/java/com/baeldung/autoconfiguration/MySQLAutoconfiguration.java +++ b/spring-boot/src/main/java/com/baeldung/autoconfiguration/MySQLAutoconfiguration.java @@ -92,21 +92,19 @@ public class MySQLAutoconfiguration { static class HibernateCondition extends SpringBootCondition { - private static final String[] CLASS_NAMES = { - "org.hibernate.ejb.HibernateEntityManager", - "org.hibernate.jpa.HibernateEntityManager" }; + private static final String[] CLASS_NAMES = { "org.hibernate.ejb.HibernateEntityManager", "org.hibernate.jpa.HibernateEntityManager" }; @Override public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { ConditionMessage.Builder message = ConditionMessage.forCondition("Hibernate"); return Arrays.stream(CLASS_NAMES) - .filter(className -> ClassUtils.isPresent(className, context.getClassLoader())) - .map(className -> ConditionOutcome - .match(message.found("class").items(Style.NORMAL, className))) - .findAny() - .orElseGet(() -> ConditionOutcome - .noMatch(message.didNotFind("class", "classes").items(Style.NORMAL, Arrays.asList(CLASS_NAMES)))); + .filter(className -> ClassUtils.isPresent(className, context.getClassLoader())) + .map(className -> ConditionOutcome.match(message.found("class") + .items(Style.NORMAL, className))) + .findAny() + .orElseGet(() -> ConditionOutcome.noMatch(message.didNotFind("class", "classes") + .items(Style.NORMAL, Arrays.asList(CLASS_NAMES)))); } } diff --git a/spring-boot/src/main/java/com/baeldung/autoconfiguration/example/MyUserRepository.java b/spring-boot/src/main/java/com/baeldung/autoconfiguration/example/MyUserRepository.java index fa411bc0b8..3d07e515b1 100644 --- a/spring-boot/src/main/java/com/baeldung/autoconfiguration/example/MyUserRepository.java +++ b/spring-boot/src/main/java/com/baeldung/autoconfiguration/example/MyUserRepository.java @@ -2,6 +2,6 @@ package com.baeldung.autoconfiguration.example; import org.springframework.data.jpa.repository.JpaRepository; -public interface MyUserRepository extends JpaRepository{ - +public interface MyUserRepository extends JpaRepository { + } diff --git a/spring-boot/src/main/java/com/baeldung/displayallbeans/Application.java b/spring-boot/src/main/java/com/baeldung/displayallbeans/Application.java index cd015e6554..6cc3f72cf6 100644 --- a/spring-boot/src/main/java/com/baeldung/displayallbeans/Application.java +++ b/spring-boot/src/main/java/com/baeldung/displayallbeans/Application.java @@ -10,13 +10,13 @@ public class Application { public static void main(String[] args) { applicationContext = SpringApplication.run(Application.class, args); - + displayAllBeans(); } - + public static void displayAllBeans() { String[] allBeanNames = applicationContext.getBeanDefinitionNames(); - for(String beanName : allBeanNames) { + for (String beanName : allBeanNames) { System.out.println(beanName); } } diff --git a/spring-boot/src/main/java/com/baeldung/displayallbeans/controller/FooController.java b/spring-boot/src/main/java/com/baeldung/displayallbeans/controller/FooController.java index 9f483b18d1..26f0a60bff 100644 --- a/spring-boot/src/main/java/com/baeldung/displayallbeans/controller/FooController.java +++ b/spring-boot/src/main/java/com/baeldung/displayallbeans/controller/FooController.java @@ -12,9 +12,9 @@ import com.baeldung.displayallbeans.service.FooService; public class FooController { @Autowired private FooService fooService; - - @RequestMapping(value="/displayallbeans") - public String getHeaderAndBody (Map model){ + + @RequestMapping(value = "/displayallbeans") + public String getHeaderAndBody(Map model) { model.put("header", fooService.getHeader()); model.put("message", fooService.getBody()); return "displayallbeans"; diff --git a/spring-boot/src/main/java/com/baeldung/displayallbeans/service/FooService.java b/spring-boot/src/main/java/com/baeldung/displayallbeans/service/FooService.java index e29f18c94a..1f3c15ee0e 100644 --- a/spring-boot/src/main/java/com/baeldung/displayallbeans/service/FooService.java +++ b/spring-boot/src/main/java/com/baeldung/displayallbeans/service/FooService.java @@ -4,15 +4,13 @@ import org.springframework.stereotype.Service; @Service public class FooService { - + public String getHeader() { return "Display All Beans"; } - + public String getBody() { - return "This is a sample application that displays all beans " - + "in Spring IoC container using ListableBeanFactory interface " - + "and Spring Boot Actuators."; + return "This is a sample application that displays all beans " + "in Spring IoC container using ListableBeanFactory interface " + "and Spring Boot Actuators."; } - + } diff --git a/spring-boot/src/main/java/com/baeldung/dynamicvalidation/config/PersistenceConfig.java b/spring-boot/src/main/java/com/baeldung/dynamicvalidation/config/PersistenceConfig.java index d89dfc5fcd..a2b171c156 100644 --- a/spring-boot/src/main/java/com/baeldung/dynamicvalidation/config/PersistenceConfig.java +++ b/spring-boot/src/main/java/com/baeldung/dynamicvalidation/config/PersistenceConfig.java @@ -18,7 +18,10 @@ public class PersistenceConfig { @Bean public DataSource dataSource() { EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder(); - EmbeddedDatabase db = builder.setType(EmbeddedDatabaseType.H2).addScript("schema-expressions.sql").addScript("data-expressions.sql").build(); + EmbeddedDatabase db = builder.setType(EmbeddedDatabaseType.H2) + .addScript("schema-expressions.sql") + .addScript("data-expressions.sql") + .build(); return db; } } diff --git a/spring-boot/src/main/java/com/baeldung/failureanalyzer/FailureAnalyzerApplication.java b/spring-boot/src/main/java/com/baeldung/failureanalyzer/FailureAnalyzerApplication.java index 9d379cbc09..84c96feb92 100644 --- a/spring-boot/src/main/java/com/baeldung/failureanalyzer/FailureAnalyzerApplication.java +++ b/spring-boot/src/main/java/com/baeldung/failureanalyzer/FailureAnalyzerApplication.java @@ -7,7 +7,7 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; import com.baeldung.autoconfiguration.MySQLAutoconfiguration; -@SpringBootApplication(exclude=MySQLAutoconfiguration.class) +@SpringBootApplication(exclude = MySQLAutoconfiguration.class) public class FailureAnalyzerApplication { @RolesAllowed("*") public static void main(String[] args) { diff --git a/spring-boot/src/main/java/com/baeldung/failureanalyzer/MyBeanNotOfRequiredTypeFailureAnalyzer.java b/spring-boot/src/main/java/com/baeldung/failureanalyzer/MyBeanNotOfRequiredTypeFailureAnalyzer.java index 2bbae8944a..04c7fdff9a 100644 --- a/spring-boot/src/main/java/com/baeldung/failureanalyzer/MyBeanNotOfRequiredTypeFailureAnalyzer.java +++ b/spring-boot/src/main/java/com/baeldung/failureanalyzer/MyBeanNotOfRequiredTypeFailureAnalyzer.java @@ -4,8 +4,7 @@ import org.springframework.beans.factory.BeanNotOfRequiredTypeException; import org.springframework.boot.diagnostics.AbstractFailureAnalyzer; import org.springframework.boot.diagnostics.FailureAnalysis; -public class MyBeanNotOfRequiredTypeFailureAnalyzer - extends AbstractFailureAnalyzer { +public class MyBeanNotOfRequiredTypeFailureAnalyzer extends AbstractFailureAnalyzer { @Override protected FailureAnalysis analyze(Throwable rootFailure, BeanNotOfRequiredTypeException cause) { @@ -13,16 +12,15 @@ public class MyBeanNotOfRequiredTypeFailureAnalyzer } private String getDescription(BeanNotOfRequiredTypeException ex) { - return String.format("The bean %s could not be injected as %s because it is of type %s", - ex.getBeanName(), - ex.getRequiredType().getName(), - ex.getActualType().getName()); + return String.format("The bean %s could not be injected as %s because it is of type %s", ex.getBeanName(), ex.getRequiredType() + .getName(), + ex.getActualType() + .getName()); } private String getAction(BeanNotOfRequiredTypeException ex) { - return String.format("Consider creating a bean with name %s of type %s", - ex.getBeanName(), - ex.getRequiredType().getName()); + return String.format("Consider creating a bean with name %s of type %s", ex.getBeanName(), ex.getRequiredType() + .getName()); } } diff --git a/spring-boot/src/main/java/com/baeldung/git/CommitIdApplication.java b/spring-boot/src/main/java/com/baeldung/git/CommitIdApplication.java index c077692edb..4655e36f83 100644 --- a/spring-boot/src/main/java/com/baeldung/git/CommitIdApplication.java +++ b/spring-boot/src/main/java/com/baeldung/git/CommitIdApplication.java @@ -8,7 +8,7 @@ import org.springframework.core.io.ClassPathResource; import com.baeldung.autoconfiguration.MySQLAutoconfiguration; -@SpringBootApplication(scanBasePackages = { "com.baeldung.git" }, exclude=MySQLAutoconfiguration.class) +@SpringBootApplication(scanBasePackages = { "com.baeldung.git" }, exclude = MySQLAutoconfiguration.class) public class CommitIdApplication { public static void main(String[] args) { SpringApplication.run(CommitIdApplication.class, args); diff --git a/spring-boot/src/main/java/com/baeldung/graphql/GraphqlConfiguration.java b/spring-boot/src/main/java/com/baeldung/graphql/GraphqlConfiguration.java index a7a864cf96..c5ae8bd772 100644 --- a/spring-boot/src/main/java/com/baeldung/graphql/GraphqlConfiguration.java +++ b/spring-boot/src/main/java/com/baeldung/graphql/GraphqlConfiguration.java @@ -23,7 +23,7 @@ public class GraphqlConfiguration { } return new PostDao(posts); } - + @Bean public AuthorDao authorDao() { List authors = new ArrayList<>(); @@ -36,12 +36,12 @@ public class GraphqlConfiguration { } return new AuthorDao(authors); } - + @Bean public PostResolver postResolver(AuthorDao authorDao) { return new PostResolver(authorDao); } - + @Bean public AuthorResolver authorResolver(PostDao postDao) { return new AuthorResolver(postDao); diff --git a/spring-boot/src/main/java/com/baeldung/graphql/Mutation.java b/spring-boot/src/main/java/com/baeldung/graphql/Mutation.java index 0e16e3c8b7..5ccc80dad1 100644 --- a/spring-boot/src/main/java/com/baeldung/graphql/Mutation.java +++ b/spring-boot/src/main/java/com/baeldung/graphql/Mutation.java @@ -13,7 +13,8 @@ public class Mutation implements GraphQLMutationResolver { public Post writePost(String title, String text, String category, String author) { Post post = new Post(); - post.setId(UUID.randomUUID().toString()); + post.setId(UUID.randomUUID() + .toString()); post.setTitle(title); post.setText(text); post.setCategory(category); diff --git a/spring-boot/src/main/java/com/baeldung/internationalization/InternationalizationApp.java b/spring-boot/src/main/java/com/baeldung/internationalization/InternationalizationApp.java index b743eb4b61..ca56437392 100644 --- a/spring-boot/src/main/java/com/baeldung/internationalization/InternationalizationApp.java +++ b/spring-boot/src/main/java/com/baeldung/internationalization/InternationalizationApp.java @@ -7,7 +7,7 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; import com.baeldung.autoconfiguration.MySQLAutoconfiguration; -@SpringBootApplication(exclude=MySQLAutoconfiguration.class) +@SpringBootApplication(exclude = MySQLAutoconfiguration.class) public class InternationalizationApp { @RolesAllowed("*") public static void main(String[] args) { diff --git a/spring-boot/src/main/java/com/baeldung/intro/App.java b/spring-boot/src/main/java/com/baeldung/intro/App.java index 9553d814ac..b865deea29 100644 --- a/spring-boot/src/main/java/com/baeldung/intro/App.java +++ b/spring-boot/src/main/java/com/baeldung/intro/App.java @@ -5,11 +5,9 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; import com.baeldung.autoconfiguration.MySQLAutoconfiguration; -@SpringBootApplication(exclude=MySQLAutoconfiguration.class) -public class App -{ - public static void main( String[] args ) - { +@SpringBootApplication(exclude = MySQLAutoconfiguration.class) +public class App { + public static void main(String[] args) { SpringApplication.run(App.class, args); } } diff --git a/spring-boot/src/main/java/com/baeldung/intro/controller/HomeController.java b/spring-boot/src/main/java/com/baeldung/intro/controller/HomeController.java index 9109b0a292..2a82e58829 100644 --- a/spring-boot/src/main/java/com/baeldung/intro/controller/HomeController.java +++ b/spring-boot/src/main/java/com/baeldung/intro/controller/HomeController.java @@ -7,12 +7,12 @@ import org.springframework.web.bind.annotation.RestController; public class HomeController { @RequestMapping("/") - public String root(){ + public String root() { return "Index Page"; } - + @RequestMapping("/local") - public String local(){ + public String local() { return "/local"; } } diff --git a/spring-boot/src/main/java/com/baeldung/servlets/ApplicationMain.java b/spring-boot/src/main/java/com/baeldung/servlets/ApplicationMain.java index 8965e2f013..c8461e4efc 100644 --- a/spring-boot/src/main/java/com/baeldung/servlets/ApplicationMain.java +++ b/spring-boot/src/main/java/com/baeldung/servlets/ApplicationMain.java @@ -7,7 +7,7 @@ import org.springframework.boot.web.support.SpringBootServletInitializer; import com.baeldung.autoconfiguration.MySQLAutoconfiguration; -@SpringBootApplication(exclude=MySQLAutoconfiguration.class) +@SpringBootApplication(exclude = MySQLAutoconfiguration.class) public class ApplicationMain extends SpringBootServletInitializer { public static void main(String[] args) { diff --git a/spring-boot/src/main/java/com/baeldung/servlets/configuration/WebMvcConfigure.java b/spring-boot/src/main/java/com/baeldung/servlets/configuration/WebMvcConfigure.java index 3d6a10c2ac..2d8298338c 100644 --- a/spring-boot/src/main/java/com/baeldung/servlets/configuration/WebMvcConfigure.java +++ b/spring-boot/src/main/java/com/baeldung/servlets/configuration/WebMvcConfigure.java @@ -26,10 +26,13 @@ public class WebMvcConfigure extends WebMvcConfigurerAdapter { configurer.enable(); } - @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { - registry.addResourceHandler("/resources/**").addResourceLocations("/resources/").setCachePeriod(3600).resourceChain(true).addResolver(new PathResourceResolver()); + registry.addResourceHandler("/resources/**") + .addResourceLocations("/resources/") + .setCachePeriod(3600) + .resourceChain(true) + .addResolver(new PathResourceResolver()); } @Bean diff --git a/spring-boot/src/main/java/com/baeldung/servlets/props/PropertySourcesLoader.java b/spring-boot/src/main/java/com/baeldung/servlets/props/PropertySourcesLoader.java index aa70bac777..bbab95c41f 100644 --- a/spring-boot/src/main/java/com/baeldung/servlets/props/PropertySourcesLoader.java +++ b/spring-boot/src/main/java/com/baeldung/servlets/props/PropertySourcesLoader.java @@ -10,7 +10,8 @@ import org.springframework.core.env.ConfigurableEnvironment; @Configuration @ComponentScan(basePackages = { "com.baeldung.servlets.*" }) -@PropertySource("classpath:custom.properties") public class PropertySourcesLoader { +@PropertySource("classpath:custom.properties") +public class PropertySourcesLoader { private static final Logger log = LoggerFactory.getLogger(PropertySourcesLoader.class); diff --git a/spring-boot/src/main/java/com/baeldung/servlets/servlets/javaee/AnnotationServlet.java b/spring-boot/src/main/java/com/baeldung/servlets/servlets/javaee/AnnotationServlet.java index b50a7d5454..358ff5af2d 100644 --- a/spring-boot/src/main/java/com/baeldung/servlets/servlets/javaee/AnnotationServlet.java +++ b/spring-boot/src/main/java/com/baeldung/servlets/servlets/javaee/AnnotationServlet.java @@ -7,14 +7,13 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; -@WebServlet(name = "AnnotationServlet", - description = "Example Servlet Using Annotations", - urlPatterns = { "/annotationservlet" }) +@WebServlet(name = "AnnotationServlet", description = "Example Servlet Using Annotations", urlPatterns = { "/annotationservlet" }) public class AnnotationServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - request.getRequestDispatcher("/annotationservlet.jsp").forward(request, response); + request.getRequestDispatcher("/annotationservlet.jsp") + .forward(request, response); } } diff --git a/spring-boot/src/main/java/com/baeldung/toggle/EmployeeRepository.java b/spring-boot/src/main/java/com/baeldung/toggle/EmployeeRepository.java index 7ea7c11fde..4e75fc6411 100644 --- a/spring-boot/src/main/java/com/baeldung/toggle/EmployeeRepository.java +++ b/spring-boot/src/main/java/com/baeldung/toggle/EmployeeRepository.java @@ -2,6 +2,6 @@ package com.baeldung.toggle; import org.springframework.data.repository.CrudRepository; -public interface EmployeeRepository extends CrudRepository{ +public interface EmployeeRepository extends CrudRepository { } diff --git a/spring-boot/src/main/java/com/baeldung/toggle/MyFeatures.java b/spring-boot/src/main/java/com/baeldung/toggle/MyFeatures.java index 245415a2a0..b05ec2bf52 100644 --- a/spring-boot/src/main/java/com/baeldung/toggle/MyFeatures.java +++ b/spring-boot/src/main/java/com/baeldung/toggle/MyFeatures.java @@ -10,13 +10,15 @@ import org.togglz.core.context.FeatureContext; public enum MyFeatures implements Feature { - @Label("Employee Management Feature") @EnabledByDefault @DefaultActivationStrategy(id = SystemPropertyActivationStrategy.ID, - parameters = { @ActivationParameter(name = SystemPropertyActivationStrategy.PARAM_PROPERTY_NAME, value = "employee.feature"), - @ActivationParameter(name = SystemPropertyActivationStrategy.PARAM_PROPERTY_VALUE, value = "true") }) + @Label("Employee Management Feature") + @EnabledByDefault + @DefaultActivationStrategy(id = SystemPropertyActivationStrategy.ID, parameters = { @ActivationParameter(name = SystemPropertyActivationStrategy.PARAM_PROPERTY_NAME, value = "employee.feature"), + @ActivationParameter(name = SystemPropertyActivationStrategy.PARAM_PROPERTY_VALUE, value = "true") }) EMPLOYEE_MANAGEMENT_FEATURE; public boolean isActive() { - return FeatureContext.getFeatureManager().isActive(this); + return FeatureContext.getFeatureManager() + .isActive(this); } } diff --git a/spring-boot/src/main/java/com/baeldung/utils/UtilsApplication.java b/spring-boot/src/main/java/com/baeldung/utils/UtilsApplication.java index b63ada9eee..4b00247c4a 100644 --- a/spring-boot/src/main/java/com/baeldung/utils/UtilsApplication.java +++ b/spring-boot/src/main/java/com/baeldung/utils/UtilsApplication.java @@ -8,13 +8,13 @@ import org.springframework.context.annotation.ComponentScan; import com.baeldung.autoconfiguration.MySQLAutoconfiguration; -@SpringBootApplication(exclude=MySQLAutoconfiguration.class) -@ComponentScan(basePackages="com.baeldung.utils") +@SpringBootApplication(exclude = MySQLAutoconfiguration.class) +@ComponentScan(basePackages = "com.baeldung.utils") public class UtilsApplication { - @RolesAllowed("*") - public static void main(String[] args) { - SpringApplication.run(UtilsApplication.class, args); - } + @RolesAllowed("*") + public static void main(String[] args) { + SpringApplication.run(UtilsApplication.class, args); + } } diff --git a/spring-boot/src/main/java/com/baeldung/utils/controller/UtilsController.java b/spring-boot/src/main/java/com/baeldung/utils/controller/UtilsController.java index 7b4827cdf2..7c66391bd2 100644 --- a/spring-boot/src/main/java/com/baeldung/utils/controller/UtilsController.java +++ b/spring-boot/src/main/java/com/baeldung/utils/controller/UtilsController.java @@ -13,37 +13,37 @@ import org.springframework.web.util.WebUtils; @Controller public class UtilsController { - @GetMapping("/utils") - public String webUtils(Model model) { - return "utils"; - } - - @PostMapping("/setParam") - public String post(HttpServletRequest request, Model model) { - String param = ServletRequestUtils.getStringParameter(request, "param", "DEFAULT"); - -// Long param = ServletRequestUtils.getLongParameter(request, "param",1L); -// boolean param = ServletRequestUtils.getBooleanParameter(request, "param", true); -// double param = ServletRequestUtils.getDoubleParameter(request, "param", 1000); -// float param = ServletRequestUtils.getFloatParameter(request, "param", (float) 1.00); -// int param = ServletRequestUtils.getIntParameter(request, "param", 100); - -// try { -// ServletRequestUtils.getRequiredStringParameter(request, "param"); -// } catch (ServletRequestBindingException e) { -// e.printStackTrace(); -// } - - WebUtils.setSessionAttribute(request, "parameter", param); - model.addAttribute("parameter", "You set: "+(String) WebUtils.getSessionAttribute(request, "parameter")); - return "utils"; - } - - @GetMapping("/other") - public String other(HttpServletRequest request, Model model) { - String param = (String) WebUtils.getSessionAttribute(request, "parameter"); - model.addAttribute("parameter", param); - return "other"; - } - + @GetMapping("/utils") + public String webUtils(Model model) { + return "utils"; + } + + @PostMapping("/setParam") + public String post(HttpServletRequest request, Model model) { + String param = ServletRequestUtils.getStringParameter(request, "param", "DEFAULT"); + + // Long param = ServletRequestUtils.getLongParameter(request, "param",1L); + // boolean param = ServletRequestUtils.getBooleanParameter(request, "param", true); + // double param = ServletRequestUtils.getDoubleParameter(request, "param", 1000); + // float param = ServletRequestUtils.getFloatParameter(request, "param", (float) 1.00); + // int param = ServletRequestUtils.getIntParameter(request, "param", 100); + + // try { + // ServletRequestUtils.getRequiredStringParameter(request, "param"); + // } catch (ServletRequestBindingException e) { + // e.printStackTrace(); + // } + + WebUtils.setSessionAttribute(request, "parameter", param); + model.addAttribute("parameter", "You set: " + (String) WebUtils.getSessionAttribute(request, "parameter")); + return "utils"; + } + + @GetMapping("/other") + public String other(HttpServletRequest request, Model model) { + String param = (String) WebUtils.getSessionAttribute(request, "parameter"); + model.addAttribute("parameter", param); + return "other"; + } + } diff --git a/spring-boot/src/main/java/com/baeldung/webjar/WebjarsdemoApplication.java b/spring-boot/src/main/java/com/baeldung/webjar/WebjarsdemoApplication.java index 44d48f5f8f..8704b42166 100644 --- a/spring-boot/src/main/java/com/baeldung/webjar/WebjarsdemoApplication.java +++ b/spring-boot/src/main/java/com/baeldung/webjar/WebjarsdemoApplication.java @@ -6,7 +6,7 @@ import org.springframework.context.annotation.ComponentScan; import com.baeldung.autoconfiguration.MySQLAutoconfiguration; -@SpringBootApplication(exclude=MySQLAutoconfiguration.class) +@SpringBootApplication(exclude = MySQLAutoconfiguration.class) public class WebjarsdemoApplication { public static void main(String[] args) { diff --git a/spring-boot/src/main/java/org/baeldung/Application.java b/spring-boot/src/main/java/org/baeldung/Application.java index 8b49f4d6ab..1c1e466afc 100644 --- a/spring-boot/src/main/java/org/baeldung/Application.java +++ b/spring-boot/src/main/java/org/baeldung/Application.java @@ -6,7 +6,7 @@ import org.springframework.context.ApplicationContext; import com.baeldung.autoconfiguration.MySQLAutoconfiguration; -@SpringBootApplication(exclude=MySQLAutoconfiguration.class) +@SpringBootApplication(exclude = MySQLAutoconfiguration.class) public class Application { private static ApplicationContext applicationContext; diff --git a/spring-boot/src/main/java/org/baeldung/boot/DemoApplication.java b/spring-boot/src/main/java/org/baeldung/boot/DemoApplication.java index 5de4134739..cb269f77f1 100644 --- a/spring-boot/src/main/java/org/baeldung/boot/DemoApplication.java +++ b/spring-boot/src/main/java/org/baeldung/boot/DemoApplication.java @@ -7,7 +7,7 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; import com.baeldung.autoconfiguration.MySQLAutoconfiguration; import org.springframework.context.annotation.Import; -@SpringBootApplication(exclude=MySQLAutoconfiguration.class) +@SpringBootApplication(exclude = MySQLAutoconfiguration.class) @Import(GraphqlConfiguration.class) public class DemoApplication { diff --git a/spring-boot/src/main/java/org/baeldung/boot/components/FooService.java b/spring-boot/src/main/java/org/baeldung/boot/components/FooService.java index 235fd43299..4ff8e9fdd4 100644 --- a/spring-boot/src/main/java/org/baeldung/boot/components/FooService.java +++ b/spring-boot/src/main/java/org/baeldung/boot/components/FooService.java @@ -10,11 +10,11 @@ public class FooService { @Autowired private FooRepository fooRepository; - + public Foo getFooWithId(Integer id) throws Exception { return fooRepository.findOne(id); } - + public Foo getFooWithName(String name) { return fooRepository.findByName(name); } diff --git a/spring-boot/src/main/java/org/baeldung/boot/exceptions/CommonException.java b/spring-boot/src/main/java/org/baeldung/boot/exceptions/CommonException.java index 1f008440e6..e03b859eab 100644 --- a/spring-boot/src/main/java/org/baeldung/boot/exceptions/CommonException.java +++ b/spring-boot/src/main/java/org/baeldung/boot/exceptions/CommonException.java @@ -1,13 +1,13 @@ package org.baeldung.boot.exceptions; -public class CommonException extends RuntimeException{ +public class CommonException extends RuntimeException { /** * */ private static final long serialVersionUID = 3080004140659213332L; - public CommonException(String message){ + public CommonException(String message) { super(message); } } diff --git a/spring-boot/src/main/java/org/baeldung/boot/exceptions/FooNotFoundException.java b/spring-boot/src/main/java/org/baeldung/boot/exceptions/FooNotFoundException.java index 68ef3fa389..0b04bd2759 100644 --- a/spring-boot/src/main/java/org/baeldung/boot/exceptions/FooNotFoundException.java +++ b/spring-boot/src/main/java/org/baeldung/boot/exceptions/FooNotFoundException.java @@ -1,13 +1,13 @@ package org.baeldung.boot.exceptions; -public class FooNotFoundException extends RuntimeException{ +public class FooNotFoundException extends RuntimeException { /** * */ private static final long serialVersionUID = 9042200028456133589L; - public FooNotFoundException(String message){ + public FooNotFoundException(String message) { super(message); } } diff --git a/spring-boot/src/main/java/org/baeldung/boot/model/Foo.java b/spring-boot/src/main/java/org/baeldung/boot/model/Foo.java index ac8a8fe429..d373e25b85 100644 --- a/spring-boot/src/main/java/org/baeldung/boot/model/Foo.java +++ b/spring-boot/src/main/java/org/baeldung/boot/model/Foo.java @@ -21,7 +21,6 @@ public class Foo implements Serializable { this.name = name; } - public Foo(Integer id, String name) { super(); this.id = id; diff --git a/spring-boot/src/main/java/org/baeldung/boot/service/FooController.java b/spring-boot/src/main/java/org/baeldung/boot/service/FooController.java index 834fa342e2..d400c3bf9e 100644 --- a/spring-boot/src/main/java/org/baeldung/boot/service/FooController.java +++ b/spring-boot/src/main/java/org/baeldung/boot/service/FooController.java @@ -18,7 +18,7 @@ public class FooController { public Foo getFooWithId(@PathVariable Integer id) throws Exception { return fooService.getFooWithId(id); } - + @GetMapping("/") public Foo getFooWithName(@RequestParam String name) throws Exception { return fooService.getFooWithName(name); diff --git a/spring-boot/src/main/java/org/baeldung/controller/GenericEntityController.java b/spring-boot/src/main/java/org/baeldung/controller/GenericEntityController.java index 7d1ad7d899..a9e7dee0b7 100644 --- a/spring-boot/src/main/java/org/baeldung/controller/GenericEntityController.java +++ b/spring-boot/src/main/java/org/baeldung/controller/GenericEntityController.java @@ -39,21 +39,31 @@ public class GenericEntityController { @RequestMapping("/entity/findby/{id}") public GenericEntity findById(@PathVariable Long id) { - return entityList.stream().filter(entity -> entity.getId().equals(id)).findFirst().get(); + return entityList.stream() + .filter(entity -> entity.getId() + .equals(id)) + .findFirst() + .get(); } @GetMapping("/entity/findbydate/{date}") public GenericEntity findByDate(@PathVariable("date") LocalDateTime date) { - return entityList.stream().findFirst().get(); + return entityList.stream() + .findFirst() + .get(); } @GetMapping("/entity/findbymode/{mode}") public GenericEntity findByEnum(@PathVariable("mode") Modes mode) { - return entityList.stream().findFirst().get(); + return entityList.stream() + .findFirst() + .get(); } @GetMapping("/entity/findbyversion") public ResponseEntity findByVersion(@Version String version) { - return version != null ? new ResponseEntity(entityList.stream().findFirst().get(), HttpStatus.OK) : new ResponseEntity(HttpStatus.NOT_FOUND); + return version != null ? new ResponseEntity(entityList.stream() + .findFirst() + .get(), HttpStatus.OK) : new ResponseEntity(HttpStatus.NOT_FOUND); } } diff --git a/spring-boot/src/main/java/org/baeldung/endpoints/MyHealthCheck.java b/spring-boot/src/main/java/org/baeldung/endpoints/MyHealthCheck.java index 1a175aed48..68fbffda6e 100644 --- a/spring-boot/src/main/java/org/baeldung/endpoints/MyHealthCheck.java +++ b/spring-boot/src/main/java/org/baeldung/endpoints/MyHealthCheck.java @@ -10,9 +10,13 @@ public class MyHealthCheck implements HealthIndicator { public Health health() { int errorCode = check(); // perform some specific health check if (errorCode != 0) { - return Health.down().withDetail("Error Code", errorCode).withDetail("Description", "You custom MyHealthCheck endpoint is down").build(); + return Health.down() + .withDetail("Error Code", errorCode) + .withDetail("Description", "You custom MyHealthCheck endpoint is down") + .build(); } - return Health.up().build(); + return Health.up() + .build(); } public int check() { diff --git a/spring-boot/src/main/java/org/baeldung/jsoncomponent/UserCombinedSerializer.java b/spring-boot/src/main/java/org/baeldung/jsoncomponent/UserCombinedSerializer.java index 2001340197..cb1b838ca4 100644 --- a/spring-boot/src/main/java/org/baeldung/jsoncomponent/UserCombinedSerializer.java +++ b/spring-boot/src/main/java/org/baeldung/jsoncomponent/UserCombinedSerializer.java @@ -21,8 +21,7 @@ public class UserCombinedSerializer { @Override public void serialize(User user, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException { jsonGenerator.writeStartObject(); - jsonGenerator.writeStringField("favoriteColor", - getColorAsWebColor(user.getFavoriteColor())); + jsonGenerator.writeStringField("favoriteColor", getColorAsWebColor(user.getFavoriteColor())); jsonGenerator.writeEndObject(); } @@ -37,7 +36,8 @@ public class UserCombinedSerializer { public static class UserJsonDeserializer extends JsonDeserializer { @Override public User deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException { - TreeNode treeNode = jsonParser.getCodec().readTree(jsonParser); + TreeNode treeNode = jsonParser.getCodec() + .readTree(jsonParser); TextNode favoriteColor = (TextNode) treeNode.get("favoriteColor"); return new User(Color.web(favoriteColor.asText())); } diff --git a/spring-boot/src/main/java/org/baeldung/jsoncomponent/UserJsonDeserializer.java b/spring-boot/src/main/java/org/baeldung/jsoncomponent/UserJsonDeserializer.java index d18de7e3f1..a310dcba5a 100644 --- a/spring-boot/src/main/java/org/baeldung/jsoncomponent/UserJsonDeserializer.java +++ b/spring-boot/src/main/java/org/baeldung/jsoncomponent/UserJsonDeserializer.java @@ -15,7 +15,8 @@ import java.io.IOException; public class UserJsonDeserializer extends JsonDeserializer { @Override public User deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException { - TreeNode treeNode = jsonParser.getCodec().readTree(jsonParser); + TreeNode treeNode = jsonParser.getCodec() + .readTree(jsonParser); TextNode favoriteColor = (TextNode) treeNode.get("favoriteColor"); return new User(Color.web(favoriteColor.asText())); } diff --git a/spring-boot/src/main/java/org/baeldung/jsoncomponent/UserJsonSerializer.java b/spring-boot/src/main/java/org/baeldung/jsoncomponent/UserJsonSerializer.java index d90f662a4b..845bc3aac5 100644 --- a/spring-boot/src/main/java/org/baeldung/jsoncomponent/UserJsonSerializer.java +++ b/spring-boot/src/main/java/org/baeldung/jsoncomponent/UserJsonSerializer.java @@ -15,8 +15,7 @@ public class UserJsonSerializer extends JsonSerializer { @Override public void serialize(User user, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException { jsonGenerator.writeStartObject(); - jsonGenerator.writeStringField("favoriteColor", - getColorAsWebColor(user.getFavoriteColor())); + jsonGenerator.writeStringField("favoriteColor", getColorAsWebColor(user.getFavoriteColor())); jsonGenerator.writeEndObject(); } diff --git a/spring-boot/src/main/java/org/baeldung/main/SpringBootApplication.java b/spring-boot/src/main/java/org/baeldung/main/SpringBootApplication.java index 872426d850..2d118b0eae 100644 --- a/spring-boot/src/main/java/org/baeldung/main/SpringBootApplication.java +++ b/spring-boot/src/main/java/org/baeldung/main/SpringBootApplication.java @@ -20,7 +20,7 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @RestController -@EnableAutoConfiguration(exclude=MySQLAutoconfiguration.class) +@EnableAutoConfiguration(exclude = MySQLAutoconfiguration.class) @ComponentScan({ "org.baeldung.common.error", "org.baeldung.common.error.controller", "org.baeldung.common.properties", "org.baeldung.common.resources", "org.baeldung.endpoints", "org.baeldung.service", "org.baeldung.monitor.jmx", "org.baeldung.service" }) public class SpringBootApplication { diff --git a/spring-boot/src/main/java/org/baeldung/monitor/jmx/MonitoringConfig.java b/spring-boot/src/main/java/org/baeldung/monitor/jmx/MonitoringConfig.java index 8100e61629..40f36ef924 100644 --- a/spring-boot/src/main/java/org/baeldung/monitor/jmx/MonitoringConfig.java +++ b/spring-boot/src/main/java/org/baeldung/monitor/jmx/MonitoringConfig.java @@ -14,7 +14,8 @@ public class MonitoringConfig { @Bean public JmxReporter jmxReporter() { - JmxReporter reporter = JmxReporter.forRegistry(registry).build(); + JmxReporter reporter = JmxReporter.forRegistry(registry) + .build(); reporter.start(); return reporter; } diff --git a/spring-boot/src/main/java/org/baeldung/service/LoginServiceImpl.java b/spring-boot/src/main/java/org/baeldung/service/LoginServiceImpl.java index ed0090f8e4..6d89f7f695 100644 --- a/spring-boot/src/main/java/org/baeldung/service/LoginServiceImpl.java +++ b/spring-boot/src/main/java/org/baeldung/service/LoginServiceImpl.java @@ -16,7 +16,8 @@ public class LoginServiceImpl implements LoginService { public boolean login(String userName, char[] password) { boolean success; - if (userName.equals("admin") && "secret".toCharArray().equals(password)) { + if (userName.equals("admin") && "secret".toCharArray() + .equals(password)) { counterService.increment("counter.login.success"); success = true; } else { diff --git a/spring-boot/src/main/java/org/baeldung/session/exception/Application.java b/spring-boot/src/main/java/org/baeldung/session/exception/Application.java index 9f8dadbe55..c0cc669420 100644 --- a/spring-boot/src/main/java/org/baeldung/session/exception/Application.java +++ b/spring-boot/src/main/java/org/baeldung/session/exception/Application.java @@ -10,7 +10,7 @@ import org.springframework.orm.jpa.vendor.HibernateJpaSessionFactoryBean; import com.baeldung.autoconfiguration.MySQLAutoconfiguration; @EntityScan(basePackageClasses = Foo.class) -@SpringBootApplication(exclude=MySQLAutoconfiguration.class) +@SpringBootApplication(exclude = MySQLAutoconfiguration.class) public class Application { public static void main(String[] args) { System.setProperty("spring.config.name", "exception"); diff --git a/spring-boot/src/main/java/org/baeldung/session/exception/repository/FooRepositoryImpl.java b/spring-boot/src/main/java/org/baeldung/session/exception/repository/FooRepositoryImpl.java index 83de888e5e..36d87e6dad 100644 --- a/spring-boot/src/main/java/org/baeldung/session/exception/repository/FooRepositoryImpl.java +++ b/spring-boot/src/main/java/org/baeldung/session/exception/repository/FooRepositoryImpl.java @@ -14,12 +14,14 @@ public class FooRepositoryImpl implements FooRepository { @Override public void save(Foo foo) { - sessionFactory.getCurrentSession().saveOrUpdate(foo); + sessionFactory.getCurrentSession() + .saveOrUpdate(foo); } @Override public Foo get(Integer id) { - return sessionFactory.getCurrentSession().get(Foo.class, id); + return sessionFactory.getCurrentSession() + .get(Foo.class, id); } } \ No newline at end of file diff --git a/spring-boot/src/main/java/org/baeldung/websocket/client/Message.java b/spring-boot/src/main/java/org/baeldung/websocket/client/Message.java index bcab44870b..2744c49f62 100644 --- a/spring-boot/src/main/java/org/baeldung/websocket/client/Message.java +++ b/spring-boot/src/main/java/org/baeldung/websocket/client/Message.java @@ -20,6 +20,5 @@ public class Message { public void setText(String text) { this.text = text; } - - + } diff --git a/spring-boot/src/main/java/org/baeldung/websocket/client/MyStompSessionHandler.java b/spring-boot/src/main/java/org/baeldung/websocket/client/MyStompSessionHandler.java index 35bf1827ea..45fbf2b623 100644 --- a/spring-boot/src/main/java/org/baeldung/websocket/client/MyStompSessionHandler.java +++ b/spring-boot/src/main/java/org/baeldung/websocket/client/MyStompSessionHandler.java @@ -17,12 +17,12 @@ import java.lang.reflect.Type; * */ public class MyStompSessionHandler extends StompSessionHandlerAdapter { - + private Logger logger = Logger.getLogger(MyStompSessionHandler.class); - + @Override public void afterConnected(StompSession session, StompHeaders connectedHeaders) { - logger.info("New session established : "+session.getSessionId()); + logger.info("New session established : " + session.getSessionId()); session.subscribe("/topic/messages", this); logger.info("Subscribed to /topic/messages"); session.send("/app/chat", getSampleMessage()); @@ -41,15 +41,15 @@ public class MyStompSessionHandler extends StompSessionHandlerAdapter { @Override public void handleFrame(StompHeaders headers, Object payload) { - Message msg = (Message)payload; - logger.info("Received : "+ msg.getText()+ " from : "+msg.getFrom()); + Message msg = (Message) payload; + logger.info("Received : " + msg.getText() + " from : " + msg.getFrom()); } - + /** * A sample message instance. * @return instance of Message */ - private Message getSampleMessage(){ + private Message getSampleMessage() { Message msg = new Message(); msg.setFrom("Nicky"); msg.setText("Howdy!!"); diff --git a/spring-boot/src/main/java/org/baeldung/websocket/client/StompClient.java b/spring-boot/src/main/java/org/baeldung/websocket/client/StompClient.java index 71f5471fb1..2bff07186d 100644 --- a/spring-boot/src/main/java/org/baeldung/websocket/client/StompClient.java +++ b/spring-boot/src/main/java/org/baeldung/websocket/client/StompClient.java @@ -19,9 +19,9 @@ public class StompClient { public static void main(String[] args) { WebSocketClient client = new StandardWebSocketClient(); WebSocketStompClient stompClient = new WebSocketStompClient(client); - + stompClient.setMessageConverter(new MappingJackson2MessageConverter()); - + StompSessionHandler sessionHandler = new MyStompSessionHandler(); stompClient.connect(URL, sessionHandler); diff --git a/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithServletComponentIntegrationTest.java b/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithServletComponentIntegrationTest.java index 660b461ab6..b2b14f766e 100644 --- a/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithServletComponentIntegrationTest.java +++ b/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithServletComponentIntegrationTest.java @@ -21,7 +21,7 @@ import static org.junit.Assert.assertTrue; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = SpringBootAnnotatedApp.class) @AutoConfigureMockMvc -@TestPropertySource(properties = {"security.basic.enabled=false"}) +@TestPropertySource(properties = { "security.basic.enabled=false" }) public class SpringBootWithServletComponentIntegrationTest { @Autowired @@ -40,9 +40,8 @@ public class SpringBootWithServletComponentIntegrationTest { FilterRegistration filterRegistration = servletContext.getFilterRegistration("hello filter"); assertNotNull(filterRegistration); - assertTrue(filterRegistration - .getServletNameMappings() - .contains("echo servlet")); + assertTrue(filterRegistration.getServletNameMappings() + .contains("echo servlet")); } @Autowired @@ -62,7 +61,4 @@ public class SpringBootWithServletComponentIntegrationTest { assertEquals("filtering echo", responseEntity.getBody()); } - } - - diff --git a/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithoutServletComponentIntegrationTest.java b/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithoutServletComponentIntegrationTest.java index 31bb2ab195..a13cd250a2 100644 --- a/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithoutServletComponentIntegrationTest.java +++ b/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithoutServletComponentIntegrationTest.java @@ -21,7 +21,7 @@ import static org.junit.Assert.assertNull; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = SpringBootPlainApp.class) @AutoConfigureMockMvc -@TestPropertySource(properties = {"security.basic.enabled=false"}) +@TestPropertySource(properties = { "security.basic.enabled=false" }) public class SpringBootWithoutServletComponentIntegrationTest { @Autowired @@ -50,5 +50,3 @@ public class SpringBootWithoutServletComponentIntegrationTest { } } - - diff --git a/spring-boot/src/test/java/com/baeldung/autoconfiguration/AutoconfigurationIntegrationTest.java b/spring-boot/src/test/java/com/baeldung/autoconfiguration/AutoconfigurationIntegrationTest.java index e886042c8d..30ba397b46 100644 --- a/spring-boot/src/test/java/com/baeldung/autoconfiguration/AutoconfigurationIntegrationTest.java +++ b/spring-boot/src/test/java/com/baeldung/autoconfiguration/AutoconfigurationIntegrationTest.java @@ -12,7 +12,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = AutoconfigurationApplication.class) -@EnableJpaRepositories(basePackages = {"com.baeldung.autoconfiguration.example"}) +@EnableJpaRepositories(basePackages = { "com.baeldung.autoconfiguration.example" }) public class AutoconfigurationIntegrationTest { @Autowired diff --git a/spring-boot/src/test/java/com/baeldung/displayallbeans/DisplayBeanIntegrationTest.java b/spring-boot/src/test/java/com/baeldung/displayallbeans/DisplayBeanIntegrationTest.java index 413f6980ce..8bd9c20c5e 100644 --- a/spring-boot/src/test/java/com/baeldung/displayallbeans/DisplayBeanIntegrationTest.java +++ b/spring-boot/src/test/java/com/baeldung/displayallbeans/DisplayBeanIntegrationTest.java @@ -25,7 +25,7 @@ import static org.junit.Assert.assertTrue; @RunWith(SpringRunner.class) @SpringBootTest(classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) -@TestPropertySource(properties = {"management.port=0", "endpoints.beans.id=springbeans", "endpoints.beans.sensitive=false"}) +@TestPropertySource(properties = { "management.port=0", "endpoints.beans.id=springbeans", "endpoints.beans.sensitive=false" }) public class DisplayBeanIntegrationTest { @LocalServerPort @@ -42,8 +42,7 @@ public class DisplayBeanIntegrationTest { @Test public void givenRestTemplate_whenAccessServerUrl_thenHttpStatusOK() throws Exception { - ResponseEntity entity = this.testRestTemplate.getForEntity( - "http://localhost:" + this.port + "/displayallbeans", String.class); + ResponseEntity entity = this.testRestTemplate.getForEntity("http://localhost:" + this.port + "/displayallbeans", String.class); then(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @@ -51,8 +50,7 @@ public class DisplayBeanIntegrationTest { @Test public void givenRestTemplate_whenAccessEndpointUrl_thenHttpStatusOK() throws Exception { @SuppressWarnings("rawtypes") - ResponseEntity entity = this.testRestTemplate.getForEntity( - "http://localhost:" + this.mgt + "/springbeans", List.class); + ResponseEntity entity = this.testRestTemplate.getForEntity("http://localhost:" + this.mgt + "/springbeans", List.class); then(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @@ -60,11 +58,13 @@ public class DisplayBeanIntegrationTest { @Test public void givenRestTemplate_whenAccessEndpointUrl_thenReturnsBeanNames() throws Exception { @SuppressWarnings("rawtypes") - ResponseEntity entity = this.testRestTemplate.getForEntity( - "http://localhost:" + this.mgt + "/springbeans", List.class); + ResponseEntity entity = this.testRestTemplate.getForEntity("http://localhost:" + this.mgt + "/springbeans", List.class); - List> allBeans = (List) ((Map) entity.getBody().get(0)).get("beans"); - List beanNamesList = allBeans.stream().map(x -> (String) x.get("bean")).collect(Collectors.toList()); + List> allBeans = (List) ((Map) entity.getBody() + .get(0)).get("beans"); + List beanNamesList = allBeans.stream() + .map(x -> (String) x.get("bean")) + .collect(Collectors.toList()); assertThat(beanNamesList, hasItem("fooController")); assertThat(beanNamesList, hasItem("fooService")); diff --git a/spring-boot/src/test/java/com/baeldung/intro/AppLiveTest.java b/spring-boot/src/test/java/com/baeldung/intro/AppLiveTest.java index fa05dbab66..4856c17c7d 100644 --- a/spring-boot/src/test/java/com/baeldung/intro/AppLiveTest.java +++ b/spring-boot/src/test/java/com/baeldung/intro/AppLiveTest.java @@ -18,7 +18,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @RunWith(SpringRunner.class) @SpringBootTest @AutoConfigureMockMvc -@TestPropertySource(properties = {"security.basic.enabled=false"}) +@TestPropertySource(properties = { "security.basic.enabled=false" }) public class AppLiveTest { @Autowired @@ -26,16 +26,18 @@ public class AppLiveTest { @Test public void getIndex() throws Exception { - mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andExpect(content().string(equalTo("Index Page"))); + mvc.perform(MockMvcRequestBuilders.get("/") + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(content().string(equalTo("Index Page"))); } @Test public void getLocal() throws Exception { - mvc.perform(MockMvcRequestBuilders.get("/local").accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andExpect(content().string(equalTo("/local"))); + mvc.perform(MockMvcRequestBuilders.get("/local") + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(content().string(equalTo("/local"))); } } \ No newline at end of file diff --git a/spring-boot/src/test/java/com/baeldung/toggle/ToggleIntegrationTest.java b/spring-boot/src/test/java/com/baeldung/toggle/ToggleIntegrationTest.java index ca6230e8f5..5b70fa3cbe 100644 --- a/spring-boot/src/test/java/com/baeldung/toggle/ToggleIntegrationTest.java +++ b/spring-boot/src/test/java/com/baeldung/toggle/ToggleIntegrationTest.java @@ -35,7 +35,8 @@ public class ToggleIntegrationTest { @Before public void setup() { - this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); + this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac) + .build(); } @Test @@ -45,7 +46,8 @@ public class ToggleIntegrationTest { System.setProperty("employee.feature", "false"); - mockMvc.perform(post("/increaseSalary").param("id", emp.getId() + "")).andExpect(status().is(200)); + mockMvc.perform(post("/increaseSalary").param("id", emp.getId() + "")) + .andExpect(status().is(200)); emp = employeeRepository.findOne(1L); assertEquals("salary incorrect", 2000, emp.getSalary(), 0.5); @@ -58,7 +60,8 @@ public class ToggleIntegrationTest { System.setProperty("employee.feature", "true"); - mockMvc.perform(post("/increaseSalary").param("id", emp.getId() + "")).andExpect(status().is(200)); + mockMvc.perform(post("/increaseSalary").param("id", emp.getId() + "")) + .andExpect(status().is(200)); emp = employeeRepository.findOne(1L); assertEquals("salary incorrect", 2200, emp.getSalary(), 0.5); diff --git a/spring-boot/src/test/java/com/baeldung/utils/UtilsControllerIntegrationTest.java b/spring-boot/src/test/java/com/baeldung/utils/UtilsControllerIntegrationTest.java index edb40e9a1f..5a80e13791 100644 --- a/spring-boot/src/test/java/com/baeldung/utils/UtilsControllerIntegrationTest.java +++ b/spring-boot/src/test/java/com/baeldung/utils/UtilsControllerIntegrationTest.java @@ -22,18 +22,16 @@ public class UtilsControllerIntegrationTest { public void setup() { MockitoAnnotations.initMocks(this); this.mockMvc = MockMvcBuilders.standaloneSetup(utilsController) - .build(); + .build(); } @Test public void givenParameter_setRequestParam_andSetSessionAttribute() throws Exception { String param = "testparam"; - this.mockMvc.perform( - post("/setParam") - .param("param", param) + this.mockMvc.perform(post("/setParam").param("param", param) .sessionAttr("parameter", param)) - .andExpect(status().isOk()); + .andExpect(status().isOk()); } } diff --git a/spring-boot/src/test/java/com/baeldung/websocket/client/MyStompSessionHandlerIntegrationTest.java b/spring-boot/src/test/java/com/baeldung/websocket/client/MyStompSessionHandlerIntegrationTest.java index b52ab5b1d3..4dc4793ce2 100644 --- a/spring-boot/src/test/java/com/baeldung/websocket/client/MyStompSessionHandlerIntegrationTest.java +++ b/spring-boot/src/test/java/com/baeldung/websocket/client/MyStompSessionHandlerIntegrationTest.java @@ -14,8 +14,9 @@ public class MyStompSessionHandlerIntegrationTest { StompHeaders mockHeader = Mockito.mock(StompHeaders.class); MyStompSessionHandler sessionHandler = new MyStompSessionHandler(); sessionHandler.afterConnected(mockSession, mockHeader); - Mockito.verify(mockSession).subscribe("/topic/messages", sessionHandler); - Mockito.verify(mockSession).send(Mockito.anyString(), Mockito.anyObject()); + Mockito.verify(mockSession) + .subscribe("/topic/messages", sessionHandler); + Mockito.verify(mockSession) + .send(Mockito.anyString(), Mockito.anyObject()); } } - diff --git a/spring-boot/src/test/java/org/baeldung/SpringBootApplicationIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/SpringBootApplicationIntegrationTest.java index c5cca3c5fb..358ba942d9 100644 --- a/spring-boot/src/test/java/org/baeldung/SpringBootApplicationIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/SpringBootApplicationIntegrationTest.java @@ -33,36 +33,56 @@ public class SpringBootApplicationIntegrationTest { @Before public void setupMockMvc() { - mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); + mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext) + .build(); } @Test public void givenRequestHasBeenMade_whenMeetsAllOfGivenConditions_thenCorrect() throws Exception { MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8")); - mockMvc.perform(MockMvcRequestBuilders.get("/entity/all")).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType(contentType)).andExpect(jsonPath("$", hasSize(4))); + mockMvc.perform(MockMvcRequestBuilders.get("/entity/all")) + .andExpect(MockMvcResultMatchers.status() + .isOk()) + .andExpect(MockMvcResultMatchers.content() + .contentType(contentType)) + .andExpect(jsonPath("$", hasSize(4))); } @Test public void givenRequestHasBeenMade_whenMeetsFindByDateOfGivenConditions_thenCorrect() throws Exception { MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8")); - mockMvc.perform(MockMvcRequestBuilders.get("/entity/findbydate/{date}", "2011-12-03T10:15:30")).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType(contentType)) - .andExpect(jsonPath("$.id", equalTo(1))); + mockMvc.perform(MockMvcRequestBuilders.get("/entity/findbydate/{date}", "2011-12-03T10:15:30")) + .andExpect(MockMvcResultMatchers.status() + .isOk()) + .andExpect(MockMvcResultMatchers.content() + .contentType(contentType)) + .andExpect(jsonPath("$.id", equalTo(1))); } @Test public void givenRequestHasBeenMade_whenMeetsFindByModeOfGivenConditions_thenCorrect() throws Exception { MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8")); - mockMvc.perform(MockMvcRequestBuilders.get("/entity/findbymode/{mode}", Modes.ALPHA.name())).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType(contentType)).andExpect(jsonPath("$.id", equalTo(1))); + mockMvc.perform(MockMvcRequestBuilders.get("/entity/findbymode/{mode}", Modes.ALPHA.name())) + .andExpect(MockMvcResultMatchers.status() + .isOk()) + .andExpect(MockMvcResultMatchers.content() + .contentType(contentType)) + .andExpect(jsonPath("$.id", equalTo(1))); } @Test public void givenRequestHasBeenMade_whenMeetsFindByVersionOfGivenConditions_thenCorrect() throws Exception { MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8")); - mockMvc.perform(MockMvcRequestBuilders.get("/entity/findbyversion").header("Version", "1.0.0")).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType(contentType)) - .andExpect(jsonPath("$.id", equalTo(1))); + mockMvc.perform(MockMvcRequestBuilders.get("/entity/findbyversion") + .header("Version", "1.0.0")) + .andExpect(MockMvcResultMatchers.status() + .isOk()) + .andExpect(MockMvcResultMatchers.content() + .contentType(contentType)) + .andExpect(jsonPath("$.id", equalTo(1))); } } \ No newline at end of file diff --git a/spring-boot/src/test/java/org/baeldung/SpringBootMailIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/SpringBootMailIntegrationTest.java index 10e3d6d60b..0e8a698f41 100644 --- a/spring-boot/src/test/java/org/baeldung/SpringBootMailIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/SpringBootMailIntegrationTest.java @@ -62,11 +62,15 @@ public class SpringBootMailIntegrationTest { } private String getMessage(WiserMessage wiserMessage) throws MessagingException, IOException { - return wiserMessage.getMimeMessage().getContent().toString().trim(); + return wiserMessage.getMimeMessage() + .getContent() + .toString() + .trim(); } private String getSubject(WiserMessage wiserMessage) throws MessagingException { - return wiserMessage.getMimeMessage().getSubject(); + return wiserMessage.getMimeMessage() + .getSubject(); } private SimpleMailMessage composeEmailMessage() { diff --git a/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeControllerIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeControllerIntegrationTest.java index 6623a6396f..2146fc09bc 100644 --- a/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeControllerIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeControllerIntegrationTest.java @@ -45,9 +45,9 @@ public class EmployeeControllerIntegrationTest { given(service.save(Mockito.anyObject())).willReturn(alex); mvc.perform(post("/api/employees").contentType(MediaType.APPLICATION_JSON) - .content(JsonUtil.toJson(alex))) - .andExpect(status().isCreated()) - .andExpect(jsonPath("$.name", is("alex"))); + .content(JsonUtil.toJson(alex))) + .andExpect(status().isCreated()) + .andExpect(jsonPath("$.name", is("alex"))); verify(service, VerificationModeFactory.times(1)).save(Mockito.anyObject()); reset(service); } @@ -63,11 +63,11 @@ public class EmployeeControllerIntegrationTest { given(service.getAllEmployees()).willReturn(allEmployees); mvc.perform(get("/api/employees").contentType(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andExpect(jsonPath("$", hasSize(3))) - .andExpect(jsonPath("$[0].name", is(alex.getName()))) - .andExpect(jsonPath("$[1].name", is(john.getName()))) - .andExpect(jsonPath("$[2].name", is(bob.getName()))); + .andExpect(status().isOk()) + .andExpect(jsonPath("$", hasSize(3))) + .andExpect(jsonPath("$[0].name", is(alex.getName()))) + .andExpect(jsonPath("$[1].name", is(john.getName()))) + .andExpect(jsonPath("$[2].name", is(bob.getName()))); verify(service, VerificationModeFactory.times(1)).getAllEmployees(); reset(service); } diff --git a/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeRepositoryIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeRepositoryIntegrationTest.java index 952ff19707..ebde0e243a 100644 --- a/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeRepositoryIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeRepositoryIntegrationTest.java @@ -65,7 +65,7 @@ public class EmployeeRepositoryIntegrationTest { List allEmployees = employeeRepository.findAll(); assertThat(allEmployees).hasSize(3) - .extracting(Employee::getName) - .containsOnly(alex.getName(), ron.getName(), bob.getName()); + .extracting(Employee::getName) + .containsOnly(alex.getName(), ron.getName(), bob.getName()); } } diff --git a/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeRestControllerIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeRestControllerIntegrationTest.java index c1d8c52eb9..9e5613ab10 100644 --- a/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeRestControllerIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeRestControllerIntegrationTest.java @@ -49,11 +49,11 @@ public class EmployeeRestControllerIntegrationTest { public void whenValidInput_thenCreateEmployee() throws IOException, Exception { Employee bob = new Employee("bob"); mvc.perform(post("/api/employees").contentType(MediaType.APPLICATION_JSON) - .content(JsonUtil.toJson(bob))); + .content(JsonUtil.toJson(bob))); List found = repository.findAll(); assertThat(found).extracting(Employee::getName) - .containsOnly("bob"); + .containsOnly("bob"); } @Test @@ -63,12 +63,12 @@ public class EmployeeRestControllerIntegrationTest { createTestEmployee("alex"); mvc.perform(get("/api/employees").contentType(MediaType.APPLICATION_JSON)) - .andDo(print()) - .andExpect(status().isOk()) - .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) - .andExpect(jsonPath("$", hasSize(greaterThanOrEqualTo(2)))) - .andExpect(jsonPath("$[0].name", is("bob"))) - .andExpect(jsonPath("$[1].name", is("alex"))); + .andDo(print()) + .andExpect(status().isOk()) + .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) + .andExpect(jsonPath("$", hasSize(greaterThanOrEqualTo(2)))) + .andExpect(jsonPath("$[0].name", is("bob"))) + .andExpect(jsonPath("$[1].name", is("alex"))); } private void createTestEmployee(String name) { diff --git a/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeServiceImplIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeServiceImplIntegrationTest.java index 5bd6b34c40..9837b02df6 100644 --- a/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeServiceImplIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeServiceImplIntegrationTest.java @@ -44,17 +44,17 @@ public class EmployeeServiceImplIntegrationTest { List allEmployees = Arrays.asList(john, bob, alex); Mockito.when(employeeRepository.findByName(john.getName())) - .thenReturn(john); + .thenReturn(john); Mockito.when(employeeRepository.findByName(alex.getName())) - .thenReturn(alex); + .thenReturn(alex); Mockito.when(employeeRepository.findByName("wrong_name")) - .thenReturn(null); + .thenReturn(null); Mockito.when(employeeRepository.findById(john.getId())) - .thenReturn(john); + .thenReturn(john); Mockito.when(employeeRepository.findAll()) - .thenReturn(allEmployees); + .thenReturn(allEmployees); Mockito.when(employeeRepository.findById(-99L)) - .thenReturn(null); + .thenReturn(null); } @Test @@ -62,8 +62,7 @@ public class EmployeeServiceImplIntegrationTest { String name = "alex"; Employee found = employeeService.getEmployeeByName(name); - assertThat(found.getName()) - .isEqualTo(name); + assertThat(found.getName()).isEqualTo(name); } @Test @@ -114,25 +113,25 @@ public class EmployeeServiceImplIntegrationTest { List allEmployees = employeeService.getAllEmployees(); verifyFindAllEmployeesIsCalledOnce(); assertThat(allEmployees).hasSize(3) - .extracting(Employee::getName) - .contains(alex.getName(), john.getName(), bob.getName()); + .extracting(Employee::getName) + .contains(alex.getName(), john.getName(), bob.getName()); } private void verifyFindByNameIsCalledOnce(String name) { Mockito.verify(employeeRepository, VerificationModeFactory.times(1)) - .findByName(name); + .findByName(name); Mockito.reset(employeeRepository); } private void verifyFindByIdIsCalledOnce() { Mockito.verify(employeeRepository, VerificationModeFactory.times(1)) - .findById(Mockito.anyLong()); + .findById(Mockito.anyLong()); Mockito.reset(employeeRepository); } private void verifyFindAllEmployeesIsCalledOnce() { Mockito.verify(employeeRepository, VerificationModeFactory.times(1)) - .findAll(); + .findAll(); Mockito.reset(employeeRepository); } } diff --git a/spring-boot/src/test/java/org/baeldung/client/DetailsServiceClientIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/client/DetailsServiceClientIntegrationTest.java index 5627855aa3..0f6c13ae1f 100644 --- a/spring-boot/src/test/java/org/baeldung/client/DetailsServiceClientIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/client/DetailsServiceClientIntegrationTest.java @@ -30,7 +30,8 @@ public class DetailsServiceClientIntegrationTest { @Before public void setUp() throws Exception { String detailsString = objectMapper.writeValueAsString(new Details("John Smith", "john")); - this.server.expect(requestTo("/john/details")).andRespond(withSuccess(detailsString, MediaType.APPLICATION_JSON)); + this.server.expect(requestTo("/john/details")) + .andRespond(withSuccess(detailsString, MediaType.APPLICATION_JSON)); } @Test diff --git a/spring-boot/src/test/java/org/baeldung/jsoncomponent/UserJsonSerializerIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/jsoncomponent/UserJsonSerializerIntegrationTest.java index c1b4c8912c..ac47c5e5d9 100644 --- a/spring-boot/src/test/java/org/baeldung/jsoncomponent/UserJsonSerializerIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/jsoncomponent/UserJsonSerializerIntegrationTest.java @@ -1,6 +1,5 @@ package org.baeldung.jsoncomponent; - import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import javafx.scene.paint.Color; diff --git a/spring-security-mvc-login/src/main/java/org/baeldung/security/CustomAccessDeniedHandler.java b/spring-security-mvc-login/src/main/java/org/baeldung/security/CustomAccessDeniedHandler.java index 843f5f4dcd..64698072bc 100644 --- a/spring-security-mvc-login/src/main/java/org/baeldung/security/CustomAccessDeniedHandler.java +++ b/spring-security-mvc-login/src/main/java/org/baeldung/security/CustomAccessDeniedHandler.java @@ -25,7 +25,7 @@ public class CustomAccessDeniedHandler implements AccessDeniedHandler { if (auth != null) { LOG.warn("User: " + auth.getName() + " attempted to access the protected URL: " + request.getRequestURI()); } - + response.sendRedirect(request.getContextPath() + "/accessDenied"); } diff --git a/spring-security-mvc-login/src/main/java/org/baeldung/spring/SecSecurityConfig.java b/spring-security-mvc-login/src/main/java/org/baeldung/spring/SecSecurityConfig.java index 7331d7bb18..d9a43d48d0 100644 --- a/spring-security-mvc-login/src/main/java/org/baeldung/spring/SecSecurityConfig.java +++ b/spring-security-mvc-login/src/main/java/org/baeldung/spring/SecSecurityConfig.java @@ -65,9 +65,9 @@ public class SecSecurityConfig extends WebSecurityConfigurerAdapter { public LogoutSuccessHandler logoutSuccessHandler() { return new CustomLogoutSuccessHandler(); } - + @Bean - public AccessDeniedHandler accessDeniedHandler(){ + public AccessDeniedHandler accessDeniedHandler() { return new CustomAccessDeniedHandler(); } diff --git a/spring-security-mvc-login/src/test/java/org/baeldung/security/RedirectionSecurityIntegrationTest.java b/spring-security-mvc-login/src/test/java/org/baeldung/security/RedirectionSecurityIntegrationTest.java index 1d7fae8b60..2b7a8ce5b9 100644 --- a/spring-security-mvc-login/src/test/java/org/baeldung/security/RedirectionSecurityIntegrationTest.java +++ b/spring-security-mvc-login/src/test/java/org/baeldung/security/RedirectionSecurityIntegrationTest.java @@ -29,65 +29,58 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @WebAppConfiguration public class RedirectionSecurityIntegrationTest { - @Autowired private WebApplicationContext context; + @Autowired + private WebApplicationContext context; - @Autowired private UserDetailsService userDetailsService; + @Autowired + private UserDetailsService userDetailsService; private MockMvc mvc; private UserDetails userDetails; @Before public void setup() { - mvc = MockMvcBuilders - .webAppContextSetup(context) - .apply(springSecurity()) - .build(); + mvc = MockMvcBuilders.webAppContextSetup(context) + .apply(springSecurity()) + .build(); userDetails = userDetailsService.loadUserByUsername("user1"); } @Test public void givenSecuredResource_whenAccessUnauthenticated_thenRequiresAuthentication() throws Exception { - mvc - .perform(get("/secured")) - .andExpect(status().is3xxRedirection()) - .andExpect(redirectedUrlPattern("**/login")); + mvc.perform(get("/secured")) + .andExpect(status().is3xxRedirection()) + .andExpect(redirectedUrlPattern("**/login")); } @Test public void givenCredentials_whenAccessSecuredResource_thenSuccess() throws Exception { - mvc - .perform(get("/secured").with(user(userDetails))) - .andExpect(status().isOk()); + mvc.perform(get("/secured").with(user(userDetails))) + .andExpect(status().isOk()); } @Test public void givenAccessSecuredResource_whenAuthenticated_thenRedirectedBack() throws Exception { MockHttpServletRequestBuilder securedResourceAccess = get("/secured"); - MvcResult unauthenticatedResult = mvc - .perform(securedResourceAccess) - .andExpect(status().is3xxRedirection()) - .andReturn(); + MvcResult unauthenticatedResult = mvc.perform(securedResourceAccess) + .andExpect(status().is3xxRedirection()) + .andReturn(); - MockHttpSession session = (MockHttpSession) unauthenticatedResult - .getRequest() - .getSession(); - String loginUrl = unauthenticatedResult - .getResponse() - .getRedirectedUrl(); - mvc - .perform(post(loginUrl) - .param("username", userDetails.getUsername()) + MockHttpSession session = (MockHttpSession) unauthenticatedResult.getRequest() + .getSession(); + String loginUrl = unauthenticatedResult.getResponse() + .getRedirectedUrl(); + mvc.perform(post(loginUrl).param("username", userDetails.getUsername()) .param("password", userDetails.getPassword()) .session(session) .with(csrf())) - .andExpect(status().is3xxRedirection()) - .andExpect(redirectedUrlPattern("**/secured")) - .andReturn(); + .andExpect(status().is3xxRedirection()) + .andExpect(redirectedUrlPattern("**/secured")) + .andReturn(); - mvc - .perform(securedResourceAccess.session(session)) - .andExpect(status().isOk()); + mvc.perform(securedResourceAccess.session(session)) + .andExpect(status().isOk()); }