Merge remote-tracking branch 'eugenp/master'

This commit is contained in:
DOHA 2017-08-25 17:45:23 +02:00
commit 29d6807f80
234 changed files with 1887 additions and 1691 deletions

View File

@ -19,13 +19,15 @@ public class NumbersProducer implements Runnable {
try { try {
generateNumbers(); generateNumbers();
} catch (InterruptedException e) { } catch (InterruptedException e) {
Thread.currentThread().interrupt(); Thread.currentThread()
.interrupt();
} }
} }
private void generateNumbers() throws InterruptedException { private void generateNumbers() throws InterruptedException {
for (int i = 0; i < 100; i++) { 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++) { for (int j = 0; j < poisonPillPerProducer; j++) {
numbersQueue.put(poisonPill); numbersQueue.put(poisonPill);

View File

@ -27,9 +27,6 @@ public class DelayObject implements Delayed {
@Override @Override
public String toString() { public String toString() {
return "{" + return "{" + "data='" + data + '\'' + ", startTime=" + startTime + '}';
"data='" + data + '\'' +
", startTime=" + startTime +
'}';
} }
} }

View File

@ -15,7 +15,6 @@ public class CompletableFutureLongRunningUnitTest {
private static final Logger LOG = LoggerFactory.getLogger(CompletableFutureLongRunningUnitTest.class); private static final Logger LOG = LoggerFactory.getLogger(CompletableFutureLongRunningUnitTest.class);
@Test @Test
public void whenRunningCompletableFutureAsynchronously_thenGetMethodWaitsForResult() throws InterruptedException, ExecutionException { public void whenRunningCompletableFutureAsynchronously_thenGetMethodWaitsForResult() throws InterruptedException, ExecutionException {
Future<String> completableFuture = calculateAsync(); Future<String> completableFuture = calculateAsync();
@ -27,11 +26,12 @@ public class CompletableFutureLongRunningUnitTest {
private Future<String> calculateAsync() throws InterruptedException { private Future<String> calculateAsync() throws InterruptedException {
CompletableFuture<String> completableFuture = new CompletableFuture<>(); CompletableFuture<String> completableFuture = new CompletableFuture<>();
Executors.newCachedThreadPool().submit(() -> { Executors.newCachedThreadPool()
Thread.sleep(500); .submit(() -> {
completableFuture.complete("Hello"); Thread.sleep(500);
return null; completableFuture.complete("Hello");
}); return null;
});
return completableFuture; return completableFuture;
} }
@ -47,11 +47,12 @@ public class CompletableFutureLongRunningUnitTest {
private Future<String> calculateAsyncWithCancellation() throws InterruptedException { private Future<String> calculateAsyncWithCancellation() throws InterruptedException {
CompletableFuture<String> completableFuture = new CompletableFuture<>(); CompletableFuture<String> completableFuture = new CompletableFuture<>();
Executors.newCachedThreadPool().submit(() -> { Executors.newCachedThreadPool()
Thread.sleep(500); .submit(() -> {
completableFuture.cancel(false); Thread.sleep(500);
return null; completableFuture.cancel(false);
}); return null;
});
return completableFuture; return completableFuture;
} }
@ -98,21 +99,24 @@ public class CompletableFutureLongRunningUnitTest {
@Test @Test
public void whenUsingThenCompose_thenFuturesExecuteSequentially() throws ExecutionException, InterruptedException { public void whenUsingThenCompose_thenFuturesExecuteSequentially() throws ExecutionException, InterruptedException {
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> "Hello").thenCompose(s -> CompletableFuture.supplyAsync(() -> s + " World")); CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> "Hello")
.thenCompose(s -> CompletableFuture.supplyAsync(() -> s + " World"));
assertEquals("Hello World", completableFuture.get()); assertEquals("Hello World", completableFuture.get());
} }
@Test @Test
public void whenUsingThenCombine_thenWaitForExecutionOfBothFutures() throws ExecutionException, InterruptedException { public void whenUsingThenCombine_thenWaitForExecutionOfBothFutures() throws ExecutionException, InterruptedException {
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> "Hello").thenCombine(CompletableFuture.supplyAsync(() -> " World"), (s1, s2) -> s1 + s2); CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> "Hello")
.thenCombine(CompletableFuture.supplyAsync(() -> " World"), (s1, s2) -> s1 + s2);
assertEquals("Hello World", completableFuture.get()); assertEquals("Hello World", completableFuture.get());
} }
@Test @Test
public void whenUsingThenAcceptBoth_thenWaitForExecutionOfBothFutures() throws ExecutionException, InterruptedException { 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 @Test
@ -131,7 +135,9 @@ public class CompletableFutureLongRunningUnitTest {
assertTrue(future2.isDone()); assertTrue(future2.isDone());
assertTrue(future3.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); assertEquals("Hello Beautiful World", combined);
} }
@ -147,7 +153,8 @@ public class CompletableFutureLongRunningUnitTest {
throw new RuntimeException("Computation error!"); throw new RuntimeException("Computation error!");
} }
return "Hello, " + name; return "Hello, " + name;
}).handle((s, t) -> s != null ? s : "Hello, Stranger!"); })
.handle((s, t) -> s != null ? s : "Hello, Stranger!");
assertEquals("Hello, Stranger!", completableFuture.get()); assertEquals("Hello, Stranger!", completableFuture.get());
} }

View File

@ -47,7 +47,8 @@ public class ConcurrentMapAggregateStatusManualTest {
executorService.awaitTermination(1, TimeUnit.MINUTES); executorService.awaitTermination(1, TimeUnit.MINUTES);
for (int i = 1; i <= MAX_SIZE; i++) { 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()); assertEquals(MAX_SIZE, concurrentMap.size());
} }
@ -69,7 +70,8 @@ public class ConcurrentMapAggregateStatusManualTest {
executorService.shutdown(); executorService.shutdown();
executorService.awaitTermination(1, TimeUnit.MINUTES); 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()); assertEquals(MAX_SIZE, concurrentMap.size());
} }

View File

