diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/blockingqueue/NumbersProducer.java b/core-java-concurrency/src/main/java/com/baeldung/concurrent/blockingqueue/NumbersProducer.java index 9dcd0a3e47..b301e994d5 100644 --- a/core-java-concurrency/src/main/java/com/baeldung/concurrent/blockingqueue/NumbersProducer.java +++ b/core-java-concurrency/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-concurrency/src/main/java/com/baeldung/concurrent/delayqueue/DelayObject.java b/core-java-concurrency/src/main/java/com/baeldung/concurrent/delayqueue/DelayObject.java index 5f72758e71..312eb929ed 100644 --- a/core-java-concurrency/src/main/java/com/baeldung/concurrent/delayqueue/DelayObject.java +++ b/core-java-concurrency/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-concurrency/src/test/java/com/baeldung/completablefuture/CompletableFutureLongRunningUnitTest.java b/core-java-concurrency/src/test/java/com/baeldung/completablefuture/CompletableFutureLongRunningUnitTest.java index 0c3a13d176..0a6d94e126 100644 --- a/core-java-concurrency/src/test/java/com/baeldung/completablefuture/CompletableFutureLongRunningUnitTest.java +++ b/core-java-concurrency/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-concurrency/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapAggregateStatusManualTest.java b/core-java-concurrency/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapAggregateStatusManualTest.java index ec865f71c4..2971f14c41 100644 --- a/core-java-concurrency/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapAggregateStatusManualTest.java +++ b/core-java-concurrency/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-concurrency/src/test/java/com/baeldung/java/concurrentmap/ConcurretMapMemoryConsistencyManualTest.java b/core-java-concurrency/src/test/java/com/baeldung/java/concurrentmap/ConcurretMapMemoryConsistencyManualTest.java index 43cbb2d293..e4fac66fe3 100644 --- a/core-java-concurrency/src/test/java/com/baeldung/java/concurrentmap/ConcurretMapMemoryConsistencyManualTest.java +++ b/core-java-concurrency/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/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/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/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/com/baeldung/string/CharSequenceVsStringUnitTest.java b/core-java/src/test/java/com/baeldung/string/CharSequenceVsStringUnitTest.java index 1378b5d876..916a3c79ff 100644 --- a/core-java/src/test/java/com/baeldung/string/CharSequenceVsStringUnitTest.java +++ b/core-java/src/test/java/com/baeldung/string/CharSequenceVsStringUnitTest.java @@ -21,7 +21,7 @@ public class CharSequenceVsStringUnitTest { CharSequence charSequence1 = "baeldung_1"; CharSequence charSequence2 = "baeldung_2"; - assertTrue(charSequence1.toString().compareTo(charSequence2.toString()) > 0); + assertTrue(charSequence1.toString().compareTo(charSequence2.toString()) < 0); } @Test @@ -31,7 +31,7 @@ public class CharSequenceVsStringUnitTest { test += "b"; int secondAddressOfTest = System.identityHashCode(test); - assertEquals(firstAddressOfTest, secondAddressOfTest); + assertNotEquals(firstAddressOfTest, secondAddressOfTest); } @Test 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/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/config/JWTCsrfTokenRepository.java b/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/config/JWTCsrfTokenRepository.java index bf88b8aff1..4462c012e3 100644 --- a/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/config/JWTCsrfTokenRepository.java +++ b/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/config/JWTCsrfTokenRepository.java @@ -16,7 +16,8 @@ import java.util.UUID; public class JWTCsrfTokenRepository implements CsrfTokenRepository { - private static final String DEFAULT_CSRF_TOKEN_ATTR_NAME = CSRFConfig.class.getName().concat(".CSRF_TOKEN"); + private static final String DEFAULT_CSRF_TOKEN_ATTR_NAME = CSRFConfig.class.getName() + .concat(".CSRF_TOKEN"); private static final Logger log = LoggerFactory.getLogger(JWTCsrfTokenRepository.class); private byte[] secret; @@ -27,10 +28,12 @@ public class JWTCsrfTokenRepository implements CsrfTokenRepository { @Override public CsrfToken generateToken(HttpServletRequest request) { - String id = UUID.randomUUID().toString().replace("-", ""); + String id = UUID.randomUUID() + .toString() + .replace("-", ""); Date now = new Date(); - Date exp = new Date(System.currentTimeMillis() + (1000*30)); // 30 seconds + Date exp = new Date(System.currentTimeMillis() + (1000 * 30)); // 30 seconds String token = Jwts.builder() .setId(id) @@ -50,8 +53,7 @@ public class JWTCsrfTokenRepository implements CsrfTokenRepository { if (session != null) { session.removeAttribute(DEFAULT_CSRF_TOKEN_ATTR_NAME); } - } - else { + } else { HttpSession session = request.getSession(); session.setAttribute(DEFAULT_CSRF_TOKEN_ATTR_NAME, token); } diff --git a/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/config/WebSecurityConfig.java b/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/config/WebSecurityConfig.java index 94e2c6ddc5..687a827448 100644 --- a/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/config/WebSecurityConfig.java +++ b/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/config/WebSecurityConfig.java @@ -30,23 +30,18 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter { SecretService secretService; // ordered so we can use binary search below - private String[] ignoreCsrfAntMatchers = { - "/dynamic-builder-compress", - "/dynamic-builder-general", - "/dynamic-builder-specific", - "/set-secrets" - }; + private String[] ignoreCsrfAntMatchers = { "/dynamic-builder-compress", "/dynamic-builder-general", "/dynamic-builder-specific", "/set-secrets" }; @Override protected void configure(HttpSecurity http) throws Exception { - http - .addFilterAfter(new JwtCsrfValidatorFilter(), CsrfFilter.class) + http.addFilterAfter(new JwtCsrfValidatorFilter(), CsrfFilter.class) .csrf() - .csrfTokenRepository(jwtCsrfTokenRepository) - .ignoringAntMatchers(ignoreCsrfAntMatchers) - .and().authorizeRequests() - .antMatchers("/**") - .permitAll(); + .csrfTokenRepository(jwtCsrfTokenRepository) + .ignoringAntMatchers(ignoreCsrfAntMatchers) + .and() + .authorizeRequests() + .antMatchers("/**") + .permitAll(); } private class JwtCsrfValidatorFilter extends OncePerRequestFilter { @@ -58,13 +53,12 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter { CsrfToken token = (CsrfToken) request.getAttribute("_csrf"); if ( - // only care if it's a POST - "POST".equals(request.getMethod()) && - // ignore if the request path is in our list + // only care if it's a POST + "POST".equals(request.getMethod()) && + // ignore if the request path is in our list Arrays.binarySearch(ignoreCsrfAntMatchers, request.getServletPath()) < 0 && // make sure we have a token - token != null - ) { + token != null) { // CsrfFilter already made sure the token matched. Here, we'll make sure it's not expired try { Jwts.parser() diff --git a/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/controller/BaseController.java b/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/controller/BaseController.java index e1e195c6ab..3e2309d43c 100644 --- a/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/controller/BaseController.java +++ b/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/controller/BaseController.java @@ -11,12 +11,13 @@ import org.springframework.web.bind.annotation.ResponseStatus; public class BaseController { @ResponseStatus(HttpStatus.BAD_REQUEST) - @ExceptionHandler({SignatureException.class, MalformedJwtException.class, JwtException.class}) + @ExceptionHandler({ SignatureException.class, MalformedJwtException.class, JwtException.class }) public JwtResponse exception(Exception e) { JwtResponse response = new JwtResponse(); response.setStatus(JwtResponse.Status.ERROR); response.setMessage(e.getMessage()); - response.setExceptionType(e.getClass().getName()); + response.setExceptionType(e.getClass() + .getName()); return response; } diff --git a/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/controller/DynamicJWTController.java b/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/controller/DynamicJWTController.java index c03c63dd80..3d157827d1 100644 --- a/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/controller/DynamicJWTController.java +++ b/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/controller/DynamicJWTController.java @@ -27,25 +27,19 @@ public class DynamicJWTController extends BaseController { @RequestMapping(value = "/dynamic-builder-general", method = POST) public JwtResponse dynamicBuilderGeneric(@RequestBody Map claims) throws UnsupportedEncodingException { - String jws = Jwts.builder() + String jws = Jwts.builder() .setClaims(claims) - .signWith( - SignatureAlgorithm.HS256, - secretService.getHS256SecretBytes() - ) + .signWith(SignatureAlgorithm.HS256, secretService.getHS256SecretBytes()) .compact(); return new JwtResponse(jws); } @RequestMapping(value = "/dynamic-builder-compress", method = POST) public JwtResponse dynamicBuildercompress(@RequestBody Map claims) throws UnsupportedEncodingException { - String jws = Jwts.builder() + String jws = Jwts.builder() .setClaims(claims) .compressWith(CompressionCodecs.DEFLATE) - .signWith( - SignatureAlgorithm.HS256, - secretService.getHS256SecretBytes() - ) + .signWith(SignatureAlgorithm.HS256, secretService.getHS256SecretBytes()) .compact(); return new JwtResponse(jws); } @@ -56,36 +50,36 @@ public class DynamicJWTController extends BaseController { claims.forEach((key, value) -> { switch (key) { - case "iss": - ensureType(key, value, String.class); - builder.setIssuer((String) value); - break; - case "sub": - ensureType(key, value, String.class); - builder.setSubject((String) value); - break; - case "aud": - ensureType(key, value, String.class); - builder.setAudience((String) value); - break; - case "exp": - ensureType(key, value, Long.class); - builder.setExpiration(Date.from(Instant.ofEpochSecond(Long.parseLong(value.toString())))); - break; - case "nbf": - ensureType(key, value, Long.class); - builder.setNotBefore(Date.from(Instant.ofEpochSecond(Long.parseLong(value.toString())))); - break; - case "iat": - ensureType(key, value, Long.class); - builder.setIssuedAt(Date.from(Instant.ofEpochSecond(Long.parseLong(value.toString())))); - break; - case "jti": - ensureType(key, value, String.class); - builder.setId((String) value); - break; - default: - builder.claim(key, value); + case "iss": + ensureType(key, value, String.class); + builder.setIssuer((String) value); + break; + case "sub": + ensureType(key, value, String.class); + builder.setSubject((String) value); + break; + case "aud": + ensureType(key, value, String.class); + builder.setAudience((String) value); + break; + case "exp": + ensureType(key, value, Long.class); + builder.setExpiration(Date.from(Instant.ofEpochSecond(Long.parseLong(value.toString())))); + break; + case "nbf": + ensureType(key, value, Long.class); + builder.setNotBefore(Date.from(Instant.ofEpochSecond(Long.parseLong(value.toString())))); + break; + case "iat": + ensureType(key, value, Long.class); + builder.setIssuedAt(Date.from(Instant.ofEpochSecond(Long.parseLong(value.toString())))); + break; + case "jti": + ensureType(key, value, String.class); + builder.setId((String) value); + break; + default: + builder.claim(key, value); } }); @@ -95,13 +89,11 @@ public class DynamicJWTController extends BaseController { } private void ensureType(String registeredClaim, Object value, Class expectedType) { - boolean isCorrectType = - expectedType.isInstance(value) || - expectedType == Long.class && value instanceof Integer; + boolean isCorrectType = expectedType.isInstance(value) || expectedType == Long.class && value instanceof Integer; if (!isCorrectType) { - String msg = "Expected type: " + expectedType.getCanonicalName() + " for registered claim: '" + - registeredClaim + "', but got value: " + value + " of type: " + value.getClass().getCanonicalName(); + String msg = "Expected type: " + expectedType.getCanonicalName() + " for registered claim: '" + registeredClaim + "', but got value: " + value + " of type: " + value.getClass() + .getCanonicalName(); throw new JwtException(msg); } } diff --git a/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/controller/HomeController.java b/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/controller/HomeController.java index 57cd14385e..00bc1fb386 100644 --- a/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/controller/HomeController.java +++ b/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/controller/HomeController.java @@ -11,22 +11,16 @@ public class HomeController { @RequestMapping("/") public String home(HttpServletRequest req) { String requestUrl = getUrl(req); - return "Available commands (assumes httpie - https://github.com/jkbrzt/httpie):\n\n" + - " http " + requestUrl + "/\n\tThis usage message\n\n" + - " http " + requestUrl + "/static-builder\n\tbuild JWT from hardcoded claims\n\n" + - " http POST " + requestUrl + "/dynamic-builder-general claim-1=value-1 ... [claim-n=value-n]\n\tbuild JWT from passed in claims (using general claims map)\n\n" + - " http POST " + requestUrl + "/dynamic-builder-specific claim-1=value-1 ... [claim-n=value-n]\n\tbuild JWT from passed in claims (using specific claims methods)\n\n" + - " http POST " + requestUrl + "/dynamic-builder-compress claim-1=value-1 ... [claim-n=value-n]\n\tbuild DEFLATE compressed JWT from passed in claims\n\n" + - " http " + requestUrl + "/parser?jwt=\n\tParse passed in JWT\n\n" + - " http " + requestUrl + "/parser-enforce?jwt=\n\tParse passed in JWT enforcing the 'iss' registered claim and the 'hasMotorcycle' custom claim\n\n" + - " http " + requestUrl + "/get-secrets\n\tShow the signing keys currently in use.\n\n" + - " http " + requestUrl + "/refresh-secrets\n\tGenerate new signing keys and show them.\n\n" + - " http POST " + requestUrl + "/set-secrets HS256=base64-encoded-value HS384=base64-encoded-value HS512=base64-encoded-value\n\tExplicitly set secrets to use in the application."; + return "Available commands (assumes httpie - https://github.com/jkbrzt/httpie):\n\n" + " http " + requestUrl + "/\n\tThis usage message\n\n" + " http " + requestUrl + "/static-builder\n\tbuild JWT from hardcoded claims\n\n" + " http POST " + + requestUrl + "/dynamic-builder-general claim-1=value-1 ... [claim-n=value-n]\n\tbuild JWT from passed in claims (using general claims map)\n\n" + " http POST " + requestUrl + + "/dynamic-builder-specific claim-1=value-1 ... [claim-n=value-n]\n\tbuild JWT from passed in claims (using specific claims methods)\n\n" + " http POST " + requestUrl + + "/dynamic-builder-compress claim-1=value-1 ... [claim-n=value-n]\n\tbuild DEFLATE compressed JWT from passed in claims\n\n" + " http " + requestUrl + "/parser?jwt=\n\tParse passed in JWT\n\n" + " http " + requestUrl + + "/parser-enforce?jwt=\n\tParse passed in JWT enforcing the 'iss' registered claim and the 'hasMotorcycle' custom claim\n\n" + " http " + requestUrl + "/get-secrets\n\tShow the signing keys currently in use.\n\n" + " http " + requestUrl + + "/refresh-secrets\n\tGenerate new signing keys and show them.\n\n" + " http POST " + requestUrl + + "/set-secrets HS256=base64-encoded-value HS384=base64-encoded-value HS512=base64-encoded-value\n\tExplicitly set secrets to use in the application."; } private String getUrl(HttpServletRequest req) { - return req.getScheme() + "://" + - req.getServerName() + - ((req.getServerPort() == 80 || req.getServerPort() == 443) ? "" : ":" + req.getServerPort()); + return req.getScheme() + "://" + req.getServerName() + ((req.getServerPort() == 80 || req.getServerPort() == 443) ? "" : ":" + req.getServerPort()); } } diff --git a/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/controller/StaticJWTController.java b/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/controller/StaticJWTController.java index 83f5336978..efafa4b1b7 100644 --- a/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/controller/StaticJWTController.java +++ b/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/controller/StaticJWTController.java @@ -30,12 +30,9 @@ public class StaticJWTController extends BaseController { .setSubject("msilverman") .claim("name", "Micah Silverman") .claim("scope", "admins") - .setIssuedAt(Date.from(Instant.ofEpochSecond(1466796822L))) // Fri Jun 24 2016 15:33:42 GMT-0400 (EDT) + .setIssuedAt(Date.from(Instant.ofEpochSecond(1466796822L))) // Fri Jun 24 2016 15:33:42 GMT-0400 (EDT) .setExpiration(Date.from(Instant.ofEpochSecond(4622470422L))) // Sat Jun 24 2116 15:33:42 GMT-0400 (EDT) - .signWith( - SignatureAlgorithm.HS256, - secretService.getHS256SecretBytes() - ) + .signWith(SignatureAlgorithm.HS256, secretService.getHS256SecretBytes()) .compact(); return new JwtResponse(jws); diff --git a/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/model/JwtResponse.java b/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/model/JwtResponse.java index 491f003289..a18cad7e71 100644 --- a/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/model/JwtResponse.java +++ b/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/model/JwtResponse.java @@ -16,7 +16,8 @@ public class JwtResponse { SUCCESS, ERROR } - public JwtResponse() {} + public JwtResponse() { + } public JwtResponse(String jwt) { this.jwt = jwt; diff --git a/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/service/SecretService.java b/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/service/SecretService.java index 4311afa592..0165d10c83 100644 --- a/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/service/SecretService.java +++ b/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/service/SecretService.java @@ -61,7 +61,6 @@ public class SecretService { return TextCodec.BASE64.decode(secrets.get(SignatureAlgorithm.HS384.getValue())); } - public Map refreshSecrets() { SecretKey key = MacProvider.generateKey(SignatureAlgorithm.HS256); secrets.put(SignatureAlgorithm.HS256.getValue(), TextCodec.BASE64.encode(key.getEncoded())); diff --git a/jpa-storedprocedure/src/test/java/com/baeldung/jpa/storedprocedure/StoredProcedureIntegrationTest.java b/jpa-storedprocedure/src/test/java/com/baeldung/jpa/storedprocedure/StoredProcedureIntegrationTest.java index c93d59fe30..c0fb5485aa 100644 --- a/jpa-storedprocedure/src/test/java/com/baeldung/jpa/storedprocedure/StoredProcedureIntegrationTest.java +++ b/jpa-storedprocedure/src/test/java/com/baeldung/jpa/storedprocedure/StoredProcedureIntegrationTest.java @@ -50,13 +50,17 @@ public class StoredProcedureIntegrationTest { public void findCarsByYearNamedProcedure() { final StoredProcedureQuery findByYearProcedure = entityManager.createNamedStoredProcedureQuery("findByYearProcedure"); final StoredProcedureQuery storedProcedure = findByYearProcedure.setParameter("p_year", 2015); - storedProcedure.getResultList().forEach(c -> Assert.assertEquals(new Integer(2015), ((Car) c).getYear())); + storedProcedure.getResultList() + .forEach(c -> Assert.assertEquals(new Integer(2015), ((Car) c).getYear())); } @Test public void findCarsByYearNoNamed() { - final StoredProcedureQuery storedProcedure = entityManager.createStoredProcedureQuery("FIND_CAR_BY_YEAR", Car.class).registerStoredProcedureParameter(1, Integer.class, ParameterMode.IN).setParameter(1, 2015); - storedProcedure.getResultList().forEach(c -> Assert.assertEquals(new Integer(2015), ((Car) c).getYear())); + final StoredProcedureQuery storedProcedure = entityManager.createStoredProcedureQuery("FIND_CAR_BY_YEAR", Car.class) + .registerStoredProcedureParameter(1, Integer.class, ParameterMode.IN) + .setParameter(1, 2015); + storedProcedure.getResultList() + .forEach(c -> Assert.assertEquals(new Integer(2015), ((Car) c).getYear())); } @AfterClass diff --git a/jsf/src/main/java/com/baeldung/springintegration/controllers/ELSampleBean.java b/jsf/src/main/java/com/baeldung/springintegration/controllers/ELSampleBean.java index 16d9f80d89..abc1399f88 100644 --- a/jsf/src/main/java/com/baeldung/springintegration/controllers/ELSampleBean.java +++ b/jsf/src/main/java/com/baeldung/springintegration/controllers/ELSampleBean.java @@ -27,18 +27,22 @@ public class ELSampleBean { @PostConstruct public void init() { pageCounter = randomIntGen.nextInt(); - FacesContext.getCurrentInstance().getApplication().addELContextListener(new ELContextListener() { - @Override - public void contextCreated(ELContextEvent evt) { - evt.getELContext().getImportHandler().importClass("com.baeldung.springintegration.controllers.ELSampleBean"); - } - }); + FacesContext.getCurrentInstance() + .getApplication() + .addELContextListener(new ELContextListener() { + @Override + public void contextCreated(ELContextEvent evt) { + evt.getELContext() + .getImportHandler() + .importClass("com.baeldung.springintegration.controllers.ELSampleBean"); + } + }); } public void save() { } - + public static String constantField() { return constantField; } @@ -48,7 +52,8 @@ public class ELSampleBean { } public Long multiplyValue(LambdaExpression expr) { - Long theResult = (Long) expr.invoke(FacesContext.getCurrentInstance().getELContext(), pageCounter); + Long theResult = (Long) expr.invoke(FacesContext.getCurrentInstance() + .getELContext(), pageCounter); return theResult; } diff --git a/jsf/src/main/java/com/baeldung/springintegration/dao/UserManagementDAOImpl.java b/jsf/src/main/java/com/baeldung/springintegration/dao/UserManagementDAOImpl.java index 56cbdd7b88..d135fba2b7 100644 --- a/jsf/src/main/java/com/baeldung/springintegration/dao/UserManagementDAOImpl.java +++ b/jsf/src/main/java/com/baeldung/springintegration/dao/UserManagementDAOImpl.java @@ -1,6 +1,5 @@ package com.baeldung.springintegration.dao; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Repository; @@ -34,5 +33,4 @@ public class UserManagementDAOImpl implements UserManagementDAO { public UserManagementDAOImpl() { } - } diff --git a/json-path/src/test/java/com/baeldung/jsonpath/introduction/OperationIntegrationTest.java b/json-path/src/test/java/com/baeldung/jsonpath/introduction/OperationIntegrationTest.java index 855f524dbe..7728d2dad6 100644 --- a/json-path/src/test/java/com/baeldung/jsonpath/introduction/OperationIntegrationTest.java +++ b/json-path/src/test/java/com/baeldung/jsonpath/introduction/OperationIntegrationTest.java @@ -18,8 +18,11 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; public class OperationIntegrationTest { - private InputStream jsonInputStream = this.getClass().getClassLoader().getResourceAsStream("intro_api.json"); - private String jsonDataSourceString = new Scanner(jsonInputStream, "UTF-8").useDelimiter("\\Z").next(); + private InputStream jsonInputStream = this.getClass() + .getClassLoader() + .getResourceAsStream("intro_api.json"); + private String jsonDataSourceString = new Scanner(jsonInputStream, "UTF-8").useDelimiter("\\Z") + .next(); @Test public void givenJsonPathWithoutPredicates_whenReading_thenCorrect() { @@ -38,21 +41,27 @@ public class OperationIntegrationTest { @Test public void givenJsonPathWithFilterPredicate_whenReading_thenCorrect() { - Filter expensiveFilter = Filter.filter(Criteria.where("price").gt(20.00)); - List> expensive = JsonPath.parse(jsonDataSourceString).read("$['book'][?]", expensiveFilter); + Filter expensiveFilter = Filter.filter(Criteria.where("price") + .gt(20.00)); + List> expensive = JsonPath.parse(jsonDataSourceString) + .read("$['book'][?]", expensiveFilter); predicateUsageAssertionHelper(expensive); } @Test public void givenJsonPathWithCustomizedPredicate_whenReading_thenCorrect() { - Predicate expensivePredicate = context -> Float.valueOf(context.item(Map.class).get("price").toString()) > 20.00; - List> expensive = JsonPath.parse(jsonDataSourceString).read("$['book'][?]", expensivePredicate); + Predicate expensivePredicate = context -> Float.valueOf(context.item(Map.class) + .get("price") + .toString()) > 20.00; + List> expensive = JsonPath.parse(jsonDataSourceString) + .read("$['book'][?]", expensivePredicate); predicateUsageAssertionHelper(expensive); } @Test public void givenJsonPathWithInlinePredicate_whenReading_thenCorrect() { - List> expensive = JsonPath.parse(jsonDataSourceString).read("$['book'][?(@['price'] > $['price range']['medium'])]"); + List> expensive = JsonPath.parse(jsonDataSourceString) + .read("$['book'][?(@['price'] > $['price range']['medium'])]"); predicateUsageAssertionHelper(expensive); } diff --git a/json-path/src/test/java/com/baeldung/jsonpath/introduction/ServiceTest.java b/json-path/src/test/java/com/baeldung/jsonpath/introduction/ServiceTest.java index d5cfa50e80..067e5cf8ce 100644 --- a/json-path/src/test/java/com/baeldung/jsonpath/introduction/ServiceTest.java +++ b/json-path/src/test/java/com/baeldung/jsonpath/introduction/ServiceTest.java @@ -18,12 +18,16 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; public class ServiceTest { - private InputStream jsonInputStream = this.getClass().getClassLoader().getResourceAsStream("intro_service.json"); - private String jsonString = new Scanner(jsonInputStream, "UTF-8").useDelimiter("\\Z").next(); + private InputStream jsonInputStream = this.getClass() + .getClassLoader() + .getResourceAsStream("intro_service.json"); + private String jsonString = new Scanner(jsonInputStream, "UTF-8").useDelimiter("\\Z") + .next(); @Test public void givenId_whenRequestingRecordData_thenSucceed() { - Object dataObject = JsonPath.parse(jsonString).read("$[?(@.id == 2)]"); + Object dataObject = JsonPath.parse(jsonString) + .read("$[?(@.id == 2)]"); String dataString = dataObject.toString(); assertThat(dataString, containsString("2")); @@ -33,8 +37,10 @@ public class ServiceTest { @Test public void givenStarring_whenRequestingMovieTitle_thenSucceed() { - List> dataList = JsonPath.parse(jsonString).read("$[?('Eva Green' in @['starring'])]"); - String title = (String) dataList.get(0).get("title"); + List> dataList = JsonPath.parse(jsonString) + .read("$[?('Eva Green' in @['starring'])]"); + String title = (String) dataList.get(0) + .get("title"); assertEquals("Casino Royale", title); } @@ -59,8 +65,12 @@ public class ServiceTest { Arrays.sort(revenueArray); int highestRevenue = revenueArray[revenueArray.length - 1]; - Configuration pathConfiguration = Configuration.builder().options(Option.AS_PATH_LIST).build(); - List pathList = JsonPath.using(pathConfiguration).parse(jsonString).read("$[?(@['box office'] == " + highestRevenue + ")]"); + Configuration pathConfiguration = Configuration.builder() + .options(Option.AS_PATH_LIST) + .build(); + List pathList = JsonPath.using(pathConfiguration) + .parse(jsonString) + .read("$[?(@['box office'] == " + highestRevenue + ")]"); Map dataRecord = context.read(pathList.get(0)); String title = dataRecord.get("title"); @@ -83,7 +93,8 @@ public class ServiceTest { long latestTime = dateArray[dateArray.length - 1]; List> finalDataList = context.read("$[?(@['director'] == 'Sam Mendes' && @['release date'] == " + latestTime + ")]"); - String title = (String) finalDataList.get(0).get("title"); + String title = (String) finalDataList.get(0) + .get("title"); assertEquals("Spectre", title); } diff --git a/json/src/test/java/fast_json/FastJsonUnitTest.java b/json/src/test/java/fast_json/FastJsonUnitTest.java index e37f443387..6fcf1e398a 100644 --- a/json/src/test/java/fast_json/FastJsonUnitTest.java +++ b/json/src/test/java/fast_json/FastJsonUnitTest.java @@ -32,11 +32,7 @@ public class FastJsonUnitTest { @Test public void whenJavaList_thanConvertToJsonCorrect() { String personJsonFormat = JSON.toJSONString(listOfPersons); - assertEquals( - personJsonFormat, - "[{\"FIRST NAME\":\"Doe\",\"LAST NAME\":\"John\",\"DATE OF BIRTH\":" - + "\"24/07/2016\"},{\"FIRST NAME\":\"Doe\",\"LAST NAME\":\"Janette\",\"DATE OF BIRTH\":" - + "\"24/07/2016\"}]"); + assertEquals(personJsonFormat, "[{\"FIRST NAME\":\"Doe\",\"LAST NAME\":\"John\",\"DATE OF BIRTH\":" + "\"24/07/2016\"},{\"FIRST NAME\":\"Doe\",\"LAST NAME\":\"Janette\",\"DATE OF BIRTH\":" + "\"24/07/2016\"}]"); } @Test @@ -44,8 +40,10 @@ public class FastJsonUnitTest { String personJsonFormat = JSON.toJSONString(listOfPersons.get(0)); Person newPerson = JSON.parseObject(personJsonFormat, Person.class); assertEquals(newPerson.getAge(), 0); // serialize is set to false for age attribute - assertEquals(newPerson.getFirstName(), listOfPersons.get(0).getFirstName()); - assertEquals(newPerson.getLastName(), listOfPersons.get(0).getLastName()); + assertEquals(newPerson.getFirstName(), listOfPersons.get(0) + .getFirstName()); + assertEquals(newPerson.getLastName(), listOfPersons.get(0) + .getLastName()); } @Test @@ -58,18 +56,13 @@ public class FastJsonUnitTest { jsonObject.put("DATE OF BIRTH", "2016/12/12 12:12:12"); jsonArray.add(jsonObject); } - assertEquals( - jsonArray.toString(), - "[{\"LAST NAME\":\"Doe0\",\"DATE OF BIRTH\":" - + "\"2016/12/12 12:12:12\",\"FIRST NAME\":\"John0\"},{\"LAST NAME\":\"Doe1\"," - + "\"DATE OF BIRTH\":\"2016/12/12 12:12:12\",\"FIRST NAME\":\"John1\"}]"); + assertEquals(jsonArray.toString(), "[{\"LAST NAME\":\"Doe0\",\"DATE OF BIRTH\":" + "\"2016/12/12 12:12:12\",\"FIRST NAME\":\"John0\"},{\"LAST NAME\":\"Doe1\"," + "\"DATE OF BIRTH\":\"2016/12/12 12:12:12\",\"FIRST NAME\":\"John1\"}]"); } @Test public void givenContextFilter_whenJavaObject_thanJsonCorrect() { ContextValueFilter valueFilter = new ContextValueFilter() { - public Object process(BeanContext context, Object object, - String name, Object value) { + public Object process(BeanContext context, Object object, String name, Object value) { if (name.equals("DATE OF BIRTH")) { return "NOT TO DISCLOSE"; } @@ -87,18 +80,16 @@ public class FastJsonUnitTest { public void givenSerializeConfig_whenJavaObject_thanJsonCorrect() { NameFilter formatName = new NameFilter() { public String process(Object object, String name, Object value) { - return name.toLowerCase().replace(" ", "_"); + return name.toLowerCase() + .replace(" ", "_"); } }; - SerializeConfig.getGlobalInstance().addFilter(Person.class, formatName); - String jsonOutput = JSON.toJSONStringWithDateFormat(listOfPersons, - "yyyy-MM-dd"); - assertEquals( - jsonOutput, - "[{\"first_name\":\"Doe\",\"last_name\":\"John\"," - + "\"date_of_birth\":\"2016-07-24\"},{\"first_name\":\"Doe\",\"last_name\":" - + "\"Janette\",\"date_of_birth\":\"2016-07-24\"}]"); + SerializeConfig.getGlobalInstance() + .addFilter(Person.class, formatName); + String jsonOutput = JSON.toJSONStringWithDateFormat(listOfPersons, "yyyy-MM-dd"); + assertEquals(jsonOutput, "[{\"first_name\":\"Doe\",\"last_name\":\"John\"," + "\"date_of_birth\":\"2016-07-24\"},{\"first_name\":\"Doe\",\"last_name\":" + "\"Janette\",\"date_of_birth\":\"2016-07-24\"}]"); // resetting custom serializer - SerializeConfig.getGlobalInstance().put(Person.class, null); + SerializeConfig.getGlobalInstance() + .put(Person.class, null); } } diff --git a/json/src/test/java/fast_json/Person.java b/json/src/test/java/fast_json/Person.java index 0eac58cdfd..3d772348a4 100644 --- a/json/src/test/java/fast_json/Person.java +++ b/json/src/test/java/fast_json/Person.java @@ -32,10 +32,9 @@ public class Person { @Override public String toString() { - return "Person [age=" + age + ", lastName=" + lastName + ", firstName=" - + firstName + ", dateOfBirth=" + dateOfBirth + "]"; + return "Person [age=" + age + ", lastName=" + lastName + ", firstName=" + firstName + ", dateOfBirth=" + dateOfBirth + "]"; } - + public int getAge() { return age; } diff --git a/jsoup/src/test/java/com/baeldung/jsoup/JsoupParserIntegrationTest.java b/jsoup/src/test/java/com/baeldung/jsoup/JsoupParserIntegrationTest.java index dadd57b0ed..ee39f2550f 100644 --- a/jsoup/src/test/java/com/baeldung/jsoup/JsoupParserIntegrationTest.java +++ b/jsoup/src/test/java/com/baeldung/jsoup/JsoupParserIntegrationTest.java @@ -20,13 +20,15 @@ public class JsoupParserIntegrationTest { @Before public void setUp() throws IOException { - doc = Jsoup.connect("https://spring.io/blog").get(); + doc = Jsoup.connect("https://spring.io/blog") + .get(); } @Test public void loadDocument404() throws IOException { try { - doc = Jsoup.connect("https://spring.io/will-not-be-found").get(); + doc = Jsoup.connect("https://spring.io/will-not-be-found") + .get(); } catch (HttpStatusException ex) { assertEquals(404, ex.getStatusCode()); } @@ -35,13 +37,13 @@ public class JsoupParserIntegrationTest { @Test public void loadDocumentCustomized() throws IOException { doc = Jsoup.connect("https://spring.io/blog") - .userAgent("Mozilla") - .timeout(5000) - .cookie("cookiename", "val234") - .cookie("anothercookie", "ilovejsoup") - .referrer("http://google.com") - .header("headersecurity", "xyz123") - .get(); + .userAgent("Mozilla") + .timeout(5000) + .cookie("cookiename", "val234") + .cookie("anothercookie", "ilovejsoup") + .referrer("http://google.com") + .header("headersecurity", "xyz123") + .get(); } @Test @@ -77,10 +79,13 @@ public class JsoupParserIntegrationTest { @Test public void examplesExtracting() { - Element firstArticle = doc.select("article").first(); - Element timeElement = firstArticle.select("time").first(); + Element firstArticle = doc.select("article") + .first(); + Element timeElement = firstArticle.select("time") + .first(); String dateTimeOfFirstArticle = timeElement.attr("datetime"); - Element sectionDiv = firstArticle.select("section div").first(); + Element sectionDiv = firstArticle.select("section div") + .first(); String sectionDivText = sectionDiv.text(); String articleHtml = firstArticle.html(); String outerHtml = firstArticle.outerHtml(); @@ -88,24 +93,30 @@ public class JsoupParserIntegrationTest { @Test public void examplesModifying() { - Element firstArticle = doc.select("article").first(); - Element timeElement = firstArticle.select("time").first(); - Element sectionDiv = firstArticle.select("section div").first(); + Element firstArticle = doc.select("article") + .first(); + Element timeElement = firstArticle.select("time") + .first(); + Element sectionDiv = firstArticle.select("section div") + .first(); String dateTimeOfFirstArticle = timeElement.attr("datetime"); timeElement.attr("datetime", "2016-12-16 15:19:54.3"); sectionDiv.text("foo bar"); - firstArticle.select("h2").html("
"); + firstArticle.select("h2") + .html("
"); - Element link = new Element(Tag.valueOf("a"), "") - .text("Checkout this amazing website!") - .attr("href", "http://baeldung.com") - .attr("target", "_blank"); + Element link = new Element(Tag.valueOf("a"), "").text("Checkout this amazing website!") + .attr("href", "http://baeldung.com") + .attr("target", "_blank"); firstArticle.appendChild(link); - doc.select("li.navbar-link").remove(); - firstArticle.select("img").remove(); + doc.select("li.navbar-link") + .remove(); + firstArticle.select("img") + .remove(); - assertTrue(doc.html().contains("http://baeldung.com")); + assertTrue(doc.html() + .contains("http://baeldung.com")); } } diff --git a/junit5/src/test/java/com/baeldung/AssertionUnitTest.java b/junit5/src/test/java/com/baeldung/AssertionUnitTest.java index 504931b3d7..6fefd4e06d 100644 --- a/junit5/src/test/java/com/baeldung/AssertionUnitTest.java +++ b/junit5/src/test/java/com/baeldung/AssertionUnitTest.java @@ -6,23 +6,23 @@ import org.junit.jupiter.api.Test; public class AssertionUnitTest { - @Test - public void testConvertToDoubleThrowException() { - String age = "eighteen"; - assertThrows(NumberFormatException.class, () -> { - convertToInt(age); - }); + @Test + public void testConvertToDoubleThrowException() { + String age = "eighteen"; + assertThrows(NumberFormatException.class, () -> { + convertToInt(age); + }); - assertThrows(NumberFormatException.class, () -> { - convertToInt(age); - }); - } - - private static Integer convertToInt(String str) { - if (str == null) { - return null; - } - return Integer.valueOf(str); - } + assertThrows(NumberFormatException.class, () -> { + convertToInt(age); + }); + } + + private static Integer convertToInt(String str) { + if (str == null) { + return null; + } + return Integer.valueOf(str); + } } diff --git a/junit5/src/test/java/com/baeldung/AssumptionUnitTest.java b/junit5/src/test/java/com/baeldung/AssumptionUnitTest.java index afeee642eb..7d67d93486 100644 --- a/junit5/src/test/java/com/baeldung/AssumptionUnitTest.java +++ b/junit5/src/test/java/com/baeldung/AssumptionUnitTest.java @@ -24,9 +24,6 @@ public class AssumptionUnitTest { @Test void assumptionThat() { String someString = "Just a string"; - assumingThat( - someString.equals("Just a string"), - () -> assertEquals(2 + 2, 4) - ); + assumingThat(someString.equals("Just a string"), () -> assertEquals(2 + 2, 4)); } } diff --git a/junit5/src/test/java/com/baeldung/DynamicTestsExample.java b/junit5/src/test/java/com/baeldung/DynamicTestsExample.java index fd6bb3e0a8..b684f3603f 100644 --- a/junit5/src/test/java/com/baeldung/DynamicTestsExample.java +++ b/junit5/src/test/java/com/baeldung/DynamicTestsExample.java @@ -24,40 +24,33 @@ public class DynamicTestsExample { @TestFactory Collection dynamicTestsWithCollection() { - return Arrays.asList( - DynamicTest.dynamicTest("Add test", () -> assertEquals(2, Math.addExact(1, 1))), - DynamicTest.dynamicTest("Multiply Test", () -> assertEquals(4, Math.multiplyExact(2, 2)))); + return Arrays.asList(DynamicTest.dynamicTest("Add test", () -> assertEquals(2, Math.addExact(1, 1))), DynamicTest.dynamicTest("Multiply Test", () -> assertEquals(4, Math.multiplyExact(2, 2)))); } - + @TestFactory Iterable dynamicTestsWithIterable() { - return Arrays.asList( - DynamicTest.dynamicTest("Add test", () -> assertEquals(2, Math.addExact(1, 1))), - DynamicTest.dynamicTest("Multiply Test", () -> assertEquals(4, Math.multiplyExact(2, 2)))); + return Arrays.asList(DynamicTest.dynamicTest("Add test", () -> assertEquals(2, Math.addExact(1, 1))), DynamicTest.dynamicTest("Multiply Test", () -> assertEquals(4, Math.multiplyExact(2, 2)))); } - + @TestFactory Iterator dynamicTestsWithIterator() { - return Arrays.asList( - DynamicTest.dynamicTest("Add test", () -> assertEquals(2, Math.addExact(1, 1))), - DynamicTest.dynamicTest("Multiply Test", () -> assertEquals(4, Math.multiplyExact(2, 2)))) - .iterator(); + return Arrays.asList(DynamicTest.dynamicTest("Add test", () -> assertEquals(2, Math.addExact(1, 1))), DynamicTest.dynamicTest("Multiply Test", () -> assertEquals(4, Math.multiplyExact(2, 2)))) + .iterator(); } - + @TestFactory Stream dynamicTestsFromIntStream() { - return IntStream.iterate(0, n -> n + 2).limit(10).mapToObj( - n -> DynamicTest.dynamicTest("test" + n, () -> assertTrue(n % 2 == 0))); + return IntStream.iterate(0, n -> n + 2) + .limit(10) + .mapToObj(n -> DynamicTest.dynamicTest("test" + n, () -> assertTrue(n % 2 == 0))); } - + @TestFactory Stream dynamicTestsFromStream() { // sample input and output - List inputList = - Arrays.asList("www.somedomain.com", "www.anotherdomain.com", "www.yetanotherdomain.com"); - List outputList = - Arrays.asList("154.174.10.56", "211.152.104.132", "178.144.120.156"); + List inputList = Arrays.asList("www.somedomain.com", "www.anotherdomain.com", "www.yetanotherdomain.com"); + List outputList = Arrays.asList("154.174.10.56", "211.152.104.132", "178.144.120.156"); // input generator that generates inputs using inputList Iterator inputGenerator = inputList.iterator(); @@ -75,57 +68,56 @@ public class DynamicTestsExample { // combine everything and return a Stream of DynamicTest return DynamicTest.stream(inputGenerator, displayNameGenerator, testExecutor); } - + @TestFactory Stream dynamicTestsFromStreamInJava8() { - + DomainNameResolver resolver = new DomainNameResolver(); - - List inputList = - Arrays.asList("www.somedomain.com", "www.anotherdomain.com", "www.yetanotherdomain.com"); - List outputList = - Arrays.asList("154.174.10.56", "211.152.104.132", "178.144.120.156"); - - return inputList.stream().map(dom -> DynamicTest.dynamicTest("Resolving: " + dom, () -> { - int id = inputList.indexOf(dom); - assertEquals(outputList.get(id), resolver.resolveDomain(dom)); - })); - + + List inputList = Arrays.asList("www.somedomain.com", "www.anotherdomain.com", "www.yetanotherdomain.com"); + List outputList = Arrays.asList("154.174.10.56", "211.152.104.132", "178.144.120.156"); + + return inputList.stream() + .map(dom -> DynamicTest.dynamicTest("Resolving: " + dom, () -> { + int id = inputList.indexOf(dom); + assertEquals(outputList.get(id), resolver.resolveDomain(dom)); + })); + } @TestFactory Stream dynamicTestsForEmployeeWorkflows() { - List inputList = - Arrays.asList(new Employee(1, "Fred"), new Employee(2), new Employee(3, "John")); - + List inputList = Arrays.asList(new Employee(1, "Fred"), new Employee(2), new Employee(3, "John")); + EmployeeDao dao = new EmployeeDao(); - Stream saveEmployeeStream = inputList.stream().map(emp -> - DynamicTest.dynamicTest("saveEmployee: " + emp.toString(), () -> { - Employee returned = dao.save(emp.getId()); - assertEquals(returned.getId(), emp.getId()); - })); - - Stream saveEmployeeWithFirstNameStream - = inputList.stream().filter(emp -> !emp.getFirstName().isEmpty()) + Stream saveEmployeeStream = inputList.stream() + .map(emp -> DynamicTest.dynamicTest("saveEmployee: " + emp.toString(), () -> { + Employee returned = dao.save(emp.getId()); + assertEquals(returned.getId(), emp.getId()); + })); + + Stream saveEmployeeWithFirstNameStream = inputList.stream() + .filter(emp -> !emp.getFirstName() + .isEmpty()) .map(emp -> DynamicTest.dynamicTest("saveEmployeeWithName" + emp.toString(), () -> { - Employee returned = dao.save(emp.getId(), emp.getFirstName()); - assertEquals(returned.getId(), emp.getId()); - assertEquals(returned.getFirstName(), emp.getFirstName()); - })); - + Employee returned = dao.save(emp.getId(), emp.getFirstName()); + assertEquals(returned.getId(), emp.getId()); + assertEquals(returned.getFirstName(), emp.getFirstName()); + })); + return Stream.concat(saveEmployeeStream, saveEmployeeWithFirstNameStream); } - + class DomainNameResolver { - + private Map ipByDomainName = new HashMap<>(); - + DomainNameResolver() { this.ipByDomainName.put("www.somedomain.com", "154.174.10.56"); this.ipByDomainName.put("www.anotherdomain.com", "211.152.104.132"); this.ipByDomainName.put("www.yetanotherdomain.com", "178.144.120.156"); } - + public String resolveDomain(String domainName) { return ipByDomainName.get(domainName); } diff --git a/junit5/src/test/java/com/baeldung/EmployeesTest.java b/junit5/src/test/java/com/baeldung/EmployeesTest.java index 1a6da37d72..71bb52284b 100644 --- a/junit5/src/test/java/com/baeldung/EmployeesTest.java +++ b/junit5/src/test/java/com/baeldung/EmployeesTest.java @@ -33,12 +33,14 @@ public class EmployeesTest { public void whenAddEmployee_thenGetEmployee() throws SQLException { Employee emp = new Employee(1, "john"); employeeDao.add(emp); - assertEquals(1, employeeDao.findAll().size()); + assertEquals(1, employeeDao.findAll() + .size()); } @Test public void whenGetEmployees_thenEmptyList() throws SQLException { - assertEquals(0, employeeDao.findAll().size()); + assertEquals(0, employeeDao.findAll() + .size()); } public void setLogger(Logger logger) { diff --git a/junit5/src/test/java/com/baeldung/ExceptionUnitTest.java b/junit5/src/test/java/com/baeldung/ExceptionUnitTest.java index 6ec1a4b7bd..bd57f5b3cb 100644 --- a/junit5/src/test/java/com/baeldung/ExceptionUnitTest.java +++ b/junit5/src/test/java/com/baeldung/ExceptionUnitTest.java @@ -7,19 +7,19 @@ import org.junit.jupiter.api.Test; public class ExceptionUnitTest { - @Test - void shouldThrowException() { - Throwable exception = assertThrows(UnsupportedOperationException.class, () -> { - throw new UnsupportedOperationException("Not supported"); - }); - assertEquals(exception.getMessage(), "Not supported"); - } + @Test + void shouldThrowException() { + Throwable exception = assertThrows(UnsupportedOperationException.class, () -> { + throw new UnsupportedOperationException("Not supported"); + }); + assertEquals(exception.getMessage(), "Not supported"); + } - @Test - void assertThrowsException() { - String str = null; - assertThrows(IllegalArgumentException.class, () -> { - Integer.valueOf(str); - }); - } + @Test + void assertThrowsException() { + String str = null; + assertThrows(IllegalArgumentException.class, () -> { + Integer.valueOf(str); + }); + } } diff --git a/junit5/src/test/java/com/baeldung/FirstUnitTest.java b/junit5/src/test/java/com/baeldung/FirstUnitTest.java index 78c563cf82..c47a70e52f 100644 --- a/junit5/src/test/java/com/baeldung/FirstUnitTest.java +++ b/junit5/src/test/java/com/baeldung/FirstUnitTest.java @@ -13,21 +13,16 @@ class FirstUnitTest { @Test void lambdaExpressions() { List numbers = Arrays.asList(1, 2, 3); - assertTrue(numbers - .stream() - .mapToInt(i -> i) - .sum() > 5, "Sum should be greater than 5"); + assertTrue(numbers.stream() + .mapToInt(i -> i) + .sum() > 5, "Sum should be greater than 5"); } @Disabled("test to show MultipleFailuresError") @Test void groupAssertions() { - int[] numbers = {0, 1, 2, 3, 4}; - assertAll("numbers", - () -> assertEquals(numbers[0], 1), - () -> assertEquals(numbers[3], 3), - () -> assertEquals(numbers[4], 1) - ); + int[] numbers = { 0, 1, 2, 3, 4 }; + assertAll("numbers", () -> assertEquals(numbers[0], 1), () -> assertEquals(numbers[3], 3), () -> assertEquals(numbers[4], 1)); } @Test diff --git a/junit5/src/test/java/com/baeldung/JUnit5NewFeaturesUnitTest.java b/junit5/src/test/java/com/baeldung/JUnit5NewFeaturesUnitTest.java index a4dfd610a1..311c62f425 100644 --- a/junit5/src/test/java/com/baeldung/JUnit5NewFeaturesUnitTest.java +++ b/junit5/src/test/java/com/baeldung/JUnit5NewFeaturesUnitTest.java @@ -13,38 +13,38 @@ import org.junit.jupiter.api.Test; //@RunWith(JUnitPlatform.class) public class JUnit5NewFeaturesUnitTest { - private static final Logger log = Logger.getLogger(JUnit5NewFeaturesUnitTest.class.getName()); + private static final Logger log = Logger.getLogger(JUnit5NewFeaturesUnitTest.class.getName()); - @BeforeAll - static void setup() { - log.info("@BeforeAll - executes once before all test methods in this class"); - } + @BeforeAll + static void setup() { + log.info("@BeforeAll - executes once before all test methods in this class"); + } - @BeforeEach - void init() { - log.info("@BeforeEach - executes before each test method in this class"); - } + @BeforeEach + void init() { + log.info("@BeforeEach - executes before each test method in this class"); + } - @DisplayName("Single test successful") - @Test - void testSingleSuccessTest() { - log.info("Success"); + @DisplayName("Single test successful") + @Test + void testSingleSuccessTest() { + log.info("Success"); - } + } - @Test - @Disabled("Not implemented yet.") - void testShowSomething() { - } + @Test + @Disabled("Not implemented yet.") + void testShowSomething() { + } - @AfterEach - void tearDown() { - log.info("@AfterEach - executed after each test method."); - } + @AfterEach + void tearDown() { + log.info("@AfterEach - executed after each test method."); + } - @AfterAll - static void done() { - log.info("@AfterAll - executed after all test methods."); - } + @AfterAll + static void done() { + log.info("@AfterAll - executed after all test methods."); + } } diff --git a/junit5/src/test/java/com/baeldung/LiveTest.java b/junit5/src/test/java/com/baeldung/LiveTest.java index e0e267da0b..c23eeb5afa 100644 --- a/junit5/src/test/java/com/baeldung/LiveTest.java +++ b/junit5/src/test/java/com/baeldung/LiveTest.java @@ -12,27 +12,28 @@ import org.junit.jupiter.api.TestFactory; public class LiveTest { - private List in = new ArrayList<>(Arrays.asList("Hello", "Yes", "No")); - private List out = new ArrayList<>(Arrays.asList("Cześć", "Tak", "Nie")); + private List in = new ArrayList<>(Arrays.asList("Hello", "Yes", "No")); + private List out = new ArrayList<>(Arrays.asList("Cześć", "Tak", "Nie")); - @TestFactory - public Stream translateDynamicTestsFromStream() { + @TestFactory + public Stream translateDynamicTestsFromStream() { - return in.stream().map(word -> DynamicTest.dynamicTest("Test translate " + word, () -> { - int id = in.indexOf(word); - assertEquals(out.get(id), translate(word)); - })); - } + return in.stream() + .map(word -> DynamicTest.dynamicTest("Test translate " + word, () -> { + int id = in.indexOf(word); + assertEquals(out.get(id), translate(word)); + })); + } - private String translate(String word) { - if ("Hello".equalsIgnoreCase(word)) { - return "Cześć"; - } else if ("Yes".equalsIgnoreCase(word)) { - return "Tak"; - } else if ("No".equalsIgnoreCase(word)) { - return "Nie"; - } - return "Error"; - } + private String translate(String word) { + if ("Hello".equalsIgnoreCase(word)) { + return "Cześć"; + } else if ("Yes".equalsIgnoreCase(word)) { + return "Tak"; + } else if ("No".equalsIgnoreCase(word)) { + return "Nie"; + } + return "Error"; + } } diff --git a/junit5/src/test/java/com/baeldung/RepeatedTestExample.java b/junit5/src/test/java/com/baeldung/RepeatedTestExample.java index 8674e01e5d..749d7064bc 100644 --- a/junit5/src/test/java/com/baeldung/RepeatedTestExample.java +++ b/junit5/src/test/java/com/baeldung/RepeatedTestExample.java @@ -14,36 +14,36 @@ public class RepeatedTestExample { void beforeEachTest() { System.out.println("Before Each Test"); } - + @AfterEach void afterEachTest() { System.out.println("After Each Test"); System.out.println("====================="); } - + @RepeatedTest(3) void repeatedTest(TestInfo testInfo) { System.out.println("Executing repeated test"); assertEquals(2, Math.addExact(1, 1), "1 + 1 should equal 2"); } - + @RepeatedTest(value = 3, name = RepeatedTest.LONG_DISPLAY_NAME) void repeatedTestWithLongName() { System.out.println("Executing repeated test with long name"); assertEquals(2, Math.addExact(1, 1), "1 + 1 should equal 2"); } - + @RepeatedTest(value = 3, name = RepeatedTest.SHORT_DISPLAY_NAME) void repeatedTestWithShortName() { System.out.println("Executing repeated test with long name"); assertEquals(2, Math.addExact(1, 1), "1 + 1 should equal 2"); } - + @RepeatedTest(value = 3, name = "Custom name {currentRepetition}/{totalRepetitions}") void repeatedTestWithCustomDisplayName() { assertEquals(2, Math.addExact(1, 1), "1 + 1 should equal 2"); } - + @RepeatedTest(3) void repeatedTestWithRepetitionInfo(RepetitionInfo repetitionInfo) { System.out.println("Repetition #" + repetitionInfo.getCurrentRepetition()); diff --git a/junit5/src/test/java/com/baeldung/StringUtils.java b/junit5/src/test/java/com/baeldung/StringUtils.java index c1852113bc..227f131876 100644 --- a/junit5/src/test/java/com/baeldung/StringUtils.java +++ b/junit5/src/test/java/com/baeldung/StringUtils.java @@ -2,10 +2,10 @@ package com.baeldung; public final class StringUtils { - public static Double convertToDouble(String str) { - if (str == null) { - return null; - } - return Double.valueOf(str); - } + public static Double convertToDouble(String str) { + if (str == null) { + return null; + } + return Double.valueOf(str); + } } diff --git a/junit5/src/test/java/com/baeldung/TestLauncher.java b/junit5/src/test/java/com/baeldung/TestLauncher.java index d0354e19a9..f9766d2bd9 100644 --- a/junit5/src/test/java/com/baeldung/TestLauncher.java +++ b/junit5/src/test/java/com/baeldung/TestLauncher.java @@ -25,13 +25,15 @@ public class TestLauncher { //@formatter:on - TestPlan plan = LauncherFactory.create().discover(request); + TestPlan plan = LauncherFactory.create() + .discover(request); Launcher launcher = LauncherFactory.create(); SummaryGeneratingListener summaryGeneratingListener = new SummaryGeneratingListener(); launcher.execute(request, new TestExecutionListener[] { summaryGeneratingListener }); launcher.execute(request); - summaryGeneratingListener.getSummary().printTo(new PrintWriter(System.out)); + summaryGeneratingListener.getSummary() + .printTo(new PrintWriter(System.out)); } } diff --git a/junit5/src/test/java/com/baeldung/extensions/EmployeeDaoParameterResolver.java b/junit5/src/test/java/com/baeldung/extensions/EmployeeDaoParameterResolver.java index 2626266454..4e6931a65d 100644 --- a/junit5/src/test/java/com/baeldung/extensions/EmployeeDaoParameterResolver.java +++ b/junit5/src/test/java/com/baeldung/extensions/EmployeeDaoParameterResolver.java @@ -12,7 +12,9 @@ public class EmployeeDaoParameterResolver implements ParameterResolver { @Override public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException { - return parameterContext.getParameter().getType().equals(EmployeeJdbcDao.class); + return parameterContext.getParameter() + .getType() + .equals(EmployeeJdbcDao.class); } @Override diff --git a/junit5/src/test/java/com/baeldung/extensions/LoggingExtension.java b/junit5/src/test/java/com/baeldung/extensions/LoggingExtension.java index 437c5c24de..930018d576 100644 --- a/junit5/src/test/java/com/baeldung/extensions/LoggingExtension.java +++ b/junit5/src/test/java/com/baeldung/extensions/LoggingExtension.java @@ -10,7 +10,9 @@ public class LoggingExtension implements TestInstancePostProcessor { @Override public void postProcessTestInstance(Object testInstance, ExtensionContext context) throws Exception { Logger logger = LogManager.getLogger(testInstance.getClass()); - testInstance.getClass().getMethod("setLogger", Logger.class).invoke(testInstance, logger); + testInstance.getClass() + .getMethod("setLogger", Logger.class) + .invoke(testInstance, logger); } } diff --git a/junit5/src/test/java/com/baeldung/migration/junit5/AssertionsExampleTest.java b/junit5/src/test/java/com/baeldung/migration/junit5/AssertionsExampleTest.java index 642b7371de..3cfe4c59f5 100644 --- a/junit5/src/test/java/com/baeldung/migration/junit5/AssertionsExampleTest.java +++ b/junit5/src/test/java/com/baeldung/migration/junit5/AssertionsExampleTest.java @@ -30,9 +30,10 @@ public class AssertionsExampleTest { List list = Arrays.asList(1, 2, 3); Assertions.assertAll("List is not incremental", () -> Assertions.assertEquals(list.get(0) - .intValue(), 1), - () -> Assertions.assertEquals(list.get(1) - .intValue(), 2), + .intValue(), 1), () -> Assertions.assertEquals( + list.get(1) + .intValue(), + 2), () -> Assertions.assertEquals(list.get(2) .intValue(), 3)); } diff --git a/junit5/src/test/java/com/baeldung/param/InvalidPersonParameterResolver.java b/junit5/src/test/java/com/baeldung/param/InvalidPersonParameterResolver.java index 67bd47a44a..73ae2e08b7 100644 --- a/junit5/src/test/java/com/baeldung/param/InvalidPersonParameterResolver.java +++ b/junit5/src/test/java/com/baeldung/param/InvalidPersonParameterResolver.java @@ -9,42 +9,51 @@ import org.junit.jupiter.api.extension.ParameterResolver; public class InvalidPersonParameterResolver implements ParameterResolver { - /** - * The "bad" (invalid) data for testing purposes has to go somewhere, right? - */ - public static Person[] INVALID_PERSONS = { - new Person().setId(1L).setLastName("Ad_ams").setFirstName("Jill,"), - new Person().setId(2L).setLastName(",Baker").setFirstName(""), - new Person().setId(3L).setLastName(null).setFirstName(null), - new Person().setId(4L).setLastName("Daniel&").setFirstName("{Joseph}"), - new Person().setId(5L).setLastName("").setFirstName("English, Jane"), - new Person()/* .setId(6L).setLastName("Fontana").setFirstName("Enrique") */, - // TODO: ADD MORE DATA HERE - }; + /** + * The "bad" (invalid) data for testing purposes has to go somewhere, right? + */ + public static Person[] INVALID_PERSONS = { new Person().setId(1L) + .setLastName("Ad_ams") + .setFirstName("Jill,"), + new Person().setId(2L) + .setLastName(",Baker") + .setFirstName(""), + new Person().setId(3L) + .setLastName(null) + .setFirstName(null), + new Person().setId(4L) + .setLastName("Daniel&") + .setFirstName("{Joseph}"), + new Person().setId(5L) + .setLastName("") + .setFirstName("English, Jane"), + new Person()/* .setId(6L).setLastName("Fontana").setFirstName("Enrique") */, + // TODO: ADD MORE DATA HERE + }; - @Override - public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) - throws ParameterResolutionException { - Object ret = null; - // - // Return a random, valid Person object if Person.class is the type of Parameter - /// to be resolved. Otherwise return null. - if (parameterContext.getParameter().getType() == Person.class) { - ret = INVALID_PERSONS[new Random().nextInt(INVALID_PERSONS.length)]; + @Override + public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException { + Object ret = null; + // + // Return a random, valid Person object if Person.class is the type of Parameter + /// to be resolved. Otherwise return null. + if (parameterContext.getParameter() + .getType() == Person.class) { + ret = INVALID_PERSONS[new Random().nextInt(INVALID_PERSONS.length)]; + } + return ret; } - return ret; - } - @Override - public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) - throws ParameterResolutionException { - boolean ret = false; - // - // If the Parameter.type == Person.class, then we support it, otherwise, get outta here! - if (parameterContext.getParameter().getType() == Person.class) { - ret = true; + @Override + public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException { + boolean ret = false; + // + // If the Parameter.type == Person.class, then we support it, otherwise, get outta here! + if (parameterContext.getParameter() + .getType() == Person.class) { + ret = true; + } + return ret; } - return ret; - } } diff --git a/junit5/src/test/java/com/baeldung/param/Person.java b/junit5/src/test/java/com/baeldung/param/Person.java index 65333b5e56..7095036bd4 100644 --- a/junit5/src/test/java/com/baeldung/param/Person.java +++ b/junit5/src/test/java/com/baeldung/param/Person.java @@ -9,35 +9,35 @@ package com.baeldung.param; */ public class Person { - private Long id; - private String lastName; - private String firstName; + private Long id; + private String lastName; + private String firstName; - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public Person setId(Long id) { - this.id = id; - return this; - } + public Person setId(Long id) { + this.id = id; + return this; + } - public String getLastName() { - return lastName; - } + public String getLastName() { + return lastName; + } - public Person setLastName(String lastName) { - this.lastName = lastName; - return this; - } + public Person setLastName(String lastName) { + this.lastName = lastName; + return this; + } - public String getFirstName() { - return firstName; - } + public String getFirstName() { + return firstName; + } - public Person setFirstName(String firstName) { - this.firstName = firstName; - return this; - } + public Person setFirstName(String firstName) { + this.firstName = firstName; + return this; + } } diff --git a/junit5/src/test/java/com/baeldung/param/PersonValidator.java b/junit5/src/test/java/com/baeldung/param/PersonValidator.java index 0219169aab..fbf596be8a 100644 --- a/junit5/src/test/java/com/baeldung/param/PersonValidator.java +++ b/junit5/src/test/java/com/baeldung/param/PersonValidator.java @@ -11,132 +11,122 @@ import java.util.Arrays; */ public class PersonValidator { - /** - * Contrived checked exception to illustrate one possible - * way to handle validation errors (via a checked exception). - * - * @author J Steven Perry - * - */ - public static class ValidationException extends Exception { + /** + * Contrived checked exception to illustrate one possible + * way to handle validation errors (via a checked exception). + * + * @author J Steven Perry + * + */ + public static class ValidationException extends Exception { + + /** + * + */ + private static final long serialVersionUID = -134518049431883102L; + + // Probably should implement some more constructors, but don't want + /// to tarnish the lesson... + + /** + * The one and only way to create this checked exception. + * + * @param message + * The message accompanying the exception. Should be meaningful. + */ + public ValidationException(String message) { + super(message); + + } + + } + + private static final String[] ILLEGAL_NAME_CHARACTERS = { ",", "_", "{", "}", "!" }; /** + * Validate the first name of the specified Person object. * + * @param person + * The Person object to validate. + * + * @return - returns true if the specified Person is valid + * + * @throws ValidationException + * - this Exception is thrown if any kind of validation error occurs. */ - private static final long serialVersionUID = -134518049431883102L; - - // Probably should implement some more constructors, but don't want - /// to tarnish the lesson... + public static boolean validateFirstName(Person person) throws ValidationException { + boolean ret = true; + // The validation rules go here. + // Naive: use simple ifs + if (person == null) { + throw new ValidationException("Person is null (not allowed)!"); + } + if (person.getFirstName() == null) { + throw new ValidationException("Person FirstName is null (not allowed)!"); + } + if (person.getFirstName() + .isEmpty()) { + throw new ValidationException("Person FirstName is an empty String (not allowed)!"); + } + if (!isStringValid(person.getFirstName(), ILLEGAL_NAME_CHARACTERS)) { + throw new ValidationException("Person FirstName (" + person.getFirstName() + ") may not contain any of the following characters: " + Arrays.toString(ILLEGAL_NAME_CHARACTERS) + "!"); + } + return ret; + } /** - * The one and only way to create this checked exception. + * Validate the last name of the specified Person object. Looks the same as first + * name? Look closer. Just kidding. It's the same. But real world code can (and will) diverge. * - * @param message - * The message accompanying the exception. Should be meaningful. + * @param person + * The Person object to validate. + * + * @return - returns true if the specified Person is valid + * + * @throws ValidationException + * - this Exception is thrown if any kind of validation error occurs. */ - public ValidationException(String message) { - super(message); - + public static boolean validateLastName(Person person) throws ValidationException { + boolean ret = true; + // The validation rules go here. + // Naive: use simple ifs + if (person == null) { + throw new ValidationException("Person is null (not allowed)!"); + } + if (person.getFirstName() == null) { + throw new ValidationException("Person FirstName is null (not allowed)!"); + } + if (person.getFirstName() + .isEmpty()) { + throw new ValidationException("Person FirstName is an empty String (not allowed)!"); + } + if (!isStringValid(person.getFirstName(), ILLEGAL_NAME_CHARACTERS)) { + throw new ValidationException("Person LastName (" + person.getLastName() + ") may not contain any of the following characters: " + Arrays.toString(ILLEGAL_NAME_CHARACTERS) + "!"); + } + return ret; } - } - - private static final String[] ILLEGAL_NAME_CHARACTERS = { - ",", - "_", - "{", - "}", - "!" - }; - - /** - * Validate the first name of the specified Person object. - * - * @param person - * The Person object to validate. - * - * @return - returns true if the specified Person is valid - * - * @throws ValidationException - * - this Exception is thrown if any kind of validation error occurs. - */ - public static boolean validateFirstName(Person person) throws ValidationException { - boolean ret = true; - // The validation rules go here. - // Naive: use simple ifs - if (person == null) { - throw new ValidationException("Person is null (not allowed)!"); + /** + * Validates the specified name. If it contains any of the illegalCharacters, + * this method returns false (indicating the name is illegal). Otherwise it returns true. + * + * @param candidate + * The candidate String to validate + * + * @param illegalCharacters + * The characters the String is not allowed to have + * + * @return - boolean - true if the name is valid, false otherwise. + */ + private static boolean isStringValid(String candidate, String[] illegalCharacters) { + boolean ret = true; + for (String illegalChar : illegalCharacters) { + if (candidate.contains(illegalChar)) { + ret = false; + break; + } + } + return ret; } - if (person.getFirstName() == null) { - throw new ValidationException("Person FirstName is null (not allowed)!"); - } - if (person.getFirstName().isEmpty()) { - throw new ValidationException("Person FirstName is an empty String (not allowed)!"); - } - if (!isStringValid(person.getFirstName(), ILLEGAL_NAME_CHARACTERS)) { - throw new ValidationException( - "Person FirstName (" + person.getFirstName() + ") may not contain any of the following characters: " - + Arrays.toString(ILLEGAL_NAME_CHARACTERS) - + "!"); - } - return ret; - } - - /** - * Validate the last name of the specified Person object. Looks the same as first - * name? Look closer. Just kidding. It's the same. But real world code can (and will) diverge. - * - * @param person - * The Person object to validate. - * - * @return - returns true if the specified Person is valid - * - * @throws ValidationException - * - this Exception is thrown if any kind of validation error occurs. - */ - public static boolean validateLastName(Person person) throws ValidationException { - boolean ret = true; - // The validation rules go here. - // Naive: use simple ifs - if (person == null) { - throw new ValidationException("Person is null (not allowed)!"); - } - if (person.getFirstName() == null) { - throw new ValidationException("Person FirstName is null (not allowed)!"); - } - if (person.getFirstName().isEmpty()) { - throw new ValidationException("Person FirstName is an empty String (not allowed)!"); - } - if (!isStringValid(person.getFirstName(), ILLEGAL_NAME_CHARACTERS)) { - throw new ValidationException( - "Person LastName (" + person.getLastName() + ") may not contain any of the following characters: " - + Arrays.toString(ILLEGAL_NAME_CHARACTERS) - + "!"); - } - return ret; - } - - /** - * Validates the specified name. If it contains any of the illegalCharacters, - * this method returns false (indicating the name is illegal). Otherwise it returns true. - * - * @param candidate - * The candidate String to validate - * - * @param illegalCharacters - * The characters the String is not allowed to have - * - * @return - boolean - true if the name is valid, false otherwise. - */ - private static boolean isStringValid(String candidate, String[] illegalCharacters) { - boolean ret = true; - for (String illegalChar : illegalCharacters) { - if (candidate.contains(illegalChar)) { - ret = false; - break; - } - } - return ret; - } } diff --git a/junit5/src/test/java/com/baeldung/param/PersonValidatorTest.java b/junit5/src/test/java/com/baeldung/param/PersonValidatorTest.java index 09ab03b811..cd6f2b7e4f 100644 --- a/junit5/src/test/java/com/baeldung/param/PersonValidatorTest.java +++ b/junit5/src/test/java/com/baeldung/param/PersonValidatorTest.java @@ -15,88 +15,88 @@ import org.junit.runner.RunWith; @DisplayName("Testing PersonValidator") public class PersonValidatorTest { - /** - * Nested class, uses ExtendWith - * {@link com.baeldung.param.ValidPersonParameterResolver ValidPersonParameterResolver} - * to feed Test methods with "good" data. - */ - @Nested - @DisplayName("When using Valid data") - @ExtendWith(ValidPersonParameterResolver.class) - public class ValidData { - /** - * Repeat the test ten times, that way we have a good shot at - * running all of the data through at least once. - * - * @param person - * A valid Person object to validate. + * Nested class, uses ExtendWith + * {@link com.baeldung.param.ValidPersonParameterResolver ValidPersonParameterResolver} + * to feed Test methods with "good" data. */ - @RepeatedTest(value = 10) - @DisplayName("All first names are valid") - public void validateFirstName(Person person) { - try { - assertTrue(PersonValidator.validateFirstName(person)); - } catch (PersonValidator.ValidationException e) { - fail("Exception not expected: " + e.getLocalizedMessage()); - } + @Nested + @DisplayName("When using Valid data") + @ExtendWith(ValidPersonParameterResolver.class) + public class ValidData { + + /** + * Repeat the test ten times, that way we have a good shot at + * running all of the data through at least once. + * + * @param person + * A valid Person object to validate. + */ + @RepeatedTest(value = 10) + @DisplayName("All first names are valid") + public void validateFirstName(Person person) { + try { + assertTrue(PersonValidator.validateFirstName(person)); + } catch (PersonValidator.ValidationException e) { + fail("Exception not expected: " + e.getLocalizedMessage()); + } + } + + /** + * Repeat the test ten times, that way we have a good shot at + * running all of the data through at least once. + * + * @param person + * A valid Person object to validate. + */ + @RepeatedTest(value = 10) + @DisplayName("All last names are valid") + public void validateLastName(Person person) { + try { + assertTrue(PersonValidator.validateLastName(person)); + } catch (PersonValidator.ValidationException e) { + fail("Exception not expected: " + e.getLocalizedMessage()); + } + } + } /** - * Repeat the test ten times, that way we have a good shot at - * running all of the data through at least once. - * - * @param person - * A valid Person object to validate. + * Nested class, uses ExtendWith + * {@link com.baeldung.param.InvalidPersonParameterResolver InvalidPersonParameterResolver} + * to feed Test methods with "bad" data. */ - @RepeatedTest(value = 10) - @DisplayName("All last names are valid") - public void validateLastName(Person person) { - try { - assertTrue(PersonValidator.validateLastName(person)); - } catch (PersonValidator.ValidationException e) { - fail("Exception not expected: " + e.getLocalizedMessage()); - } + @Nested + @DisplayName("When using Invalid data") + @ExtendWith(InvalidPersonParameterResolver.class) + public class InvalidData { + + /** + * Repeat the test ten times, that way we have a good shot at + * running all of the data through at least once. + * + * @param person + * An invalid Person object to validate. + */ + @RepeatedTest(value = 10) + @DisplayName("All first names are invalid") + public void validateFirstName(Person person) { + assertThrows(PersonValidator.ValidationException.class, () -> PersonValidator.validateFirstName(person)); + } + + /** + * Repeat the test ten times, that way we have a good shot at + * running all of the data through at least once. + * + * @param person + * An invalid Person object to validate. + */ + @RepeatedTest(value = 10) + @DisplayName("All first names are invalid") + public void validateLastName(Person person) { + assertThrows(PersonValidator.ValidationException.class, () -> PersonValidator.validateLastName(person)); + } + } - } - - /** - * Nested class, uses ExtendWith - * {@link com.baeldung.param.InvalidPersonParameterResolver InvalidPersonParameterResolver} - * to feed Test methods with "bad" data. - */ - @Nested - @DisplayName("When using Invalid data") - @ExtendWith(InvalidPersonParameterResolver.class) - public class InvalidData { - - /** - * Repeat the test ten times, that way we have a good shot at - * running all of the data through at least once. - * - * @param person - * An invalid Person object to validate. - */ - @RepeatedTest(value = 10) - @DisplayName("All first names are invalid") - public void validateFirstName(Person person) { - assertThrows(PersonValidator.ValidationException.class, () -> PersonValidator.validateFirstName(person)); - } - - /** - * Repeat the test ten times, that way we have a good shot at - * running all of the data through at least once. - * - * @param person - * An invalid Person object to validate. - */ - @RepeatedTest(value = 10) - @DisplayName("All first names are invalid") - public void validateLastName(Person person) { - assertThrows(PersonValidator.ValidationException.class, () -> PersonValidator.validateLastName(person)); - } - - } - } diff --git a/junit5/src/test/java/com/baeldung/param/ValidPersonParameterResolver.java b/junit5/src/test/java/com/baeldung/param/ValidPersonParameterResolver.java index abb97586eb..10d958b83c 100644 --- a/junit5/src/test/java/com/baeldung/param/ValidPersonParameterResolver.java +++ b/junit5/src/test/java/com/baeldung/param/ValidPersonParameterResolver.java @@ -9,42 +9,53 @@ import org.junit.jupiter.api.extension.ParameterResolver; public class ValidPersonParameterResolver implements ParameterResolver { - /** - * The "good" (valid) data for testing purposes has to go somewhere, right? - */ - public static Person[] VALID_PERSONS = { - new Person().setId(1L).setLastName("Adams").setFirstName("Jill"), - new Person().setId(2L).setLastName("Baker").setFirstName("James"), - new Person().setId(3L).setLastName("Carter").setFirstName("Samanta"), - new Person().setId(4L).setLastName("Daniels").setFirstName("Joseph"), - new Person().setId(5L).setLastName("English").setFirstName("Jane"), - new Person().setId(6L).setLastName("Fontana").setFirstName("Enrique"), - // TODO: ADD MORE DATA HERE - }; + /** + * The "good" (valid) data for testing purposes has to go somewhere, right? + */ + public static Person[] VALID_PERSONS = { new Person().setId(1L) + .setLastName("Adams") + .setFirstName("Jill"), + new Person().setId(2L) + .setLastName("Baker") + .setFirstName("James"), + new Person().setId(3L) + .setLastName("Carter") + .setFirstName("Samanta"), + new Person().setId(4L) + .setLastName("Daniels") + .setFirstName("Joseph"), + new Person().setId(5L) + .setLastName("English") + .setFirstName("Jane"), + new Person().setId(6L) + .setLastName("Fontana") + .setFirstName("Enrique"), + // TODO: ADD MORE DATA HERE + }; - @Override - public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) - throws ParameterResolutionException { - Object ret = null; - // - // Return a random, valid Person object if Person.class is the type of Parameter - /// to be resolved. Otherwise return null. - if (parameterContext.getParameter().getType() == Person.class) { - ret = VALID_PERSONS[new Random().nextInt(VALID_PERSONS.length)]; + @Override + public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException { + Object ret = null; + // + // Return a random, valid Person object if Person.class is the type of Parameter + /// to be resolved. Otherwise return null. + if (parameterContext.getParameter() + .getType() == Person.class) { + ret = VALID_PERSONS[new Random().nextInt(VALID_PERSONS.length)]; + } + return ret; } - return ret; - } - @Override - public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) - throws ParameterResolutionException { - boolean ret = false; - // - // If the Parameter.type == Person.class, then we support it, otherwise, get outta here! - if (parameterContext.getParameter().getType() == Person.class) { - ret = true; + @Override + public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException { + boolean ret = false; + // + // If the Parameter.type == Person.class, then we support it, otherwise, get outta here! + if (parameterContext.getParameter() + .getType() == Person.class) { + ret = true; + } + return ret; } - return ret; - } } diff --git a/junit5/src/test/java/com/baeldung/suites/AllTests.java b/junit5/src/test/java/com/baeldung/suites/AllTests.java index 69f28373eb..29452efc3d 100644 --- a/junit5/src/test/java/com/baeldung/suites/AllTests.java +++ b/junit5/src/test/java/com/baeldung/suites/AllTests.java @@ -6,7 +6,7 @@ import org.junit.runner.RunWith; @RunWith(JUnitPlatform.class) @SelectPackages("com.baeldung") -//@SelectClasses({AssertionTest.class, AssumptionTest.class, ExceptionTest.class}) +// @SelectClasses({AssertionTest.class, AssumptionTest.class, ExceptionTest.class}) public class AllTests { } diff --git a/libraries/src/test/java/com/baeldung/commons/collections4/BagTests.java b/libraries/src/test/java/com/baeldung/commons/collections4/BagTests.java index 1270c50008..4ce250d979 100644 --- a/libraries/src/test/java/com/baeldung/commons/collections4/BagTests.java +++ b/libraries/src/test/java/com/baeldung/commons/collections4/BagTests.java @@ -34,9 +34,7 @@ public class BagTests { Assert.assertFalse(baseBag.contains("lemon")); Assert.assertTrue(baseBag.uniqueSet().contains("apple")); - Assert.assertFalse(baseBag.uniqueSet().contains("lemon")); - Assert.assertTrue(baseBag.uniqueSet().contains("lime")); - + List containList = new ArrayList(); containList.add("apple"); containList.add("lemon"); @@ -56,11 +54,12 @@ public class BagTests { baseCollectionBag.remove("lemon"); Assert.assertEquals(8, baseCollectionBag.size()); Assert.assertTrue(baseCollectionBag.contains("lemon")); + + baseCollectionBag.remove("lemon",1); + Assert.assertEquals(7, baseCollectionBag.size()); Assert.assertTrue(baseBag.uniqueSet().contains("apple")); - Assert.assertTrue(baseBag.uniqueSet().contains("lemon")); - Assert.assertTrue(baseBag.uniqueSet().contains("lime")); - + List containList = new ArrayList(); containList.add("apple"); containList.add("lemon"); @@ -81,5 +80,6 @@ public class BagTests { treeBag.remove("apple"); Assert.assertEquals(9, treeBag.size()); Assert.assertEquals("banana", treeBag.first()); + } } 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-hibernate5/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationMainIntegrationTest.java b/spring-hibernate5/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationMainIntegrationTest.java index 2ec1246961..9a536a0f80 100644 --- a/spring-hibernate5/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationMainIntegrationTest.java +++ b/spring-hibernate5/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationMainIntegrationTest.java @@ -47,8 +47,8 @@ public class HibernateManyToManyAnnotationMainIntegrationTest { Employee employee = new Employee(emp.split(" ")[0], emp.split(" ")[1]); assertEquals(0, employee.getProjects().size()); employee.setProjects(projects); - assertNotNull(employee); session.persist(employee); + assertNotNull(employee); } } 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()); } diff --git a/vavr/src/test/java/com/baeldung/vavr/collections/CollectionAPIUnitTest.java b/vavr/src/test/java/com/baeldung/vavr/collections/CollectionAPIUnitTest.java index 4b4eb55fc5..cfc789a837 100644 --- a/vavr/src/test/java/com/baeldung/vavr/collections/CollectionAPIUnitTest.java +++ b/vavr/src/test/java/com/baeldung/vavr/collections/CollectionAPIUnitTest.java @@ -30,16 +30,67 @@ import static org.junit.Assert.assertTrue; public class CollectionAPIUnitTest { + @Test - public void givenEmptyList_whenStacked_thenCorrect() { + public void givenParams_whenListAPI_thenCorrect() { + + List list + = List.of("Java", "PHP", "Jquery", "JavaScript", "JShell", "JAVA"); + + List list1 = list.drop(2); + assertFalse(list1.contains("Java") && list1.contains("PHP")); + + List list2 = list.dropRight(2); + assertFalse(list2.contains("JAVA") && list2.contains("JShell")); + + List list3 = list.dropUntil(s -> s.contains("Shell")); + assertEquals(list3.size(), 2); + + List list4 = list.dropWhile(s -> s.length() > 0); + assertTrue(list4.isEmpty()); + + List list5 = list.take(1); + assertEquals(list5.single(), "Java"); + + List list6 = list.takeRight(1); + assertEquals(list6.single(), "JAVA"); + + List list7 = list.takeUntil(s -> s.length() > 6); + assertEquals(list7.size(), 3); + + List list8 + = list.distinctBy( (s1, s2) -> s1.startsWith(s2.charAt(0)+"") ? 0 : 1); + assertEquals(list8.size(), 2); + + Iterator> iterator = list.grouped(2); + assertEquals(iterator.head().size(), 2); + + Map> map = list.groupBy(e -> e.startsWith("J")); + assertEquals(map.size(), 2); + assertEquals(map.get(false).get().size(), 1); + assertEquals(map.get(true).get().size(), 5); + + String words = List.of("Boys", "Girls") + .intersperse("and") + .reduce((s1, s2) -> s1.concat( " " + s2 )) + .trim(); + + assertEquals(words, "Boys and Girls"); + + } + + @Test + public void givenEmptyList_whenStackAPI_thenCorrect() { + List intList = List.empty(); - List anotherList = intList.push(4) - .push(0); - Iterator iterator = anotherList.iterator(); + List intList1 = intList.pushAll(List.rangeClosed(5,10)); + + assertEquals(intList1.peek(), Integer.valueOf(10)); + + List intList2 = intList1.pop(); + assertEquals(intList2.size(), (intList1.size() - 1) ); - assertEquals(new Integer(0), iterator.next()); - assertEquals(new Integer(4), iterator.next()); } @Test @@ -61,27 +112,33 @@ public class CollectionAPIUnitTest { @Test public void givenQueue_whenEnqueued_thenCorrect() { + Queue queue = Queue.of(1, 2, 3); - Queue secondQueue = queue.enqueue(4) - .enqueue(5); + Queue secondQueue = queue.enqueueAll(List.of(4,5)); assertEquals(3, queue.size()); assertEquals(5, secondQueue.size()); Tuple2> result = secondQueue.dequeue(); - Integer headValue = result.apply((head, tail) -> head); - assertEquals(new Integer(1), headValue); + assertEquals(Integer.valueOf(1), result._1); - Iterator iterator = result.apply((head, tail) -> tail.iterator()); - - assertEquals(new Integer(2), iterator.next()); - assertEquals(new Integer(3), iterator.next()); - assertEquals(new Integer(4), iterator.next()); - assertEquals(new Integer(5), iterator.next()); + Queue tailQueue = result._2; + assertFalse(tailQueue.contains(secondQueue.get(0))); } @Test public void givenStream_whenProcessed_thenCorrect() { + + Stream s1 = Stream.tabulate(5, (i)-> i + 1); + assertEquals(s1.get(2).intValue(), 3); + + Stream s = Stream.of(2,1,3,4); + + Stream> s2 = s.zip(List.of(7,8,9)); + Tuple2 t1 = s2.get(0); + assertEquals(t1._1().intValue(), 2); + assertEquals(t1._2().intValue(), 7); + Stream intStream = Stream.iterate(0, i -> i + 1) .take(10); @@ -92,7 +149,6 @@ public class CollectionAPIUnitTest { .longValue(); assertEquals(20, evenSum); - assertEquals(new Integer(5), intStream.get(5)); } @Test @@ -102,11 +158,12 @@ public class CollectionAPIUnitTest { assertEquals(3, intArray.size()); assertEquals(2, newArray.size()); + assertEquals(3, newArray.get(1).intValue()); + + Array array2 = intArray.replace(1, 5); + assertEquals(array2.get(0).intValue(), 5); + - assertEquals(new Integer(1), intArray.get(0)); - assertEquals(new Integer(2), intArray.get(1)); - assertEquals(new Integer(3), intArray.get(2)); - assertEquals(new Integer(3), newArray.get(1)); } @Test @@ -117,10 +174,8 @@ public class CollectionAPIUnitTest { assertEquals(4, intVector.size()); assertEquals(4, newVector.size()); - assertEquals(new Integer(1), intVector.get(0)); - assertEquals(new Integer(2), intVector.get(1)); - assertEquals(new Integer(3), intVector.get(2)); - assertEquals(new Integer(6), newVector.get(1)); + assertEquals(2, intVector.get(1).intValue()); + assertEquals(6, newVector.get(1).intValue()); } @Test @@ -143,57 +198,46 @@ public class CollectionAPIUnitTest { assertEquals(3, set.size()); assertEquals(4, newSet.size()); - assertFalse(set.contains("Yellow")); assertTrue(newSet.contains("Yellow")); } @Test public void givenSortedSet_whenIterated_thenCorrect() { SortedSet set = TreeSet.of("Red", "Green", "Blue"); + assertEquals("Blue", set.head()); - Iterator iterator = set.iterator(); - assertEquals("Blue", iterator.next()); - assertEquals("Green", iterator.next()); - assertEquals("Red", iterator.next()); + SortedSet intSet = TreeSet.of(1,2,3); + assertEquals(2, intSet.average().get().intValue()); + } @Test public void givenSortedSet_whenReversed_thenCorrect() { - SortedSet set = TreeSet.of(Comparator.reverseOrder(), "Green", "Red", "Blue"); + SortedSet reversedSet + = TreeSet.of(Comparator.reverseOrder(), "Green", "Red", "Blue"); + assertEquals("Red", reversedSet.head()); - Iterator iterator = set.iterator(); - assertEquals("Red", iterator.next()); - assertEquals("Green", iterator.next()); - assertEquals("Blue", iterator.next()); + String str = reversedSet.mkString(" and "); + assertEquals("Red and Green and Blue", str); } @Test public void givenMap_whenIterated_thenCorrect() { Map> map = List.rangeClosed(0, 10) .groupBy(i -> i % 2); - + assertEquals(2, map.size()); - - Iterator>> iterator = map.iterator(); - assertEquals(6, iterator.next() - ._2() - .size()); - assertEquals(5, iterator.next() - ._2() - .size()); + assertEquals(6, map.get(0).get().size()); + assertEquals(5, map.get(1).get().size()); } @Test public void givenTreeMap_whenIterated_thenCorrect() { - SortedMap map = TreeMap.of(3, "Three", 2, "Two", 4, "Four", 1, "One"); + SortedMap map + = TreeMap.of(3, "Three", 2, "Two", 4, "Four", 1, "One"); - Iterator> iterator = map.iterator(); - assertEquals(new Integer(1), iterator.next() - ._1()); - assertEquals(new Integer(2), iterator.next() - ._1()); - assertEquals(new Integer(3), iterator.next() - ._1()); + assertEquals(1, map.keySet().toJavaArray()[0]); + assertEquals("Four", map.get(4).get()); } @Test @@ -202,14 +246,13 @@ public class CollectionAPIUnitTest { List vavrList = List.ofAll(javaList); assertEquals(4, vavrList.size()); - assertEquals(new Integer(1), vavrList.head()); + assertEquals(1, vavrList.head().intValue()); java.util.stream.Stream javaStream = javaList.stream(); Set vavrSet = HashSet.ofAll(javaStream); assertEquals(4, vavrSet.size()); - assertEquals(new Integer(2), vavrSet.tail() - .head()); + assertEquals(2, vavrSet.tail().head().intValue()); } @Test @@ -220,7 +263,7 @@ public class CollectionAPIUnitTest { .collect(List.collector()); assertEquals(4, vavrList.size()); - assertEquals(new Integer(2), vavrList.head()); + assertEquals(2, vavrList.head().intValue()); } @Test @@ -231,7 +274,7 @@ public class CollectionAPIUnitTest { java.util.Map map = List.of("1", "2", "3") .toJavaMap(i -> Tuple.of(i, Integer.valueOf(i))); - assertEquals(new Integer(2), map.get("2")); + assertEquals(2, map.get("2").intValue()); } @Test @@ -240,8 +283,7 @@ public class CollectionAPIUnitTest { .collect(Collectors.toSet()); assertEquals(3, javaSet.size()); - assertEquals(new Integer(1), javaSet.iterator() - .next()); + assertEquals(1, javaSet.toArray()[0]); } @Test @@ -250,7 +292,7 @@ public class CollectionAPIUnitTest { .asJavaMutable(); javaList.add(4); - assertEquals(new Integer(4), javaList.get(3)); + assertEquals(4, javaList.get(3).intValue()); } @Test(expected = UnsupportedOperationException.class) @@ -258,7 +300,7 @@ public class CollectionAPIUnitTest { java.util.List javaList = List.of(1, 2, 3) .asJava(); - assertEquals(new Integer(3), javaList.get(2)); + assertEquals(3, javaList.get(2).intValue()); javaList.add(4); }