@ -16,8 +16,12 @@ public class ConcurretMapMemoryConsistencyManualTest {
public void givenConcurrentMap_whenSumParallel_thenCorrect() throws Exception { public void givenConcurrentMap_whenSumParallel_thenCorrect() throws Exception {
Map<String, Integer> map = new ConcurrentHashMap<>(); Map<String, Integer> map = new ConcurrentHashMap<>();
List<Integer> sumList = parallelSum100(map, 1000); List<Integer> sumList = parallelSum100(map, 1000);
assertEquals(1, sumList.stream().distinct().count()); assertEquals(1, sumList.stream()
long wrongResultCount = sumList.stream().filter(num -> num != 100).count(); .distinct()
.count());
long wrongResultCount = sumList.stream()
.filter(num -> num != 100)
.count();
assertEquals(0, wrongResultCount); assertEquals(0, wrongResultCount);
} }
@ -25,8 +29,12 @@ public class ConcurretMapMemoryConsistencyManualTest {
public void givenHashtable_whenSumParallel_thenCorrect() throws Exception { public void givenHashtable_whenSumParallel_thenCorrect() throws Exception {
Map<String, Integer> map = new Hashtable<>(); Map<String, Integer> map = new Hashtable<>();
List<Integer> sumList = parallelSum100(map, 1000); List<Integer> sumList = parallelSum100(map, 1000);
assertEquals(1, sumList.stream().distinct().count()); assertEquals(1, sumList.stream()
long wrongResultCount = sumList.stream().filter(num -> num != 100).count(); .distinct()
.count());
long wrongResultCount = sumList.stream()
.filter(num -> num != 100)
.count();
assertEquals(0, wrongResultCount); assertEquals(0, wrongResultCount);
} }
@ -34,8 +42,12 @@ public class ConcurretMapMemoryConsistencyManualTest {
public void givenHashMap_whenSumParallel_thenError() throws Exception { public void givenHashMap_whenSumParallel_thenError() throws Exception {
Map<String, Integer> map = new HashMap<>(); Map<String, Integer> map = new HashMap<>();
List<Integer> sumList = parallelSum100(map, 100); List<Integer> sumList = parallelSum100(map, 100);
assertNotEquals(1, sumList.stream().distinct().count()); assertNotEquals(1, sumList.stream()
long wrongResultCount = sumList.stream().filter(num -> num != 100).count(); .distinct()
.count());
long wrongResultCount = sumList.stream()
.filter(num -> num != 100)
.count();
assertTrue(wrongResultCount > 0); assertTrue(wrongResultCount > 0);
} }

View File

@ -4,11 +4,11 @@ public class LuxuryCarsSpeed {
public double bugattiVeyronInMPH() { public double bugattiVeyronInMPH() {
return 268; return 268;
} }
public double mcLarenInMPH() { public double mcLarenInMPH() {
return 241; return 241;
} }
public double astonMartinInMPH() { public double astonMartinInMPH() {
return 220; return 220;
} }

View File

@ -2,6 +2,8 @@ package com.baeldung.designpatterns.adapter;
public interface LuxuryCarsSpeedAdapter { public interface LuxuryCarsSpeedAdapter {
public double bugattiVeyronInKMPH(); public double bugattiVeyronInKMPH();
public double mcLarenInKMPH(); public double mcLarenInKMPH();
public double astonMartinInKMPH(); public double astonMartinInKMPH();
} }

View File

@ -5,7 +5,7 @@ import static com.baeldung.designpatterns.util.LogerUtil.LOG;
public class Blue implements Color { public class Blue implements Color {
@Override @Override
public void fillColor() { public void fillColor() {
LOG.info("Color : Blue"); LOG.info("Color : Blue");
} }

View File

@ -5,16 +5,14 @@ import static com.baeldung.designpatterns.util.LogerUtil.LOG;
public class DecoratorPatternDriver { public class DecoratorPatternDriver {
public static void main(String[] args) { public static void main(String[] args) {
//christmas tree with just one Garland // christmas tree with just one Garland
ChristmasTree tree1 = new Garland(new ChristmasTreeImpl()); ChristmasTree tree1 = new Garland(new ChristmasTreeImpl());
LOG.info(tree1.decorate()); LOG.info(tree1.decorate());
//christmas tree with two Garlands and one Bubble lights // christmas tree with two Garlands and one Bubble lights
ChristmasTree tree2 = new BubbleLights(new Garland( ChristmasTree tree2 = new BubbleLights(new Garland(new Garland(new ChristmasTreeImpl())));
new Garland(new ChristmasTreeImpl()))
);
LOG.info(tree2.decorate()); LOG.info(tree2.decorate());
} }
} }

View File

@ -7,14 +7,14 @@ public class ExpensiveObjectImpl implements ExpensiveObject {
public ExpensiveObjectImpl() { public ExpensiveObjectImpl() {
heavyInitialConfiguration(); heavyInitialConfiguration();
} }
@Override @Override
public void process() { public void process() {
LOG.info("processing complete."); LOG.info("processing complete.");
} }
private void heavyInitialConfiguration() { private void heavyInitialConfiguration() {
LOG.info("Loading initial configuration..."); LOG.info("Loading initial configuration...");
} }
} }

View File

@ -43,6 +43,7 @@ public class CustomRecursiveAction extends RecursiveAction {
private void processing(String work) { private void processing(String work) {
String result = work.toUpperCase(); 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());
} }
} }

View File

@ -5,6 +5,6 @@ import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)
public @interface Greeter { public @interface Greeter {
public String greet() default ""; public String greet() default "";
} }

View File

@ -44,7 +44,8 @@ public class MapIteration {
} }
public void iterateUsingIteratorAndEntry(Map<String, Integer> map) { public void iterateUsingIteratorAndEntry(Map<String, Integer> map) {
Iterator<Map.Entry<String, Integer>> iterator = map.entrySet().iterator(); Iterator<Map.Entry<String, Integer>> iterator = map.entrySet()
.iterator();
while (iterator.hasNext()) { while (iterator.hasNext()) {
Map.Entry<String, Integer> pair = iterator.next(); Map.Entry<String, Integer> pair = iterator.next();
System.out.println(pair.getKey() + ":" + pair.getValue()); System.out.println(pair.getKey() + ":" + pair.getValue());
@ -58,7 +59,9 @@ public class MapIteration {
} }
public void iterateUsingStreamAPI(Map<String, Integer> map) { public void iterateUsingStreamAPI(Map<String, Integer> 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<String, Integer> map) { public void iterateKeys(Map<String, Integer> map) {

View File

@ -8,7 +8,7 @@ public class BigIntegerImpl {
BigInteger numStarsMilkyWay = new BigInteger("8731409320171337804361260816606476"); BigInteger numStarsMilkyWay = new BigInteger("8731409320171337804361260816606476");
BigInteger numStarsAndromeda = new BigInteger("5379309320171337804361260816606476"); BigInteger numStarsAndromeda = new BigInteger("5379309320171337804361260816606476");
BigInteger totalStars = numStarsMilkyWay.add(numStarsAndromeda); BigInteger totalStars = numStarsMilkyWay.add(numStarsAndromeda);
} }

View File

@ -9,7 +9,8 @@ public class PersistentCookieStore implements CookieStore, Runnable {
public PersistentCookieStore() { public PersistentCookieStore() {
store = new CookieManager().getCookieStore(); store = new CookieManager().getCookieStore();
// deserialize cookies into store // deserialize cookies into store
Runtime.getRuntime().addShutdownHook(new Thread(this)); Runtime.getRuntime()
.addShutdownHook(new Thread(this));
} }
@Override @Override

View File

@ -14,7 +14,8 @@ public class Screenshot {
} }
public void getScreenshot(int timeToWait) throws Exception { 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(); Robot robot = new Robot();
BufferedImage img = robot.createScreenCapture(rectangle); BufferedImage img = robot.createScreenCapture(rectangle);
ImageIO.write(img, "jpg", new File(path)); ImageIO.write(img, "jpg", new File(path));

View File

@ -6,16 +6,16 @@ import java.security.NoSuchAlgorithmException;
import java.util.UUID; import java.util.UUID;
public class UUIDGenerator { public class UUIDGenerator {
/** /**
* These are predefined UUID for name spaces * These are predefined UUID for name spaces
*/ */
private static final String NAMESPACE_DNS = "6ba7b810-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_URL = "6ba7b811-9dad-11d1-80b4-00c04fd430c8";
private static final String NAMESPACE_OID = "6ba7b812-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_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) { public static void main(String[] args) {
try { try {
@ -35,7 +35,7 @@ public class UUIDGenerator {
UUID uuid = UUID.randomUUID(); UUID uuid = UUID.randomUUID();
return uuid; return uuid;
} }
/** /**
* Type 3 UUID Generation * Type 3 UUID Generation
* *
@ -47,7 +47,7 @@ public class UUIDGenerator {
UUID uuid = UUID.nameUUIDFromBytes(bytes); UUID uuid = UUID.nameUUIDFromBytes(bytes);
return uuid; return uuid;
} }
/** /**
* Type 5 UUID Generation * Type 5 UUID Generation
* *
@ -59,8 +59,7 @@ public class UUIDGenerator {
UUID uuid = type5UUIDFromBytes(bytes); UUID uuid = type5UUIDFromBytes(bytes);
return uuid; return uuid;
} }
public static UUID type5UUIDFromBytes(byte[] name) { public static UUID type5UUIDFromBytes(byte[] name) {
MessageDigest md; MessageDigest md;
try { try {
@ -69,27 +68,26 @@ public class UUIDGenerator {
throw new InternalError("MD5 not supported", nsae); throw new InternalError("MD5 not supported", nsae);
} }
byte[] bytes = md.digest(name); byte[] bytes = md.digest(name);
bytes[6] &= 0x0f; /* clear version */ bytes[6] &= 0x0f; /* clear version */
bytes[6] |= 0x50; /* set to version 5 */ bytes[6] |= 0x50; /* set to version 5 */
bytes[8] &= 0x3f; /* clear variant */ bytes[8] &= 0x3f; /* clear variant */
bytes[8] |= 0x80; /* set to IETF variant */ bytes[8] |= 0x80; /* set to IETF variant */
return constructType5UUID(bytes); return constructType5UUID(bytes);
} }
private static UUID constructType5UUID(byte[] data) { private static UUID constructType5UUID(byte[] data) {
long msb = 0; long msb = 0;
long lsb = 0; long lsb = 0;
assert data.length == 16 : "data must be 16 bytes in length"; 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); 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); lsb = (lsb << 8) | (data[i] & 0xff);
return new UUID(msb, lsb); return new UUID(msb, lsb);
} }
/** /**
* Unique Keys Generation Using Message Digest and Type 4 UUID * Unique Keys Generation Using Message Digest and Type 4 UUID
* *

View File

@ -15,7 +15,9 @@ public class UseLocalDateTimeUnitTest {
@Test @Test
public void givenString_whenUsingParse_thenLocalDateTime() { public void givenString_whenUsingParse_thenLocalDateTime() {
assertEquals(LocalDate.of(2016, Month.MAY, 10), useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30").toLocalDate()); assertEquals(LocalDate.of(2016, Month.MAY, 10), useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30")
assertEquals(LocalTime.of(6, 30), useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30").toLocalTime()); .toLocalDate());
assertEquals(LocalTime.of(6, 30), useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30")
.toLocalTime());
} }
} }

View File

@ -15,12 +15,14 @@ public class UseLocalDateUnitTest {
@Test @Test
public void givenValues_whenUsingFactoryOf_thenLocalDate() { 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 @Test
public void givenString_whenUsingParse_thenLocalDate() { 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 @Test
@ -30,12 +32,14 @@ public class UseLocalDateUnitTest {
@Test @Test
public void givenDate_whenUsingPlus_thenNextDay() { public void givenDate_whenUsingPlus_thenNextDay() {
assertEquals(LocalDate.now().plusDays(1), useLocalDate.getNextDay(LocalDate.now())); assertEquals(LocalDate.now()
.plusDays(1), useLocalDate.getNextDay(LocalDate.now()));
} }
@Test @Test
public void givenDate_whenUsingMinus_thenPreviousDay() { public void givenDate_whenUsingMinus_thenPreviousDay() {
assertEquals(LocalDate.now().minusDays(1), useLocalDate.getPreviousDay(LocalDate.now())); assertEquals(LocalDate.now()
.minusDays(1), useLocalDate.getPreviousDay(LocalDate.now()));
} }
@Test @Test
@ -45,7 +49,8 @@ public class UseLocalDateUnitTest {
@Test @Test
public void givenToday_whenUsingWithTemporalAdjuster_thenFirstDayOfMonth() { public void givenToday_whenUsingWithTemporalAdjuster_thenFirstDayOfMonth() {
assertEquals(1, useLocalDate.getFirstDayOfMonth().getDayOfMonth()); assertEquals(1, useLocalDate.getFirstDayOfMonth()
.getDayOfMonth());
} }
@Test @Test

View File

@ -21,7 +21,6 @@ public class FunctionalInterfaceUnitTest {
private static final Logger LOG = LoggerFactory.getLogger(FunctionalInterfaceUnitTest.class); private static final Logger LOG = LoggerFactory.getLogger(FunctionalInterfaceUnitTest.class);
@Test @Test
public void whenPassingLambdaToComputeIfAbsent_thenTheValueGetsComputedAndPutIntoMap() { public void whenPassingLambdaToComputeIfAbsent_thenTheValueGetsComputedAndPutIntoMap() {
Map<String, Integer> nameMap = new HashMap<>(); Map<String, Integer> nameMap = new HashMap<>();
@ -83,7 +82,8 @@ public class FunctionalInterfaceUnitTest {
return result; return result;
}); });
List<Integer> fibonacci5 = fibonacci.limit(5).collect(Collectors.toList()); List<Integer> fibonacci5 = fibonacci.limit(5)
.collect(Collectors.toList());
assertEquals(new Integer(1), fibonacci5.get(0)); assertEquals(new Integer(1), fibonacci5.get(0));
assertEquals(new Integer(1), fibonacci5.get(1)); assertEquals(new Integer(1), fibonacci5.get(1));
@ -112,7 +112,9 @@ public class FunctionalInterfaceUnitTest {
public void whenUsingPredicateInFilter_thenListValuesAreFilteredOut() { public void whenUsingPredicateInFilter_thenListValuesAreFilteredOut() {
List<String> names = Arrays.asList("Angela", "Aaron", "Bob", "Claire", "David"); List<String> names = Arrays.asList("Angela", "Aaron", "Bob", "Claire", "David");
List<String> namesWithA = names.stream().filter(name -> name.startsWith("A")).collect(Collectors.toList()); List<String> namesWithA = names.stream()
.filter(name -> name.startsWith("A"))
.collect(Collectors.toList());
assertEquals(2, namesWithA.size()); assertEquals(2, namesWithA.size());
assertTrue(namesWithA.contains("Angela")); assertTrue(namesWithA.contains("Angela"));
@ -135,7 +137,8 @@ public class FunctionalInterfaceUnitTest {
List<Integer> values = Arrays.asList(3, 5, 8, 9, 12); List<Integer> 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); assertEquals(37, sum);

View File

@ -13,35 +13,26 @@ import static org.junit.Assert.*;
public class Java8GroupingByCollectorUnitTest { public class Java8GroupingByCollectorUnitTest {
private static final List<BlogPost> posts = Arrays.asList( private static final List<BlogPost> 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("News item 1", "Author 1", BlogPostType.NEWS, 15), 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));
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 @Test
public void givenAListOfPosts_whenGroupedByType_thenGetAMapBetweenTypeAndPosts() { public void givenAListOfPosts_whenGroupedByType_thenGetAMapBetweenTypeAndPosts() {
Map<BlogPostType, List<BlogPost>> postsPerType = posts Map<BlogPostType, List<BlogPost>> postsPerType = posts.stream()
.stream() .collect(groupingBy(BlogPost::getType));
.collect(groupingBy(BlogPost::getType));
assertEquals(2, postsPerType assertEquals(2, postsPerType.get(BlogPostType.NEWS)
.get(BlogPostType.NEWS) .size());
.size()); assertEquals(1, postsPerType.get(BlogPostType.GUIDE)
assertEquals(1, postsPerType .size());
.get(BlogPostType.GUIDE) assertEquals(2, postsPerType.get(BlogPostType.REVIEW)
.size()); .size());
assertEquals(2, postsPerType
.get(BlogPostType.REVIEW)
.size());
} }
@Test @Test
public void givenAListOfPosts_whenGroupedByTypeAndTheirTitlesAreJoinedInAString_thenGetAMapBetweenTypeAndCsvTitles() { public void givenAListOfPosts_whenGroupedByTypeAndTheirTitlesAreJoinedInAString_thenGetAMapBetweenTypeAndCsvTitles() {
Map<BlogPostType, String> postsPerType = posts Map<BlogPostType, String> postsPerType = posts.stream()
.stream() .collect(groupingBy(BlogPost::getType, mapping(BlogPost::getTitle, joining(", ", "Post titles: [", "]"))));
.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: [News item 1, News item 2]", postsPerType.get(BlogPostType.NEWS));
assertEquals("Post titles: [Programming guide]", postsPerType.get(BlogPostType.GUIDE)); assertEquals("Post titles: [Programming guide]", postsPerType.get(BlogPostType.GUIDE));
@ -50,174 +41,135 @@ public class Java8GroupingByCollectorUnitTest {
@Test @Test
public void givenAListOfPosts_whenGroupedByTypeAndSumTheLikes_thenGetAMapBetweenTypeAndPostLikes() { public void givenAListOfPosts_whenGroupedByTypeAndSumTheLikes_thenGetAMapBetweenTypeAndPostLikes() {
Map<BlogPostType, Integer> likesPerType = posts Map<BlogPostType, Integer> likesPerType = posts.stream()
.stream() .collect(groupingBy(BlogPost::getType, summingInt(BlogPost::getLikes)));
.collect(groupingBy(BlogPost::getType, summingInt(BlogPost::getLikes)));
assertEquals(50, likesPerType assertEquals(50, likesPerType.get(BlogPostType.NEWS)
.get(BlogPostType.NEWS) .intValue());
.intValue()); assertEquals(20, likesPerType.get(BlogPostType.REVIEW)
assertEquals(20, likesPerType .intValue());
.get(BlogPostType.REVIEW) assertEquals(20, likesPerType.get(BlogPostType.GUIDE)
.intValue()); .intValue());
assertEquals(20, likesPerType
.get(BlogPostType.GUIDE)
.intValue());
} }
@Test @Test
public void givenAListOfPosts_whenGroupedByTypeInAnEnumMap_thenGetAnEnumMapBetweenTypeAndPosts() { public void givenAListOfPosts_whenGroupedByTypeInAnEnumMap_thenGetAnEnumMapBetweenTypeAndPosts() {
EnumMap<BlogPostType, List<BlogPost>> postsPerType = posts EnumMap<BlogPostType, List<BlogPost>> postsPerType = posts.stream()
.stream() .collect(groupingBy(BlogPost::getType, () -> new EnumMap<>(BlogPostType.class), toList()));
.collect(groupingBy(BlogPost::getType, () -> new EnumMap<>(BlogPostType.class), toList()));
assertEquals(2, postsPerType assertEquals(2, postsPerType.get(BlogPostType.NEWS)
.get(BlogPostType.NEWS) .size());
.size()); assertEquals(1, postsPerType.get(BlogPostType.GUIDE)
assertEquals(1, postsPerType .size());
.get(BlogPostType.GUIDE) assertEquals(2, postsPerType.get(BlogPostType.REVIEW)
.size()); .size());
assertEquals(2, postsPerType
.get(BlogPostType.REVIEW)
.size());
} }
@Test @Test
public void givenAListOfPosts_whenGroupedByTypeInSets_thenGetAMapBetweenTypesAndSetsOfPosts() { public void givenAListOfPosts_whenGroupedByTypeInSets_thenGetAMapBetweenTypesAndSetsOfPosts() {
Map<BlogPostType, Set<BlogPost>> postsPerType = posts Map<BlogPostType, Set<BlogPost>> postsPerType = posts.stream()
.stream() .collect(groupingBy(BlogPost::getType, toSet()));
.collect(groupingBy(BlogPost::getType, toSet()));
assertEquals(2, postsPerType assertEquals(2, postsPerType.get(BlogPostType.NEWS)
.get(BlogPostType.NEWS) .size());
.size()); assertEquals(1, postsPerType.get(BlogPostType.GUIDE)
assertEquals(1, postsPerType .size());
.get(BlogPostType.GUIDE) assertEquals(2, postsPerType.get(BlogPostType.REVIEW)
.size()); .size());
assertEquals(2, postsPerType
.get(BlogPostType.REVIEW)
.size());
} }
@Test @Test
public void givenAListOfPosts_whenGroupedByTypeConcurrently_thenGetAMapBetweenTypeAndPosts() { public void givenAListOfPosts_whenGroupedByTypeConcurrently_thenGetAMapBetweenTypeAndPosts() {
ConcurrentMap<BlogPostType, List<BlogPost>> postsPerType = posts ConcurrentMap<BlogPostType, List<BlogPost>> postsPerType = posts.parallelStream()
.parallelStream() .collect(groupingByConcurrent(BlogPost::getType));
.collect(groupingByConcurrent(BlogPost::getType));
assertEquals(2, postsPerType assertEquals(2, postsPerType.get(BlogPostType.NEWS)
.get(BlogPostType.NEWS) .size());
.size()); assertEquals(1, postsPerType.get(BlogPostType.GUIDE)
assertEquals(1, postsPerType .size());
.get(BlogPostType.GUIDE) assertEquals(2, postsPerType.get(BlogPostType.REVIEW)
.size()); .size());
assertEquals(2, postsPerType
.get(BlogPostType.REVIEW)
.size());
} }
@Test @Test
public void givenAListOfPosts_whenGroupedByTypeAndAveragingLikes_thenGetAMapBetweenTypeAndAverageNumberOfLikes() { public void givenAListOfPosts_whenGroupedByTypeAndAveragingLikes_thenGetAMapBetweenTypeAndAverageNumberOfLikes() {
Map<BlogPostType, Double> averageLikesPerType = posts Map<BlogPostType, Double> averageLikesPerType = posts.stream()
.stream() .collect(groupingBy(BlogPost::getType, averagingInt(BlogPost::getLikes)));
.collect(groupingBy(BlogPost::getType, averagingInt(BlogPost::getLikes)));
assertEquals(25, averageLikesPerType assertEquals(25, averageLikesPerType.get(BlogPostType.NEWS)
.get(BlogPostType.NEWS) .intValue());
.intValue()); assertEquals(20, averageLikesPerType.get(BlogPostType.GUIDE)
assertEquals(20, averageLikesPerType .intValue());
.get(BlogPostType.GUIDE) assertEquals(10, averageLikesPerType.get(BlogPostType.REVIEW)
.intValue()); .intValue());
assertEquals(10, averageLikesPerType
.get(BlogPostType.REVIEW)
.intValue());
} }
@Test @Test
public void givenAListOfPosts_whenGroupedByTypeAndCounted_thenGetAMapBetweenTypeAndNumberOfPosts() { public void givenAListOfPosts_whenGroupedByTypeAndCounted_thenGetAMapBetweenTypeAndNumberOfPosts() {
Map<BlogPostType, Long> numberOfPostsPerType = posts Map<BlogPostType, Long> numberOfPostsPerType = posts.stream()
.stream() .collect(groupingBy(BlogPost::getType, counting()));
.collect(groupingBy(BlogPost::getType, counting()));
assertEquals(2, numberOfPostsPerType assertEquals(2, numberOfPostsPerType.get(BlogPostType.NEWS)
.get(BlogPostType.NEWS) .intValue());
.intValue()); assertEquals(1, numberOfPostsPerType.get(BlogPostType.GUIDE)
assertEquals(1, numberOfPostsPerType .intValue());
.get(BlogPostType.GUIDE) assertEquals(2, numberOfPostsPerType.get(BlogPostType.REVIEW)
.intValue()); .intValue());
assertEquals(2, numberOfPostsPerType
.get(BlogPostType.REVIEW)
.intValue());
} }
@Test @Test
public void givenAListOfPosts_whenGroupedByTypeAndMaxingLikes_thenGetAMapBetweenTypeAndMaximumNumberOfLikes() { public void givenAListOfPosts_whenGroupedByTypeAndMaxingLikes_thenGetAMapBetweenTypeAndMaximumNumberOfLikes() {
Map<BlogPostType, Optional<BlogPost>> maxLikesPerPostType = posts Map<BlogPostType, Optional<BlogPost>> maxLikesPerPostType = posts.stream()
.stream() .collect(groupingBy(BlogPost::getType, maxBy(comparingInt(BlogPost::getLikes))));
.collect(groupingBy(BlogPost::getType, maxBy(comparingInt(BlogPost::getLikes))));
assertTrue(maxLikesPerPostType assertTrue(maxLikesPerPostType.get(BlogPostType.NEWS)
.get(BlogPostType.NEWS) .isPresent());
.isPresent()); assertEquals(35, maxLikesPerPostType.get(BlogPostType.NEWS)
assertEquals(35, maxLikesPerPostType .get()
.get(BlogPostType.NEWS) .getLikes());
.get()
.getLikes());
assertTrue(maxLikesPerPostType assertTrue(maxLikesPerPostType.get(BlogPostType.GUIDE)
.get(BlogPostType.GUIDE) .isPresent());
.isPresent()); assertEquals(20, maxLikesPerPostType.get(BlogPostType.GUIDE)
assertEquals(20, maxLikesPerPostType .get()
.get(BlogPostType.GUIDE) .getLikes());
.get()
.getLikes());
assertTrue(maxLikesPerPostType assertTrue(maxLikesPerPostType.get(BlogPostType.REVIEW)
.get(BlogPostType.REVIEW) .isPresent());
.isPresent()); assertEquals(15, maxLikesPerPostType.get(BlogPostType.REVIEW)
assertEquals(15, maxLikesPerPostType .get()
.get(BlogPostType.REVIEW) .getLikes());
.get()
.getLikes());
} }
@Test @Test
public void givenAListOfPosts_whenGroupedByAuthorAndThenByType_thenGetAMapBetweenAuthorAndMapsBetweenTypeAndBlogPosts() { public void givenAListOfPosts_whenGroupedByAuthorAndThenByType_thenGetAMapBetweenAuthorAndMapsBetweenTypeAndBlogPosts() {
Map<String, Map<BlogPostType, List<BlogPost>>> map = posts Map<String, Map<BlogPostType, List<BlogPost>>> map = posts.stream()
.stream() .collect(groupingBy(BlogPost::getAuthor, groupingBy(BlogPost::getType)));
.collect(groupingBy(BlogPost::getAuthor, groupingBy(BlogPost::getType)));
assertEquals(1, map assertEquals(1, map.get("Author 1")
.get("Author 1") .get(BlogPostType.NEWS)
.get(BlogPostType.NEWS) .size());
.size()); assertEquals(1, map.get("Author 1")
assertEquals(1, map .get(BlogPostType.GUIDE)
.get("Author 1") .size());
.get(BlogPostType.GUIDE) assertEquals(1, map.get("Author 1")
.size()); .get(BlogPostType.REVIEW)
assertEquals(1, map .size());
.get("Author 1")
.get(BlogPostType.REVIEW)
.size());
assertEquals(1, map assertEquals(1, map.get("Author 2")
.get("Author 2") .get(BlogPostType.NEWS)
.get(BlogPostType.NEWS) .size());
.size()); assertEquals(1, map.get("Author 2")
assertEquals(1, map .get(BlogPostType.REVIEW)
.get("Author 2") .size());
.get(BlogPostType.REVIEW) assertNull(map.get("Author 2")
.size()); .get(BlogPostType.GUIDE));
assertNull(map
.get("Author 2")
.get(BlogPostType.GUIDE));
} }
@Test @Test
public void givenAListOfPosts_whenGroupedByTypeAndSummarizingLikes_thenGetAMapBetweenTypeAndSummary() { public void givenAListOfPosts_whenGroupedByTypeAndSummarizingLikes_thenGetAMapBetweenTypeAndSummary() {
Map<BlogPostType, IntSummaryStatistics> likeStatisticsPerType = posts Map<BlogPostType, IntSummaryStatistics> likeStatisticsPerType = posts.stream()
.stream() .collect(groupingBy(BlogPost::getType, summarizingInt(BlogPost::getLikes)));
.collect(groupingBy(BlogPost::getType, summarizingInt(BlogPost::getLikes)));
IntSummaryStatistics newsLikeStatistics = likeStatisticsPerType.get(BlogPostType.NEWS); IntSummaryStatistics newsLikeStatistics = likeStatisticsPerType.get(BlogPostType.NEWS);

View File

@ -17,8 +17,8 @@ public class Java8MapAndFlatMap {
@Test @Test
public void givenStream_whenCalledMap_thenProduceList() { public void givenStream_whenCalledMap_thenProduceList() {
List<String> myList = Stream.of("a", "b") List<String> myList = Stream.of("a", "b")
.map(String::toUpperCase) .map(String::toUpperCase)
.collect(Collectors.toList()); .collect(Collectors.toList());
assertEquals(asList("A", "B"), myList); assertEquals(asList("A", "B"), myList);
} }
@ -27,9 +27,9 @@ public class Java8MapAndFlatMap {
List<List<String>> list = Arrays.asList(Arrays.asList("a"), Arrays.asList("b")); List<List<String>> list = Arrays.asList(Arrays.asList("a"), Arrays.asList("b"));
System.out.println(list); System.out.println(list);
System.out.println(list System.out.println(list.stream()
.stream().flatMap(Collection::stream) .flatMap(Collection::stream)
.collect(Collectors.toList())); .collect(Collectors.toList()));
} }
@Test @Test
@ -40,13 +40,11 @@ public class Java8MapAndFlatMap {
@Test @Test
public void givenOptional_whenCalledFlatMap_thenProduceFlattenedOptional() { public void givenOptional_whenCalledFlatMap_thenProduceFlattenedOptional() {
assertEquals(Optional.of(Optional.of("STRING")), Optional assertEquals(Optional.of(Optional.of("STRING")), Optional.of("string")
.of("string") .map(s -> Optional.of("STRING")));
.map(s -> Optional.of("STRING")));
assertEquals(Optional.of("STRING"), Optional assertEquals(Optional.of("STRING"), Optional.of("string")
.of("string") .flatMap(s -> Optional.of("STRING")));
.flatMap(s -> Optional.of("STRING")));
} }
} }

View File

@ -55,7 +55,12 @@ public class JavaFolderSizeUnitTest {
@Test @Test
public void whenGetFolderSizeUsingJava8_thenCorrect() throws IOException { public void whenGetFolderSizeUsingJava8_thenCorrect() throws IOException {
final Path folder = Paths.get(path); 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); assertEquals(EXPECTED_SIZE, size);
} }
@ -72,8 +77,12 @@ public class JavaFolderSizeUnitTest {
public void whenGetFolderSizeUsingGuava_thenCorrect() { public void whenGetFolderSizeUsingGuava_thenCorrect() {
final File folder = new File(path); final File folder = new File(path);
final Iterable<File> files = com.google.common.io.Files.fileTreeTraverser().breadthFirstTraversal(folder); final Iterable<File> files = com.google.common.io.Files.fileTreeTraverser()
final long size = StreamSupport.stream(files.spliterator(), false).filter(File::isFile).mapToLong(File::length).sum(); .breadthFirstTraversal(folder);
final long size = StreamSupport.stream(files.spliterator(), false)
.filter(File::isFile)
.mapToLong(File::length)
.sum();
assertEquals(EXPECTED_SIZE, size); assertEquals(EXPECTED_SIZE, size);
} }

View File

@ -1,4 +1,5 @@
package com.baeldung.java8.comparator; package com.baeldung.java8.comparator;
import java.util.Arrays; import java.util.Arrays;
import java.util.Comparator; import java.util.Comparator;
@ -25,44 +26,32 @@ public class Java8ComparatorUnitTest {
@Before @Before
public void initData() { public void initData() {
employees = new Employee[] { new Employee("John", 25, 3000, 9922001), new Employee("Ace", 22, 2000, 5924001), employees = new Employee[] { new Employee("John", 25, 3000, 9922001), new Employee("Ace", 22, 2000, 5924001), new Employee("Keith", 35, 4000, 3924401) };
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) };
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), sortedEmployeesByName = new Employee[] { new Employee("Ace", 22, 2000, 5924001), new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) };
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) };
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), sortedEmployeesByAge = new Employee[] { new Employee("Ace", 22, 2000, 5924001), new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) };
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), sortedEmployeesByMobile = new Employee[] { new Employee("Keith", 35, 4000, 3924401), new Employee("Ace", 22, 2000, 5924001), new Employee("John", 25, 3000, 9922001), };
new Employee("John", 25, 3000, 9922001), };
sortedEmployeesBySalary = new Employee[] { 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), };
new Employee("Keith", 35, 4000, 3924401), };
sortedEmployeesArray_WithNullsFirst = new Employee[] { null, null, new Employee("Ace", 22, 2000, 5924001), sortedEmployeesArray_WithNullsFirst = new Employee[] { null, null, new Employee("Ace", 22, 2000, 5924001), new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) };
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_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), 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) };
new Employee("Ace", 22, 3000, 6423001), new Employee("Keith", 35, 4000, 3924401) };
sortedEmployeesByAgeName = new Employee[] { new Employee("Ace", 22, 3000, 6423001), 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) };
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) };
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 @Test
public void whenComparing_thenSortedByName() { public void whenComparing_thenSortedByName() {
Comparator<Employee> employeeNameComparator = Comparator.comparing(Employee::getName); Comparator<Employee> employeeNameComparator = Comparator.comparing(Employee::getName);
Arrays.sort(employees, employeeNameComparator); Arrays.sort(employees, employeeNameComparator);
// System.out.println(Arrays.toString(employees)); // System.out.println(Arrays.toString(employees));
assertTrue(Arrays.equals(employees, sortedEmployeesByName)); assertTrue(Arrays.equals(employees, sortedEmployeesByName));
} }
@ -72,16 +61,16 @@ public class Java8ComparatorUnitTest {
return s2.compareTo(s1); return s2.compareTo(s1);
}); });
Arrays.sort(employees, employeeNameComparator); Arrays.sort(employees, employeeNameComparator);
// System.out.println(Arrays.toString(employees)); // System.out.println(Arrays.toString(employees));
assertTrue(Arrays.equals(employees, sortedEmployeesByNameDesc)); assertTrue(Arrays.equals(employees, sortedEmployeesByNameDesc));
} }
@Test @Test
public void whenReversed_thenSortedByNameDesc() { public void whenReversed_thenSortedByNameDesc() {
Comparator<Employee> employeeNameComparator = Comparator.comparing(Employee::getName); Comparator<Employee> employeeNameComparator = Comparator.comparing(Employee::getName);
Comparator<Employee> employeeNameComparatorReversed = employeeNameComparator.reversed(); Comparator<Employee> employeeNameComparatorReversed = employeeNameComparator.reversed();
Arrays.sort(employees, employeeNameComparatorReversed); Arrays.sort(employees, employeeNameComparatorReversed);
// System.out.println(Arrays.toString(employees)); // System.out.println(Arrays.toString(employees));
assertTrue(Arrays.equals(employees, sortedEmployeesByNameDesc)); assertTrue(Arrays.equals(employees, sortedEmployeesByNameDesc));
} }
@ -89,7 +78,7 @@ public class Java8ComparatorUnitTest {
public void whenComparingInt_thenSortedByAge() { public void whenComparingInt_thenSortedByAge() {
Comparator<Employee> employeeAgeComparator = Comparator.comparingInt(Employee::getAge); Comparator<Employee> employeeAgeComparator = Comparator.comparingInt(Employee::getAge);
Arrays.sort(employees, employeeAgeComparator); Arrays.sort(employees, employeeAgeComparator);
// System.out.println(Arrays.toString(employees)); // System.out.println(Arrays.toString(employees));
assertTrue(Arrays.equals(employees, sortedEmployeesByAge)); assertTrue(Arrays.equals(employees, sortedEmployeesByAge));
} }
@ -97,7 +86,7 @@ public class Java8ComparatorUnitTest {
public void whenComparingLong_thenSortedByMobile() { public void whenComparingLong_thenSortedByMobile() {
Comparator<Employee> employeeMobileComparator = Comparator.comparingLong(Employee::getMobile); Comparator<Employee> employeeMobileComparator = Comparator.comparingLong(Employee::getMobile);
Arrays.sort(employees, employeeMobileComparator); Arrays.sort(employees, employeeMobileComparator);
// System.out.println(Arrays.toString(employees)); // System.out.println(Arrays.toString(employees));
assertTrue(Arrays.equals(employees, sortedEmployeesByMobile)); assertTrue(Arrays.equals(employees, sortedEmployeesByMobile));
} }
@ -105,7 +94,7 @@ public class Java8ComparatorUnitTest {
public void whenComparingDouble_thenSortedBySalary() { public void whenComparingDouble_thenSortedBySalary() {
Comparator<Employee> employeeSalaryComparator = Comparator.comparingDouble(Employee::getSalary); Comparator<Employee> employeeSalaryComparator = Comparator.comparingDouble(Employee::getSalary);
Arrays.sort(employees, employeeSalaryComparator); Arrays.sort(employees, employeeSalaryComparator);
// System.out.println(Arrays.toString(employees)); // System.out.println(Arrays.toString(employees));
assertTrue(Arrays.equals(employees, sortedEmployeesBySalary)); assertTrue(Arrays.equals(employees, sortedEmployeesBySalary));
} }
@ -113,7 +102,7 @@ public class Java8ComparatorUnitTest {
public void whenNaturalOrder_thenSortedByName() { public void whenNaturalOrder_thenSortedByName() {
Comparator<Employee> employeeNameComparator = Comparator.<Employee> naturalOrder(); Comparator<Employee> employeeNameComparator = Comparator.<Employee> naturalOrder();
Arrays.sort(employees, employeeNameComparator); Arrays.sort(employees, employeeNameComparator);
// System.out.println(Arrays.toString(employees)); // System.out.println(Arrays.toString(employees));
assertTrue(Arrays.equals(employees, sortedEmployeesByName)); assertTrue(Arrays.equals(employees, sortedEmployeesByName));
} }
@ -121,7 +110,7 @@ public class Java8ComparatorUnitTest {
public void whenReverseOrder_thenSortedByNameDesc() { public void whenReverseOrder_thenSortedByNameDesc() {
Comparator<Employee> employeeNameComparator = Comparator.<Employee> reverseOrder(); Comparator<Employee> employeeNameComparator = Comparator.<Employee> reverseOrder();
Arrays.sort(employees, employeeNameComparator); Arrays.sort(employees, employeeNameComparator);
// System.out.println(Arrays.toString(employees)); // System.out.println(Arrays.toString(employees));
assertTrue(Arrays.equals(employees, sortedEmployeesByNameDesc)); assertTrue(Arrays.equals(employees, sortedEmployeesByNameDesc));
} }
@ -130,7 +119,7 @@ public class Java8ComparatorUnitTest {
Comparator<Employee> employeeNameComparator = Comparator.comparing(Employee::getName); Comparator<Employee> employeeNameComparator = Comparator.comparing(Employee::getName);
Comparator<Employee> employeeNameComparator_nullFirst = Comparator.nullsFirst(employeeNameComparator); Comparator<Employee> employeeNameComparator_nullFirst = Comparator.nullsFirst(employeeNameComparator);
Arrays.sort(employeesArrayWithNulls, employeeNameComparator_nullFirst); Arrays.sort(employeesArrayWithNulls, employeeNameComparator_nullFirst);
// System.out.println(Arrays.toString(employeesArrayWithNulls)); // System.out.println(Arrays.toString(employeesArrayWithNulls));
assertTrue(Arrays.equals(employeesArrayWithNulls, sortedEmployeesArray_WithNullsFirst)); assertTrue(Arrays.equals(employeesArrayWithNulls, sortedEmployeesArray_WithNullsFirst));
} }
@ -139,27 +128,28 @@ public class Java8ComparatorUnitTest {
Comparator<Employee> employeeNameComparator = Comparator.comparing(Employee::getName); Comparator<Employee> employeeNameComparator = Comparator.comparing(Employee::getName);
Comparator<Employee> employeeNameComparator_nullLast = Comparator.nullsLast(employeeNameComparator); Comparator<Employee> employeeNameComparator_nullLast = Comparator.nullsLast(employeeNameComparator);
Arrays.sort(employeesArrayWithNulls, employeeNameComparator_nullLast); Arrays.sort(employeesArrayWithNulls, employeeNameComparator_nullLast);
// System.out.println(Arrays.toString(employeesArrayWithNulls)); // System.out.println(Arrays.toString(employeesArrayWithNulls));
assertTrue(Arrays.equals(employeesArrayWithNulls, sortedEmployeesArray_WithNullsLast)); assertTrue(Arrays.equals(employeesArrayWithNulls, sortedEmployeesArray_WithNullsLast));
} }
@Test @Test
public void whenThenComparing_thenSortedByAgeName() { public void whenThenComparing_thenSortedByAgeName() {
Comparator<Employee> employee_Age_Name_Comparator = Comparator.comparing(Employee::getAge).thenComparing(Employee::getName); Comparator<Employee> employee_Age_Name_Comparator = Comparator.comparing(Employee::getAge)
.thenComparing(Employee::getName);
Arrays.sort(someMoreEmployees, employee_Age_Name_Comparator); Arrays.sort(someMoreEmployees, employee_Age_Name_Comparator);
// System.out.println(Arrays.toString(someMoreEmployees)); // System.out.println(Arrays.toString(someMoreEmployees));
assertTrue(Arrays.equals(someMoreEmployees, sortedEmployeesByAgeName)); assertTrue(Arrays.equals(someMoreEmployees, sortedEmployeesByAgeName));
} }
@Test @Test
public void whenThenComparing_thenSortedByNameAge() { public void whenThenComparing_thenSortedByNameAge() {
Comparator<Employee> employee_Name_Age_Comparator = Comparator.comparing(Employee::getName).thenComparingInt(Employee::getAge); Comparator<Employee> employee_Name_Age_Comparator = Comparator.comparing(Employee::getName)
.thenComparingInt(Employee::getAge);
Arrays.sort(someMoreEmployees, employee_Name_Age_Comparator); Arrays.sort(someMoreEmployees, employee_Name_Age_Comparator);
// System.out.println(Arrays.toString(someMoreEmployees)); // System.out.println(Arrays.toString(someMoreEmployees));
assertTrue(Arrays.equals(someMoreEmployees, sortedEmployeesByNameAge)); assertTrue(Arrays.equals(someMoreEmployees, sortedEmployeesByNameAge));
} }
} }

View File

@ -17,7 +17,6 @@ public class OptionalUnitTest {
private static final Logger LOG = LoggerFactory.getLogger(OptionalUnitTest.class); private static final Logger LOG = LoggerFactory.getLogger(OptionalUnitTest.class);
// creating Optional // creating Optional
@Test @Test
public void whenCreatesEmptyOptional_thenCorrect() { public void whenCreatesEmptyOptional_thenCorrect() {
@ -94,9 +93,11 @@ public class OptionalUnitTest {
public void whenOptionalFilterWorks_thenCorrect() { public void whenOptionalFilterWorks_thenCorrect() {
Integer year = 2016; Integer year = 2016;
Optional<Integer> yearOptional = Optional.of(year); Optional<Integer> yearOptional = Optional.of(year);
boolean is2016 = yearOptional.filter(y -> y == 2016).isPresent(); boolean is2016 = yearOptional.filter(y -> y == 2016)
.isPresent();
assertTrue(is2016); assertTrue(is2016);
boolean is2017 = yearOptional.filter(y -> y == 2017).isPresent(); boolean is2017 = yearOptional.filter(y -> y == 2017)
.isPresent();
assertFalse(is2017); assertFalse(is2017);
} }
@ -128,7 +129,11 @@ public class OptionalUnitTest {
} }
public boolean priceIsInRange2(Modem modem2) { 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() // Transforming Value With map()
@ -137,7 +142,8 @@ public class OptionalUnitTest {
List<String> companyNames = Arrays.asList("paypal", "oracle", "", "microsoft", "", "apple"); List<String> companyNames = Arrays.asList("paypal", "oracle", "", "microsoft", "", "apple");
Optional<List<String>> listOptional = Optional.of(companyNames); Optional<List<String>> listOptional = Optional.of(companyNames);
int size = listOptional.map(List::size).orElse(0); int size = listOptional.map(List::size)
.orElse(0);
assertEquals(6, size); assertEquals(6, size);
} }
@ -146,7 +152,8 @@ public class OptionalUnitTest {
String name = "baeldung"; String name = "baeldung";
Optional<String> nameOptional = Optional.of(name); Optional<String> nameOptional = Optional.of(name);
int len = nameOptional.map(String::length).orElse(0); int len = nameOptional.map(String::length)
.orElse(0);
assertEquals(8, len); assertEquals(8, len);
} }
@ -154,10 +161,13 @@ public class OptionalUnitTest {
public void givenOptional_whenMapWorksWithFilter_thenCorrect() { public void givenOptional_whenMapWorksWithFilter_thenCorrect() {
String password = " password "; String password = " password ";
Optional<String> passOpt = Optional.of(password); Optional<String> passOpt = Optional.of(password);
boolean correctPassword = passOpt.filter(pass -> pass.equals("password")).isPresent(); boolean correctPassword = passOpt.filter(pass -> pass.equals("password"))
.isPresent();
assertFalse(correctPassword); 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); assertTrue(correctPassword);
} }
@ -172,7 +182,8 @@ public class OptionalUnitTest {
String name1 = nameOptional.orElseThrow(IllegalArgumentException::new); String name1 = nameOptional.orElseThrow(IllegalArgumentException::new);
assertEquals("john", name1); assertEquals("john", name1);
String name = personOptional.flatMap(Person::getName).orElseThrow(IllegalArgumentException::new); String name = personOptional.flatMap(Person::getName)
.orElseThrow(IllegalArgumentException::new);
assertEquals("john", name); assertEquals("john", name);
} }
@ -182,7 +193,9 @@ public class OptionalUnitTest {
person.setPassword("password"); person.setPassword("password");
Optional<Person> personOptional = Optional.of(person); Optional<Person> 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); assertEquals("password", password);
} }
@ -190,7 +203,8 @@ public class OptionalUnitTest {
@Test @Test
public void whenOrElseWorks_thenCorrect() { public void whenOrElseWorks_thenCorrect() {
String nullName = null; String nullName = null;
String name = Optional.ofNullable(nullName).orElse("john"); String name = Optional.ofNullable(nullName)
.orElse("john");
assertEquals("john", name); assertEquals("john", name);
} }
@ -198,7 +212,8 @@ public class OptionalUnitTest {
@Test @Test
public void whenOrElseGetWorks_thenCorrect() { public void whenOrElseGetWorks_thenCorrect() {
String nullName = null; String nullName = null;
String name = Optional.ofNullable(nullName).orElseGet(() -> "john"); String name = Optional.ofNullable(nullName)
.orElseGet(() -> "john");
assertEquals("john", name); assertEquals("john", name);
} }
@ -207,11 +222,13 @@ public class OptionalUnitTest {
public void whenOrElseGetAndOrElseOverlap_thenCorrect() { public void whenOrElseGetAndOrElseOverlap_thenCorrect() {
String text = null; String text = null;
LOG.debug("Using orElseGet:"); LOG.debug("Using orElseGet:");
String defaultText = Optional.ofNullable(text).orElseGet(this::getMyDefault); String defaultText = Optional.ofNullable(text)
.orElseGet(this::getMyDefault);
assertEquals("Default Value", defaultText); assertEquals("Default Value", defaultText);
LOG.debug("Using orElse:"); LOG.debug("Using orElse:");
defaultText = Optional.ofNullable(text).orElse(getMyDefault()); defaultText = Optional.ofNullable(text)
.orElse(getMyDefault());
assertEquals("Default Value", defaultText); assertEquals("Default Value", defaultText);
} }
@ -219,11 +236,13 @@ public class OptionalUnitTest {
public void whenOrElseGetAndOrElseDiffer_thenCorrect() { public void whenOrElseGetAndOrElseDiffer_thenCorrect() {
String text = "Text present"; String text = "Text present";
LOG.debug("Using orElseGet:"); LOG.debug("Using orElseGet:");
String defaultText = Optional.ofNullable(text).orElseGet(this::getMyDefault); String defaultText = Optional.ofNullable(text)
.orElseGet(this::getMyDefault);
assertEquals("Text present", defaultText); assertEquals("Text present", defaultText);
LOG.debug("Using orElse:"); LOG.debug("Using orElse:");
defaultText = Optional.ofNullable(text).orElse(getMyDefault()); defaultText = Optional.ofNullable(text)
.orElse(getMyDefault());
assertEquals("Text present", defaultText); assertEquals("Text present", defaultText);
} }
@ -231,7 +250,8 @@ public class OptionalUnitTest {
@Test(expected = IllegalArgumentException.class) @Test(expected = IllegalArgumentException.class)
public void whenOrElseThrowWorks_thenCorrect() { public void whenOrElseThrowWorks_thenCorrect() {
String nullName = null; String nullName = null;
String name = Optional.ofNullable(nullName).orElseThrow(IllegalArgumentException::new); String name = Optional.ofNullable(nullName)
.orElseThrow(IllegalArgumentException::new);
} }
public String getMyDefault() { public String getMyDefault() {

View File

@ -43,6 +43,8 @@ public class FlattenNestedListUnitTest {
} }
private <T> List<T> flattenListOfListsStream(List<List<T>> list) { private <T> List<T> flattenListOfListsStream(List<List<T>> list) {
return list.stream().flatMap(Collection::stream).collect(Collectors.toList()); return list.stream()
.flatMap(Collection::stream)
.collect(Collectors.toList());
} }
} }

View File

@ -15,56 +15,56 @@ public class RoundTest {
private double expected = 2.03d; private double expected = 2.03d;
@Test @Test
public void givenDecimalNumber_whenRoundToNDecimalPlaces_thenGetExpectedResult() { public void givenDecimalNumber_whenRoundToNDecimalPlaces_thenGetExpectedResult() {
Assert.assertEquals(expected, Round.round(value, places), delta); Assert.assertEquals(expected, Round.round(value, places), delta);
Assert.assertEquals(expected, Round.roundNotPrecise(value, places), delta); Assert.assertEquals(expected, Round.roundNotPrecise(value, places), delta);
Assert.assertEquals(expected, Round.roundAvoid(value, places), delta); Assert.assertEquals(expected, Round.roundAvoid(value, places), delta);
Assert.assertEquals(expected, Precision.round(value, places), delta); Assert.assertEquals(expected, Precision.round(value, places), delta);
Assert.assertEquals(expected, DoubleRounder.round(value, places), delta); Assert.assertEquals(expected, DoubleRounder.round(value, places), delta);
places = 3; places = 3;
expected = 2.035d; expected = 2.035d;
Assert.assertEquals(expected, Round.round(value, places), delta); Assert.assertEquals(expected, Round.round(value, places), delta);
Assert.assertEquals(expected, Round.roundNotPrecise(value, places), delta); Assert.assertEquals(expected, Round.roundNotPrecise(value, places), delta);
Assert.assertEquals(expected, Round.roundAvoid(value, places), delta); Assert.assertEquals(expected, Round.roundAvoid(value, places), delta);
Assert.assertEquals(expected, Precision.round(value, places), delta); Assert.assertEquals(expected, Precision.round(value, places), delta);
Assert.assertEquals(expected, DoubleRounder.round(value, places), delta); Assert.assertEquals(expected, DoubleRounder.round(value, places), delta);
value = 1000.0d; value = 1000.0d;
places = 17; places = 17;
expected = 1000.0d; expected = 1000.0d;
Assert.assertEquals(expected, Round.round(value, places), delta); Assert.assertEquals(expected, Round.round(value, places), delta);
Assert.assertEquals(expected, Round.roundNotPrecise(value, places), delta); Assert.assertEquals(expected, Round.roundNotPrecise(value, places), delta);
Assert.assertNotEquals(expected, Round.roundAvoid(value, places), delta); // Returns: 92.23372036854776 ! Assert.assertNotEquals(expected, Round.roundAvoid(value, places), delta); // Returns: 92.23372036854776 !
Assert.assertEquals(expected, Precision.round(value, places), delta); Assert.assertEquals(expected, Precision.round(value, places), delta);
Assert.assertEquals(expected, DoubleRounder.round(value, places), delta); Assert.assertEquals(expected, DoubleRounder.round(value, places), delta);
value = 256.025d; value = 256.025d;
places = 2; places = 2;
expected = 256.03d; expected = 256.03d;
Assert.assertEquals(expected, Round.round(value, places), delta); Assert.assertEquals(expected, Round.round(value, places), delta);
Assert.assertNotEquals(expected, Round.roundNotPrecise(value, places), delta); // Returns: 256.02 ! Assert.assertNotEquals(expected, Round.roundNotPrecise(value, places), delta); // Returns: 256.02 !
Assert.assertNotEquals(expected, Round.roundAvoid(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.assertEquals(expected, Precision.round(value, places), delta);
Assert.assertNotEquals(expected, DoubleRounder.round(value, places), delta); // Returns: 256.02 ! Assert.assertNotEquals(expected, DoubleRounder.round(value, places), delta); // Returns: 256.02 !
value = 260.775d; value = 260.775d;
places = 2; places = 2;
expected = 260.78d; expected = 260.78d;
Assert.assertEquals(expected, Round.round(value, places), delta); Assert.assertEquals(expected, Round.round(value, places), delta);
Assert.assertNotEquals(expected, Round.roundNotPrecise(value, places), delta); // Returns: 260.77 ! Assert.assertNotEquals(expected, Round.roundNotPrecise(value, places), delta); // Returns: 260.77 !
Assert.assertNotEquals(expected, Round.roundAvoid(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.assertEquals(expected, Precision.round(value, places), delta);
Assert.assertNotEquals(expected, DoubleRounder.round(value, places), delta); // Returns: 260.77 ! Assert.assertNotEquals(expected, DoubleRounder.round(value, places), delta); // Returns: 260.77 !
value = 90080070060.1d; value = 90080070060.1d;
places = 9; places = 9;
expected = 90080070060.1d; expected = 90080070060.1d;
Assert.assertEquals(expected, Round.round(value, places), delta); Assert.assertEquals(expected, Round.round(value, places), delta);
Assert.assertEquals(expected, Round.roundNotPrecise(value, places), delta); Assert.assertEquals(expected, Round.roundNotPrecise(value, places), delta);
Assert.assertNotEquals(expected, Round.roundAvoid(value, places), delta); // Returns: 9.223372036854776E9 ! Assert.assertNotEquals(expected, Round.roundAvoid(value, places), delta); // Returns: 9.223372036854776E9 !

View File

@ -14,7 +14,8 @@ public class EchoIntegrationTest {
@BeforeClass @BeforeClass
public static void start() throws InterruptedException { public static void start() throws InterruptedException {
Executors.newSingleThreadExecutor().submit(() -> new EchoServer().start(PORT)); Executors.newSingleThreadExecutor()
.submit(() -> new EchoServer().start(PORT));
Thread.sleep(500); Thread.sleep(500);
} }

View File

@ -17,7 +17,8 @@ public class GreetServerIntegrationTest {
@BeforeClass @BeforeClass
public static void start() throws InterruptedException { public static void start() throws InterruptedException {
Executors.newSingleThreadExecutor().submit(() -> new GreetServer().start(PORT)); Executors.newSingleThreadExecutor()
.submit(() -> new GreetServer().start(PORT));
Thread.sleep(500); Thread.sleep(500);
} }

View File

@ -21,7 +21,7 @@ public class CharSequenceVsStringUnitTest {
CharSequence charSequence1 = "baeldung_1"; CharSequence charSequence1 = "baeldung_1";
CharSequence charSequence2 = "baeldung_2"; CharSequence charSequence2 = "baeldung_2";
assertTrue(charSequence1.toString().compareTo(charSequence2.toString()) > 0); assertTrue(charSequence1.toString().compareTo(charSequence2.toString()) < 0);
} }
@Test @Test
@ -31,7 +31,7 @@ public class CharSequenceVsStringUnitTest {
test += "b"; test += "b";
int secondAddressOfTest = System.identityHashCode(test); int secondAddressOfTest = System.identityHashCode(test);
assertEquals(firstAddressOfTest, secondAddressOfTest); assertNotEquals(firstAddressOfTest, secondAddressOfTest);
} }
@Test @Test

View File

@ -96,9 +96,12 @@ public class JavaIoUnitTest {
// utils // utils
private final void logMemory() { private final void logMemory() {
logger.info("Max Memory: {} Mb", Runtime.getRuntime().maxMemory() / 1048576); logger.info("Max Memory: {} Mb", Runtime.getRuntime()
logger.info("Total Memory: {} Mb", Runtime.getRuntime().totalMemory() / 1048576); .maxMemory() / 1048576);
logger.info("Free Memory: {} Mb", Runtime.getRuntime().freeMemory() / 1048576); logger.info("Total Memory: {} Mb", Runtime.getRuntime()
.totalMemory() / 1048576);
logger.info("Free Memory: {} Mb", Runtime.getRuntime()
.freeMemory() / 1048576);
} }
} }

View File

@ -13,7 +13,6 @@ public class JavaRandomUnitTest {
private static final Logger LOG = LoggerFactory.getLogger(JavaRandomUnitTest.class); private static final Logger LOG = LoggerFactory.getLogger(JavaRandomUnitTest.class);
// tests - random long // tests - random long
@Test @Test
@ -25,7 +24,8 @@ public class JavaRandomUnitTest {
@Test @Test
public void givenUsingApacheCommons_whenGeneratingRandomLongUnbounded_thenCorrect() { public void givenUsingApacheCommons_whenGeneratingRandomLongUnbounded_thenCorrect() {
final long generatedLong = new RandomDataGenerator().getRandomGenerator().nextLong(); final long generatedLong = new RandomDataGenerator().getRandomGenerator()
.nextLong();
LOG.debug("{}", generatedLong); LOG.debug("{}", generatedLong);
} }
@ -68,7 +68,8 @@ public class JavaRandomUnitTest {
@Test @Test
public void givenUsingApache_whenGeneratingRandomIntegerUnbounded_thenCorrect() { public void givenUsingApache_whenGeneratingRandomIntegerUnbounded_thenCorrect() {
final Integer generatedInteger = new RandomDataGenerator().getRandomGenerator().nextInt(); final Integer generatedInteger = new RandomDataGenerator().getRandomGenerator()
.nextInt();
LOG.debug("{}", generatedInteger); LOG.debug("{}", generatedInteger);
} }
@ -93,7 +94,8 @@ public class JavaRandomUnitTest {
@Test @Test
public void givenUsingApache_whenGeneratingRandomFloatUnbounded_thenCorrect() { public void givenUsingApache_whenGeneratingRandomFloatUnbounded_thenCorrect() {
final float generatedFloat = new RandomDataGenerator().getRandomGenerator().nextFloat(); final float generatedFloat = new RandomDataGenerator().getRandomGenerator()
.nextFloat();
LOG.debug("{}", generatedFloat); LOG.debug("{}", generatedFloat);
} }
@ -111,7 +113,8 @@ public class JavaRandomUnitTest {
public void givenUsingApache_whenGeneratingRandomFloatBounded_thenCorrect() { public void givenUsingApache_whenGeneratingRandomFloatBounded_thenCorrect() {
final float leftLimit = 1F; final float leftLimit = 1F;
final float rightLimit = 10F; 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); final float generatedFloat = leftLimit + randomFloat * (rightLimit - leftLimit);
LOG.debug("{}", generatedFloat); LOG.debug("{}", generatedFloat);
@ -128,7 +131,8 @@ public class JavaRandomUnitTest {
@Test @Test
public void givenUsingApache_whenGeneratingRandomDoubleUnbounded_thenCorrect() { public void givenUsingApache_whenGeneratingRandomDoubleUnbounded_thenCorrect() {
final double generatedDouble = new RandomDataGenerator().getRandomGenerator().nextDouble(); final double generatedDouble = new RandomDataGenerator().getRandomGenerator()
.nextDouble();
LOG.debug("{}", generatedDouble); LOG.debug("{}", generatedDouble);
} }

View File

@ -15,7 +15,6 @@ public class JavaTimerLongRunningUnitTest {
private static final Logger LOG = LoggerFactory.getLogger(JavaTimerLongRunningUnitTest.class); private static final Logger LOG = LoggerFactory.getLogger(JavaTimerLongRunningUnitTest.class);
// tests // tests
@Test @Test
@ -23,7 +22,8 @@ public class JavaTimerLongRunningUnitTest {
final TimerTask timerTask = new TimerTask() { final TimerTask timerTask = new TimerTask() {
@Override @Override
public void run() { 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"); final Timer timer = new Timer("Timer");

View File

@ -38,7 +38,8 @@ public class Employee implements Comparable {
@Override @Override
public boolean equals(Object obj) { public boolean equals(Object obj) {
return ((Employee) obj).getName().equals(getName()); return ((Employee) obj).getName()
.equals(getName());
} }
@Override @Override
@ -49,7 +50,13 @@ public class Employee implements Comparable {
@Override @Override
public String toString() { 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();
} }
} }

View File

@ -113,7 +113,8 @@ public class JavaSortingUnitTest {
sortedMap.put(entry.getKey(), entry.getValue()); sortedMap.put(entry.getKey(), entry.getValue());
} }
assertTrue(Arrays.equals(sortedMap.keySet().toArray(), sortedKeys)); assertTrue(Arrays.equals(sortedMap.keySet()
.toArray(), sortedKeys));
} }
@Test @Test
@ -127,7 +128,8 @@ public class JavaSortingUnitTest {
sortedMap.put(entry.getKey(), entry.getValue()); sortedMap.put(entry.getKey(), entry.getValue());
} }
assertTrue(Arrays.equals(sortedMap.values().toArray(), sortedValues)); assertTrue(Arrays.equals(sortedMap.values()
.toArray(), sortedValues));
} }
@Test @Test

View File

@ -14,6 +14,12 @@ public class BookControllerFeignClientBuilder {
private BookClient bookClient = createClient(BookClient.class, "http://localhost:8081/api/books"); private BookClient bookClient = createClient(BookClient.class, "http://localhost:8081/api/books");
private static <T> T createClient(Class<T> type, String uri) { private static <T> T createClient(Class<T> 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);
} }
} }

View File

@ -34,25 +34,31 @@ public class BookClientLiveTest {
@Test @Test
public void givenBookClient_shouldRunSuccessfully() throws Exception { public void givenBookClient_shouldRunSuccessfully() throws Exception {
List<Book> books = bookClient.findAll().stream().map(BookResource::getBook).collect(Collectors.toList()); List<Book> books = bookClient.findAll()
.stream()
.map(BookResource::getBook)
.collect(Collectors.toList());
assertTrue(books.size() > 2); assertTrue(books.size() > 2);
log.info("{}", books); log.info("{}", books);
} }
@Test @Test
public void givenBookClient_shouldFindOneBook() throws Exception { public void givenBookClient_shouldFindOneBook() throws Exception {
Book book = bookClient.findByIsbn("0151072558").getBook(); Book book = bookClient.findByIsbn("0151072558")
.getBook();
assertThat(book.getAuthor(), containsString("Orwell")); assertThat(book.getAuthor(), containsString("Orwell"));
log.info("{}", book); log.info("{}", book);
} }
@Test @Test
public void givenBookClient_shouldPostBook() throws Exception { 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); Book book = new Book(isbn, "Me", "It's me!", null, null);
bookClient.create(book); bookClient.create(book);
book = bookClient.findByIsbn(isbn).getBook(); book = bookClient.findByIsbn(isbn)
.getBook();
assertThat(book.getAuthor(), is("Me")); assertThat(book.getAuthor(), is("Me"));
log.info("{}", book); log.info("{}", book);
} }

View File

@ -9,7 +9,8 @@ public class Author extends Person {
List<Item> items = new ArrayList<>(); List<Item> items = new ArrayList<>();
public Author(){} public Author() {
}
public Author(String firstName, String lastName) { public Author(String firstName, String lastName) {
super(firstName, lastName); super(firstName, lastName);

View File

@ -11,7 +11,7 @@ public class Person {
private String firstName; private String firstName;
private String lastName; private String lastName;
public Person(){ public Person() {
} }

View File

@ -1,6 +1,5 @@
package com.baeldung.jackson.deserialization.jsoncreator; package com.baeldung.jackson.deserialization.jsoncreator;
import com.baeldung.jackson.domain.Person; import com.baeldung.jackson.domain.Person;
import com.baeldung.jackson.domain.Item; import com.baeldung.jackson.domain.Item;
import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonCreator;
@ -14,9 +13,7 @@ public class Author extends Person {
List<Item> items = new ArrayList<>(); List<Item> items = new ArrayList<>();
@JsonCreator @JsonCreator
public Author( public Author(@JsonProperty("christianName") String firstName, @JsonProperty("surname") String lastName) {
@JsonProperty("christianName") String firstName,
@JsonProperty("surname") String lastName) {
super(firstName, lastName); super(firstName, lastName);
} }

View File

@ -13,7 +13,8 @@ public class Book extends Item {
private Date published; private Date published;
private BigDecimal pages; private BigDecimal pages;
public Book() {} public Book() {
}
public Book(String title, Author author) { public Book(String title, Author author) {
super(title, author); super(title, author);

View File

@ -11,8 +11,7 @@ import java.util.Date;
public class CustomDateDeserializer extends StdDeserializer<Date> { public class CustomDateDeserializer extends StdDeserializer<Date> {
private static SimpleDateFormat formatter = private static SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
public CustomDateDeserializer() { public CustomDateDeserializer() {
this(null); this(null);
@ -23,8 +22,7 @@ public class CustomDateDeserializer extends StdDeserializer<Date> {
} }
@Override @Override
public Date deserialize(JsonParser jsonparser, DeserializationContext context) public Date deserialize(JsonParser jsonparser, DeserializationContext context) throws IOException {
throws IOException {
String date = jsonparser.getText(); String date = jsonparser.getText();
try { try {
return formatter.parse(date); return formatter.parse(date);

View File

@ -19,7 +19,8 @@ public class Item {
private List<Person> authors = new ArrayList<>(); private List<Person> authors = new ArrayList<>();
private float price; private float price;
public Item(){} public Item() {
}
public Item(String title, Author author) { public Item(String title, Author author) {
this.id = UUID.randomUUID(); this.id = UUID.randomUUID();

View File

@ -18,7 +18,8 @@ public class Author extends Person {
private List<Item> items = new ArrayList<>(); private List<Item> items = new ArrayList<>();
public Author(){} public Author() {
}
public Author(String firstName, String lastName) { public Author(String firstName, String lastName) {
super(firstName, lastName); super(firstName, lastName);

View File

@ -15,7 +15,7 @@ public class Book extends Item {
private Date published; private Date published;
private BigDecimal pages; private BigDecimal pages;
public Book(){ public Book() {
} }
public Book(String title, Author author) { public Book(String title, Author author) {

View File

@ -10,7 +10,9 @@ import java.util.List;
*/ */
public class Course extends Item { public class Course extends Item {
public enum Medium {CLASSROOM, ONLINE} public enum Medium {
CLASSROOM, ONLINE
}
public enum Level { public enum Level {
BEGINNER("Beginner", 1), INTERMEDIATE("Intermediate", 2), ADVANCED("Advanced", 3); BEGINNER("Beginner", 1), INTERMEDIATE("Intermediate", 2), ADVANCED("Advanced", 3);

View File

@ -17,7 +17,8 @@ public class Item {
private List<Person> authors = new ArrayList<>(); private List<Person> authors = new ArrayList<>();
private float price; private float price;
public Item(){} public Item() {
}
public Item(String title, Author author) { public Item(String title, Author author) {
this.id = UUID.randomUUID(); this.id = UUID.randomUUID();

View File

@ -14,7 +14,8 @@ public class Person {
private String firstName; private String firstName;
private String lastName; private String lastName;
public Person(){} public Person() {
}
public Person(String firstName, String lastName) { public Person(String firstName, String lastName) {
this.id = UUID.randomUUID(); this.id = UUID.randomUUID();

View File

@ -9,16 +9,16 @@ import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
public class ClassWithAMap { public class ClassWithAMap {
@JsonProperty("map") @JsonProperty("map")
@JsonDeserialize(keyUsing = MyPairDeserializer.class) @JsonDeserialize(keyUsing = MyPairDeserializer.class)
private final Map<MyPair, String> map; private final Map<MyPair, String> map;
@JsonCreator @JsonCreator
public ClassWithAMap(Map<MyPair, String> map) { public ClassWithAMap(Map<MyPair, String> map) {
this.map = map; this.map = map;
} }
public Map<MyPair, String> getMap() { public Map<MyPair, String> getMap() {
return map; return map;
} }
} }

View File

@ -4,77 +4,77 @@ import com.fasterxml.jackson.annotation.JsonValue;
public class MyPair { public class MyPair {
private String first; private String first;
private String second; private String second;
public MyPair(String first, String second) { public MyPair(String first, String second) {
this.first = first; this.first = first;
this.second = second; this.second = second;
} }
public MyPair(String both) { public MyPair(String both) {
String[] pairs = both.split("and"); String[] pairs = both.split("and");
this.first = pairs[0].trim(); this.first = pairs[0].trim();
this.second = pairs[1].trim(); this.second = pairs[1].trim();
} }
@Override @Override
@JsonValue @JsonValue
public String toString() { public String toString() {
return first + " and " + second; return first + " and " + second;
} }
@Override @Override
public int hashCode() { public int hashCode() {
final int prime = 31; final int prime = 31;
int result = 1; int result = 1;
result = prime * result + ((first == null) ? 0 : first.hashCode()); result = prime * result + ((first == null) ? 0 : first.hashCode());
result = prime * result + ((second == null) ? 0 : second.hashCode()); result = prime * result + ((second == null) ? 0 : second.hashCode());
return result; return result;
} }
@Override @Override
public boolean equals(Object obj) { public boolean equals(Object obj) {
if (this == obj) { if (this == obj) {
return true; return true;
} }
if (obj == null) { if (obj == null) {
return false; return false;
} }
if (!(obj instanceof MyPair)) { if (!(obj instanceof MyPair)) {
return false; return false;
} }
MyPair other = (MyPair) obj; MyPair other = (MyPair) obj;
if (first == null) { if (first == null) {
if (other.first != null) { if (other.first != null) {
return false; return false;
} }
} else if (!first.equals(other.first)) { } else if (!first.equals(other.first)) {
return false; return false;
} }
if (second == null) { if (second == null) {
if (other.second != null) { if (other.second != null) {
return false; return false;
} }
} else if (!second.equals(other.second)) { } else if (!second.equals(other.second)) {
return false; return false;
} }
return true; return true;
} }
public String getFirst() { public String getFirst() {
return first; return first;
} }
public void setFirst(String first) { public void setFirst(String first) {
this.first = first; this.first = first;
} }
public String getSecond() { public String getSecond() {
return second; return second;
} }
public void setSecond(String second) { public void setSecond(String second) {
this.second = second; this.second = second;
} }
} }

View File

@ -13,28 +13,25 @@ public class User extends Person {
private String firstName; private String firstName;
private String lastName; private String lastName;
@JsonFormat(shape = JsonFormat.Shape.STRING, @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd@HH:mm:ss.SSSZ")
pattern = "yyyy-MM-dd@HH:mm:ss.SSSZ")
private Date createdDate; private Date createdDate;
public User(String firstName,String lastName) { public User(String firstName, String lastName) {
super(firstName, lastName); super(firstName, lastName);
this.createdDate = new Date(); this.createdDate = new Date();
} }
public Date getCreatedDate() { public Date getCreatedDate() {
return createdDate; return createdDate;
} }
@JsonFormat(shape = JsonFormat.Shape.STRING, @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd@HH:mm:ss.SSSZ", locale = "en_GB")
pattern = "yyyy-MM-dd@HH:mm:ss.SSSZ",
locale = "en_GB")
public Date getCurrentDate() { public Date getCurrentDate() {
return new Date(); return new Date();
} }
@JsonFormat(shape = JsonFormat.Shape.NUMBER) @JsonFormat(shape = JsonFormat.Shape.NUMBER)
public Date getDateNum() { public Date getDateNum() {
return new Date(); return new Date();
} }
} }

View File

@ -17,7 +17,8 @@ public class Person {
private String firstName; private String firstName;
private String lastName; private String lastName;
public Person(){} public Person() {
}
public Person(String firstName, String lastName) { public Person(String firstName, String lastName) {
this.id = UUID.randomUUID(); this.id = UUID.randomUUID();

View File

@ -12,10 +12,12 @@ import java.util.List;
* @author Alex Theedom www.readlearncode.com * @author Alex Theedom www.readlearncode.com
* @version 1.0 * @version 1.0
*/ */
@JsonIgnoreProperties({"medium"}) @JsonIgnoreProperties({ "medium" })
public class Course extends Item { public class Course extends Item {
public enum Medium {CLASSROOM, ONLINE} public enum Medium {
CLASSROOM, ONLINE
}
public enum Level { public enum Level {
BEGINNER("Beginner", 1), INTERMEDIATE("Intermediate", 2), ADVANCED("Advanced", 3); BEGINNER("Beginner", 1), INTERMEDIATE("Intermediate", 2), ADVANCED("Advanced", 3);

View File

@ -12,10 +12,7 @@ public class ItemIdAddedToUser extends Event {
private final Long quantity; private final Long quantity;
@JsonCreator @JsonCreator
public ItemIdAddedToUser(@JsonProperty("id") String id, public ItemIdAddedToUser(@JsonProperty("id") String id, @JsonProperty("timestamp") Long timestamp, @JsonProperty("itemId") String itemId, @JsonProperty("quantity") Long quantity) {
@JsonProperty("timestamp") Long timestamp,
@JsonProperty("itemId") String itemId,
@JsonProperty("quantity") Long quantity) {
super(id, timestamp); super(id, timestamp);
this.itemId = itemId; this.itemId = itemId;
this.quantity = quantity; this.quantity = quantity;

View File

@ -10,10 +10,7 @@ public class ItemIdRemovedFromUser extends Event {
private final Long quantity; private final Long quantity;
@JsonCreator @JsonCreator
public ItemIdRemovedFromUser(@JsonProperty("id") String id, public ItemIdRemovedFromUser(@JsonProperty("id") String id, @JsonProperty("timestamp") Long timestamp, @JsonProperty("itemId") String itemId, @JsonProperty("quantity") Long quantity) {
@JsonProperty("timestamp") Long timestamp,
@JsonProperty("itemId") String itemId,
@JsonProperty("quantity") Long quantity) {
super(id, timestamp); super(id, timestamp);
this.itemId = itemId; this.itemId = itemId;
this.quantity = quantity; this.quantity = quantity;

View File

@ -13,7 +13,9 @@ import java.util.List;
@CustomCourseAnnotation @CustomCourseAnnotation
public class Course extends Item { public class Course extends Item {
public enum Medium {CLASSROOM, ONLINE} public enum Medium {
CLASSROOM, ONLINE
}
public enum Level { public enum Level {
BEGINNER("Beginner", 1), INTERMEDIATE("Intermediate", 2), ADVANCED("Advanced", 3); BEGINNER("Beginner", 1), INTERMEDIATE("Intermediate", 2), ADVANCED("Advanced", 3);

View File

@ -14,7 +14,7 @@ import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)
@JacksonAnnotationsInside @JacksonAnnotationsInside
@JsonInclude(JsonInclude.Include.NON_NULL) @JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({"title", "price", "id", "duration", "authors", "level"}) @JsonPropertyOrder({ "title", "price", "id", "duration", "authors", "level" })
@JsonIgnoreProperties({"prerequisite"}) @JsonIgnoreProperties({ "prerequisite" })
public @interface CustomCourseAnnotation { public @interface CustomCourseAnnotation {
} }

View File

@ -20,7 +20,8 @@ public class Item {
private List<Person> authors = new ArrayList<>(); private List<Person> authors = new ArrayList<>();
private float price; private float price;
public Item(){} public Item() {
}
public Item(String title, Author author) { public Item(String title, Author author) {
this.id = UUID.randomUUID(); this.id = UUID.randomUUID();

View File

@ -16,7 +16,7 @@ import java.util.List;
* @version 1.0 * @version 1.0
*/ */
@JsonInclude(JsonInclude.Include.NON_NULL) @JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({"lastName", "items", "firstName", "id"}) @JsonPropertyOrder({ "lastName", "items", "firstName", "id" })
public class Author extends Person { public class Author extends Person {
@JsonIgnore @JsonIgnore

View File

@ -18,12 +18,8 @@ public class Order {
private Type type; private Type type;
private int internalAudit; private int internalAudit;
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "ordertype")
include = JsonTypeInfo.As.PROPERTY, @JsonSubTypes({ @JsonSubTypes.Type(value = InternalType.class, name = "internal") })
property = "ordertype")
@JsonSubTypes({
@JsonSubTypes.Type(value = InternalType.class, name = "internal")
})
public static class Type { public static class Type {
public long id; public long id;
public String name; public String name;

View File

@ -24,8 +24,11 @@ public class ActorJacksonSerializer extends StdSerializer<ActorJackson> {
jsonGenerator.writeStartObject(); jsonGenerator.writeStartObject();
jsonGenerator.writeStringField("imdbId", actor.getImdbId()); jsonGenerator.writeStringField("imdbId", actor.getImdbId());
jsonGenerator.writeObjectField("dateOfBirth", actor.getDateOfBirth() != null ? sdf.format(actor.getDateOfBirth()) : null); jsonGenerator.writeObjectField("dateOfBirth", actor.getDateOfBirth() != null ? sdf.format(actor.getDateOfBirth()) : null);
jsonGenerator.writeNumberField("N° Film: ", actor.getFilmography() != null ? actor.getFilmography().size() : null); jsonGenerator.writeNumberField("N° Film: ", actor.getFilmography() != null ? actor.getFilmography()
jsonGenerator.writeStringField("filmography", actor.getFilmography().stream().collect(Collectors.joining("-"))); .size() : null);
jsonGenerator.writeStringField("filmography", actor.getFilmography()
.stream()
.collect(Collectors.joining("-")));
jsonGenerator.writeEndObject(); jsonGenerator.writeEndObject();
} }
} }

View File

@ -9,10 +9,9 @@ import com.fasterxml.jackson.databind.KeyDeserializer;
public class MyPairDeserializer extends KeyDeserializer { public class MyPairDeserializer extends KeyDeserializer {
@Override @Override
public MyPair deserializeKey(String key, DeserializationContext ctxt) public MyPair deserializeKey(String key, DeserializationContext ctxt) throws IOException, JsonProcessingException {
throws IOException, JsonProcessingException {
return new MyPair(key); return new MyPair(key);
} }
} }

View File

@ -12,14 +12,12 @@ import com.fasterxml.jackson.databind.SerializerProvider;
public class MyPairSerializer extends JsonSerializer<MyPair> { public class MyPairSerializer extends JsonSerializer<MyPair> {
private final ObjectMapper mapper = new ObjectMapper(); private final ObjectMapper mapper = new ObjectMapper();
@Override @Override
public void serialize(MyPair value, JsonGenerator gen, public void serialize(MyPair value, JsonGenerator gen, SerializerProvider serializers) throws IOException, JsonProcessingException {
SerializerProvider serializers) throws IOException, StringWriter writer = new StringWriter();
JsonProcessingException { mapper.writeValue(writer, value);
StringWriter writer = new StringWriter(); gen.writeFieldName(writer.toString());
mapper.writeValue(writer, value); }
gen.writeFieldName(writer.toString());
}
} }

View File

@ -1,6 +1,5 @@
package com.baeldung.jackson.serialization.jsongetter; package com.baeldung.jackson.serialization.jsongetter;
import com.baeldung.jackson.domain.Item; import com.baeldung.jackson.domain.Item;
import com.baeldung.jackson.domain.Person; import com.baeldung.jackson.domain.Person;
import com.fasterxml.jackson.annotation.JsonGetter; import com.fasterxml.jackson.annotation.JsonGetter;

View File

@ -1,6 +1,5 @@
package com.baeldung.jackson.serialization.jsonpropertyorder; package com.baeldung.jackson.serialization.jsonpropertyorder;
import com.baeldung.jackson.domain.Item; import com.baeldung.jackson.domain.Item;
import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@ -13,7 +12,7 @@ import java.util.List;
* @author Alex Theedom www.readlearncode.com * @author Alex Theedom www.readlearncode.com
* @version 1.0 * @version 1.0
*/ */
@JsonPropertyOrder({"items", "firstName", "lastName", "id"}) @JsonPropertyOrder({ "items", "firstName", "lastName", "id" })
public class Author extends Person { public class Author extends Person {
List<Item> items = new ArrayList<>(); List<Item> items = new ArrayList<>();

View File

@ -19,7 +19,8 @@ public class Book extends Item {
private Date published; private Date published;
private BigDecimal pages; private BigDecimal pages;
public Book(){} public Book() {
}
public Book(String title, Author author) { public Book(String title, Author author) {
super(title, author); super(title, author);

View File

@ -17,8 +17,7 @@ import java.util.Date;
*/ */
public class CustomDateSerializer extends StdSerializer<Date> { public class CustomDateSerializer extends StdSerializer<Date> {
private static SimpleDateFormat formatter = private static SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
public CustomDateSerializer() { public CustomDateSerializer() {
this(null); this(null);
@ -29,8 +28,7 @@ public class CustomDateSerializer extends StdSerializer<Date> {
} }
@Override @Override
public void serialize(Date value, JsonGenerator gen, SerializerProvider arg2) public void serialize(Date value, JsonGenerator gen, SerializerProvider arg2) throws IOException, JsonProcessingException {
throws IOException, JsonProcessingException {
gen.writeString(formatter.format(value)); gen.writeString(formatter.format(value));
} }
} }

View File

@ -19,7 +19,8 @@ public class Item {
private List<Person> authors = new ArrayList<>(); private List<Person> authors = new ArrayList<>();
private float price; private float price;
public Item(){} public Item() {
}
public Item(String title, Author author) { public Item(String title, Author author) {
this.id = UUID.randomUUID(); this.id = UUID.randomUUID();

View File

@ -14,7 +14,9 @@ import java.util.List;
*/ */
public class Course extends Item { public class Course extends Item {
public enum Medium {CLASSROOM, ONLINE} public enum Medium {
CLASSROOM, ONLINE
}
public enum Level { public enum Level {
BEGINNER("Beginner", 1), INTERMEDIATE("Intermediate", 2), ADVANCED("Advanced", 3); BEGINNER("Beginner", 1), INTERMEDIATE("Intermediate", 2), ADVANCED("Advanced", 3);

View File

@ -47,9 +47,10 @@ public class ExtraAnnotationUnitTest {
ObjectMapper mapper = new ObjectMapper(); ObjectMapper mapper = new ObjectMapper();
BeanWithoutAppend bean = new BeanWithoutAppend(2, "Bean Without Append Annotation"); 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); String jsonString = writer.writeValueAsString(bean);
assertThat(jsonString, not(containsString("version"))); assertThat(jsonString, not(containsString("version")));
assertThat(jsonString, not(containsString("1.0"))); assertThat(jsonString, not(containsString("1.0")));
} }
@ -59,9 +60,10 @@ public class ExtraAnnotationUnitTest {
ObjectMapper mapper = new ObjectMapper(); ObjectMapper mapper = new ObjectMapper();
BeanWithAppend bean = new BeanWithAppend(2, "Bean With Append Annotation"); 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); String jsonString = writer.writeValueAsString(bean);
assertThat(jsonString, containsString("version")); assertThat(jsonString, containsString("version"));
assertThat(jsonString, containsString("1.0")); assertThat(jsonString, containsString("1.0"));
} }
@ -71,7 +73,7 @@ public class ExtraAnnotationUnitTest {
ObjectMapper mapper = new ObjectMapper(); ObjectMapper mapper = new ObjectMapper();
NamingBean bean = new NamingBean(3, "Naming Bean"); NamingBean bean = new NamingBean(3, "Naming Bean");
String jsonString = mapper.writeValueAsString(bean); String jsonString = mapper.writeValueAsString(bean);
assertThat(jsonString, containsString("bean_name")); assertThat(jsonString, containsString("bean_name"));
} }

View File

@ -4,7 +4,6 @@ import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.JsonIdentityReference; import com.fasterxml.jackson.annotation.JsonIdentityReference;
import com.fasterxml.jackson.annotation.ObjectIdGenerators; import com.fasterxml.jackson.annotation.ObjectIdGenerators;
public class IdentityReferenceBeans { public class IdentityReferenceBeans {
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id") @JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
public static class BeanWithoutIdentityReference { public static class BeanWithoutIdentityReference {
@ -32,7 +31,7 @@ public class IdentityReferenceBeans {
this.name = name; this.name = name;
} }
} }
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id") @JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
@JsonIdentityReference(alwaysAsId = true) @JsonIdentityReference(alwaysAsId = true)
public static class BeanWithIdentityReference { public static class BeanWithIdentityReference {

View File

@ -20,6 +20,7 @@ public class CustomListSerializer extends StdSerializer<List<ItemWithSerializer>
public CustomListSerializer(final Class<List<ItemWithSerializer>> t) { public CustomListSerializer(final Class<List<ItemWithSerializer>> t) {
super(t); super(t);
} }
@Override @Override
public void serialize(final List<ItemWithSerializer> items, final JsonGenerator generator, final SerializerProvider provider) throws IOException, JsonProcessingException { public void serialize(final List<ItemWithSerializer> items, final JsonGenerator generator, final SerializerProvider provider) throws IOException, JsonProcessingException {
final List<Integer> ids = new ArrayList<Integer>(); final List<Integer> ids = new ArrayList<Integer>();

View File

@ -11,7 +11,6 @@ import com.fasterxml.jackson.databind.ser.std.StdSerializer;
public class CustomLocalDateTimeSerializer extends StdSerializer<LocalDateTime> { public class CustomLocalDateTimeSerializer extends StdSerializer<LocalDateTime> {
private static final long serialVersionUID = -7449444168934819290L; private static final long serialVersionUID = -7449444168934819290L;
private static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"); private static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");

View File

@ -28,9 +28,11 @@ public class ItemDeserializer extends StdDeserializer<Item> {
*/ */
@Override @Override
public Item deserialize(final JsonParser jp, final DeserializationContext ctxt) throws IOException, JsonProcessingException { 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 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(); final int userId = (Integer) ((IntNode) node.get("createdBy")).numberValue();
return new Item(id, itemName, new User(userId, null)); return new Item(id, itemName, new User(userId, null));

View File

@ -28,9 +28,11 @@ public class ItemDeserializerOnClass extends StdDeserializer<ItemWithSerializer>
*/ */
@Override @Override
public ItemWithSerializer deserialize(final JsonParser jp, final DeserializationContext ctxt) throws IOException, JsonProcessingException { 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 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(); final int userId = (Integer) ((IntNode) node.get("owner")).numberValue();
return new ItemWithSerializer(id, itemName, new User(userId, null)); return new ItemWithSerializer(id, itemName, new User(userId, null));

View File

@ -16,54 +16,49 @@ import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonMapDeserializeUnitTest { public class JacksonMapDeserializeUnitTest {
private Map<MyPair, String> map; private Map<MyPair, String> map;
private Map<MyPair, MyPair> cmap; private Map<MyPair, MyPair> cmap;
final ObjectMapper mapper = new ObjectMapper(); final ObjectMapper mapper = new ObjectMapper();
@Test @Test
public void whenSimpleMapDeserialize_thenCorrect() public void whenSimpleMapDeserialize_thenCorrect() throws JsonParseException, JsonMappingException, IOException {
throws JsonParseException, JsonMappingException, IOException {
final String jsonInput = "{\"key\": \"value\"}"; final String jsonInput = "{\"key\": \"value\"}";
TypeReference<HashMap<String, String>> typeRef = new TypeReference<HashMap<String, String>>() { TypeReference<HashMap<String, String>> typeRef = new TypeReference<HashMap<String, String>>() {
}; };
final Map<String, String> map = mapper.readValue(jsonInput, typeRef); final Map<String, String> map = mapper.readValue(jsonInput, typeRef);
Assert.assertEquals("value", map.get("key")); Assert.assertEquals("value", map.get("key"));
} }
@Test @Test
public void whenObjectStringMapDeserialize_thenCorrect() public void whenObjectStringMapDeserialize_thenCorrect() throws JsonParseException, JsonMappingException, IOException {
throws JsonParseException, JsonMappingException, IOException {
final String jsonInput = "{\"Abbott and Costello\":\"Comedy\"}"; final String jsonInput = "{\"Abbott and Costello\":\"Comedy\"}";
TypeReference<HashMap<MyPair, String>> typeRef = new TypeReference<HashMap<MyPair, String>>() { TypeReference<HashMap<MyPair, String>> typeRef = new TypeReference<HashMap<MyPair, String>>() {
}; };
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 classWithMap = mapper.readValue(jsonInput, ClassWithAMap.class);
ClassWithAMap.class);
Assert.assertEquals("Comedy", Assert.assertEquals("Comedy", classWithMap.getMap()
classWithMap.getMap().get(new MyPair("Abbott", "Costello"))); .get(new MyPair("Abbott", "Costello")));
} }
@Test @Test
public void whenObjectObjectMapDeserialize_thenCorrect() public void whenObjectObjectMapDeserialize_thenCorrect() throws JsonParseException, JsonMappingException, IOException {
throws JsonParseException, JsonMappingException, IOException {
final String jsonInput = "{\"Abbott and Costello\" : \"Comedy and 1940s\"}"; final String jsonInput = "{\"Abbott and Costello\" : \"Comedy and 1940s\"}";
TypeReference<HashMap<MyPair, MyPair>> typeRef = new TypeReference<HashMap<MyPair, MyPair>>() { TypeReference<HashMap<MyPair, MyPair>> typeRef = new TypeReference<HashMap<MyPair, MyPair>>() {
}; };
cmap = mapper.readValue(jsonInput, typeRef); cmap = mapper.readValue(jsonInput, typeRef);
Assert.assertEquals(new MyPair("Comedy", "1940s"), Assert.assertEquals(new MyPair("Comedy", "1940s"), cmap.get(new MyPair("Abbott", "Costello")));
cmap.get(new MyPair("Abbott", "Costello"))); }
}
} }

View File

@ -27,7 +27,9 @@ public class JacksonInjectUnitTest {
// act // act
InjectableValues inject = new InjectableValues.Std().addValue(UUID.class, id); 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 // assert
assertThat(author.getId()).isEqualTo(id); assertThat(author.getId()).isEqualTo(id);

View File

@ -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}"; String json = "{\"USA\":10.00,\"UK\":15.00,\"China\":23.00,\"Brazil\":12.00,\"France\":8.00,\"Russia\":18.00}";
// act // act
Inventory inventory = new ObjectMapper().readerFor(Inventory.class).readValue(json); Inventory inventory = new ObjectMapper().readerFor(Inventory.class)
.readValue(json);
// assert // assert
assertThat(from(json).getMap(".").get("USA")).isEqualTo(inventory.getCountryDeliveryCost().get("USA")); assertThat(from(json).getMap(".")
assertThat(from(json).getMap(".").get("UK")).isEqualTo(inventory.getCountryDeliveryCost().get("UK")); .get("USA")).isEqualTo(inventory.getCountryDeliveryCost()
assertThat(from(json).getMap(".").get("China")).isEqualTo(inventory.getCountryDeliveryCost().get("China")); .get("USA"));
assertThat(from(json).getMap(".").get("Brazil")).isEqualTo(inventory.getCountryDeliveryCost().get("Brazil")); assertThat(from(json).getMap(".")
assertThat(from(json).getMap(".").get("France")).isEqualTo(inventory.getCountryDeliveryCost().get("France")); .get("UK")).isEqualTo(inventory.getCountryDeliveryCost()
assertThat(from(json).getMap(".").get("Russia")).isEqualTo(inventory.getCountryDeliveryCost().get("Russia")); .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"));
} }
} }

View File

@ -20,14 +20,11 @@ public class JsonCreatorUnitTest {
public void whenDeserializingUsingJsonCreator_thenCorrect() throws IOException { public void whenDeserializingUsingJsonCreator_thenCorrect() throws IOException {
// arrange // arrange
String authorJson = String authorJson = "{" + " \"christianName\": \"Alex\"," + " \"surname\": \"Theedom\"" + "}";
"{" +
" \"christianName\": \"Alex\"," +
" \"surname\": \"Theedom\"" +
"}";
// act // act
final Author author = new ObjectMapper().readerFor(Author.class).readValue(authorJson); final Author author = new ObjectMapper().readerFor(Author.class)
.readValue(authorJson);
// assert // assert
assertThat(from(authorJson).getString("christianName")).isEqualTo(author.getFirstName()); assertThat(from(authorJson).getString("christianName")).isEqualTo(author.getFirstName());

View File

@ -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}"; 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 // act
Book book = new ObjectMapper().readerFor(Book.class).readValue(bookJson); Book book = new ObjectMapper().readerFor(Book.class)
.readValue(bookJson);
// assert // assert
SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");

View File

@ -23,10 +23,13 @@ public class JsonSetterUnitTest {
String json = "{\"firstName\":\"Alex\",\"lastName\":\"Theedom\",\"publications\":[{\"title\":\"Professional Java EE Design Patterns\"}]}"; String json = "{\"firstName\":\"Alex\",\"lastName\":\"Theedom\",\"publications\":[{\"title\":\"Professional Java EE Design Patterns\"}]}";
// act // act
Author author = new ObjectMapper().readerFor(Author.class).readValue(json); Author author = new ObjectMapper().readerFor(Author.class)
.readValue(json);
// assert // assert
assertThat(from(json).getList("publications").size()).isEqualTo(author.getItems().size()); assertThat(from(json).getList("publications")
.size()).isEqualTo(author.getItems()
.size());
} }
} }

View File

@ -1,6 +1,5 @@
package com.baeldung.jackson.dynamicIgnore; package com.baeldung.jackson.dynamicIgnore;
public class Address implements Hidable { public class Address implements Hidable {
private String city; private String city;
private String country; private String country;

View File

@ -2,7 +2,6 @@ package com.baeldung.jackson.dynamicIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties("hidden") @JsonIgnoreProperties("hidden")
public interface Hidable { public interface Hidable {
boolean isHidden(); boolean isHidden();

View File

@ -1,6 +1,5 @@
package com.baeldung.jackson.dynamicIgnore; package com.baeldung.jackson.dynamicIgnore;
public class Person implements Hidable { public class Person implements Hidable {
private String name; private String name;
private Address address; private Address address;
@ -13,7 +12,6 @@ public class Person implements Hidable {
this.hidden = hidden; this.hidden = hidden;
} }
public String getName() { public String getName() {
return name; return name;
} }
@ -29,6 +27,7 @@ public class Person implements Hidable {
public void setAddress(final Address address) { public void setAddress(final Address address) {
this.address = address; this.address = address;
} }
@Override @Override
public boolean isHidden() { public boolean isHidden() {
return hidden; return hidden;

View File

@ -22,18 +22,16 @@ public class JsonFormatUnitTest {
@Test @Test
public void whenSerializedDateFormat_thenCorrect() throws JsonProcessingException { 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" // Expected to match: "2016-12-19@09:34:42.628+0000"
assertThat(from(result).getString("createdDate")) assertThat(from(result).getString("createdDate")).matches("\\d{4}\\-\\d{2}\\-\\d{2}@\\d{2}:\\d{2}:\\d{2}\\.\\d{3}\\+\\d{4}");
.matches("\\d{4}\\-\\d{2}\\-\\d{2}@\\d{2}:\\d{2}:\\d{2}\\.\\d{3}\\+\\d{4}");
// Expected to be close to current time // Expected to be close to current time
long now = new Date().getTime(); long now = new Date().getTime();
assertThat(from(result).getLong("dateNum")) assertThat(from(result).getLong("dateNum")).isCloseTo(now, withPercentage(10.0));
.isCloseTo(now, withPercentage(10.0));
} }
} }

View File

@ -23,11 +23,11 @@ public class JsonFilterUnitTest {
// arrange // arrange
Author author = new Author("Alex", "Theedom"); Author author = new Author("Alex", "Theedom");
FilterProvider filters = new SimpleFilterProvider() FilterProvider filters = new SimpleFilterProvider().addFilter("authorFilter", SimpleBeanPropertyFilter.filterOutAllExcept("lastName"));
.addFilter("authorFilter", SimpleBeanPropertyFilter.filterOutAllExcept("lastName"));
// act // act
String result = new ObjectMapper().writer(filters).writeValueAsString(author); String result = new ObjectMapper().writer(filters)
.writeValueAsString(author);
// assert // assert
assertThat(from(result).getList("items")).isNull(); assertThat(from(result).getList("items")).isNull();

View File

@ -17,9 +17,7 @@ public class Book extends Item {
private String ISBN; private String ISBN;
@JsonFormat( @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy HH:mm:ss")
shape = JsonFormat.Shape.STRING,
pattern = "dd-MM-yyyy HH:mm:ss")
private Date published; private Date published;
private BigDecimal pages; private BigDecimal pages;

View File

@ -31,10 +31,7 @@ public class JsonFormatUnitTest {
String toParse = "20-12-2014 14:30:00"; String toParse = "20-12-2014 14:30:00";
Date date = df.parse(toParse); Date date = df.parse(toParse);
Book book = new Book( Book book = new Book("Design Patterns: Elements of Reusable Object-oriented Software", new Author("The", "GoF"));
"Design Patterns: Elements of Reusable Object-oriented Software",
new Author("The", "GoF")
);
book.setPublished(date); book.setPublished(date);
// act // act

View File

@ -12,9 +12,7 @@ import java.util.List;
* @author Alex Theedom www.readlearncode.com * @author Alex Theedom www.readlearncode.com
* @version 1.0 * @version 1.0
*/ */
@JsonIdentityInfo( @JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
generator = ObjectIdGenerators.PropertyGenerator.class,
property = "id")
public class Author extends Person { public class Author extends Person {
private List<Item> items = new ArrayList<>(); private List<Item> items = new ArrayList<>();

View File

@ -1,6 +1,5 @@
package com.baeldung.jackson.general.jsonidentityinfo; package com.baeldung.jackson.general.jsonidentityinfo;
import java.util.List; import java.util.List;
/** /**
@ -11,7 +10,9 @@ import java.util.List;
*/ */
public class Course extends Item { public class Course extends Item {
public enum Medium {CLASSROOM, ONLINE} public enum Medium {
CLASSROOM, ONLINE
}
public enum Level { public enum Level {
BEGINNER("Beginner", 1), INTERMEDIATE("Intermediate", 2), ADVANCED("Advanced", 3); BEGINNER("Beginner", 1), INTERMEDIATE("Intermediate", 2), ADVANCED("Advanced", 3);

View File

@ -13,9 +13,7 @@ import java.util.UUID;
* @author Alex Theedom www.readlearncode.com * @author Alex Theedom www.readlearncode.com
* @version 1.0 * @version 1.0
*/ */
@JsonIdentityInfo( @JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
generator = ObjectIdGenerators.PropertyGenerator.class,
property = "id")
public class Item { public class Item {
private UUID id; private UUID id;
@ -23,7 +21,8 @@ public class Item {
private List<Person> authors = new ArrayList<>(); private List<Person> authors = new ArrayList<>();
private float price; private float price;
public Item(){} public Item() {
}
public Item(String title, Author author) { public Item(String title, Author author) {
this.id = UUID.randomUUID(); this.id = UUID.randomUUID();

View File

@ -14,7 +14,8 @@ public class Person {
private String firstName; private String firstName;
private String lastName; private String lastName;
public Person(){} public Person() {
}
public Person(String firstName, String lastName) { public Person(String firstName, String lastName) {
this.id = UUID.randomUUID(); this.id = UUID.randomUUID();

View File

@ -19,7 +19,8 @@ public class Item {
private List<Person> authors = new ArrayList<>(); private List<Person> authors = new ArrayList<>();
private float price; private float price;
public Item(){} public Item() {
}
public Item(String title, Author author) { public Item(String title, Author author) {
this.id = UUID.randomUUID(); this.id = UUID.randomUUID();

View File

@ -21,10 +21,7 @@ public class JsonPropertyUnitTest {
public void whenSerializingUsingJsonProperty_thenCorrect() throws JsonProcessingException { public void whenSerializingUsingJsonProperty_thenCorrect() throws JsonProcessingException {
// arrange // arrange
Book book = new Book( Book book = new Book("Design Patterns: Elements of Reusable Object-oriented Software", new Author("The", "GoF"));
"Design Patterns: Elements of Reusable Object-oriented Software",
new Author("The", "GoF")
);
book.configureBinding("Hardback"); book.configureBinding("Hardback");
// act // 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\"}"; 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 // act
Book book = new ObjectMapper().readerFor(Book.class).readValue(result); Book book = new ObjectMapper().readerFor(Book.class)
.readValue(result);
// assert // assert
assertThat(book.coverBinding()).isEqualTo("Hardback"); assertThat(book.coverBinding()).isEqualTo("Hardback");
} }
} }

View File

@ -1,6 +1,5 @@
package com.baeldung.jackson.general.jsonunwrapped; package com.baeldung.jackson.general.jsonunwrapped;
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test; import org.junit.Test;

View File

@ -22,7 +22,8 @@ public class JsonViewUnitTest {
Order order = new Order(120); Order order = new Order(120);
// act // act
String result = new ObjectMapper().writerWithView(Views.Internal.class).writeValueAsString(order); String result = new ObjectMapper().writerWithView(Views.Internal.class)
.writeValueAsString(order);
// assert // assert
assertThat(from(result).getUUID("id")).isNotNull(); assertThat(from(result).getUUID("id")).isNotNull();
@ -49,7 +50,8 @@ public class JsonViewUnitTest {
Order order = new Order(120); Order order = new Order(120);
// act // act
String result = new ObjectMapper().writerWithView(Views.Public.class).writeValueAsString(order); String result = new ObjectMapper().writerWithView(Views.Public.class)
.writeValueAsString(order);
// assert // assert
assertThat(from(result).getUUID("id")).isNotNull(); assertThat(from(result).getUUID("id")).isNotNull();
@ -68,5 +70,4 @@ public class JsonViewUnitTest {
} }
} }

View File

@ -1,6 +1,5 @@
package com.baeldung.jackson.general.reference; package com.baeldung.jackson.general.reference;
import java.util.List; import java.util.List;
/** /**
@ -11,7 +10,9 @@ import java.util.List;
*/ */
public class Course extends Item { public class Course extends Item {
public enum Medium {CLASSROOM, ONLINE} public enum Medium {
CLASSROOM, ONLINE
}
public enum Level { public enum Level {
BEGINNER("Beginner", 1), INTERMEDIATE("Intermediate", 2), ADVANCED("Advanced", 3); BEGINNER("Beginner", 1), INTERMEDIATE("Intermediate", 2), ADVANCED("Advanced", 3);

View File

@ -21,7 +21,8 @@ public class Item {
private List<Person> authors = new ArrayList<>(); private List<Person> authors = new ArrayList<>();
private float price; private float price;
public Item(){} public Item() {
}
public Item(String title, Author author) { public Item(String title, Author author) {
this.id = UUID.randomUUID(); this.id = UUID.randomUUID();

View File

@ -14,7 +14,8 @@ public class Person {
private String firstName; private String firstName;
private String lastName; private String lastName;
public Person(){} public Person() {
}
public Person(String firstName, String lastName) { public Person(String firstName, String lastName) {
this.id = UUID.randomUUID(); this.id = UUID.randomUUID();

View File

@ -36,7 +36,7 @@ public class ReferenceUnitTest {
/* /*
Without references defined it throws StackOverflowError. Without references defined it throws StackOverflowError.
Authors excluded. Authors excluded.
{ {
"id": "9c45d9b3-4888-4c24-8b74-65ef35627cd7", "id": "9c45d9b3-4888-4c24-8b74-65ef35627cd7",
"firstName": "Alex", "firstName": "Alex",

Some files were not shown because too many files have changed in this diff Show More