This commit is contained in:
Seun Matt 2017-08-24 16:20:38 +01:00
commit 0d79d018b5
339 changed files with 5543 additions and 2194 deletions

View File

@ -1,11 +1,11 @@
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class BinarySearch {
public int runBinarySearch() {
int[] sortedArray = { 0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9 };
int key = 6;
public int runBinarySearchIteratively(int[] sortedArray, int key, int low, int high) {
int low = 0;
int high = sortedArray.length - 1;
int index = Integer.MAX_VALUE;
while (low <= high) {
@ -23,4 +23,31 @@ public class BinarySearch {
}
return index;
}
public int runBinarySearchRecursively(int[] sortedArray, int key, int low, int high) {
int middle = (low + high) / 2;
if (high < low) {
return -1;
}
if (key == sortedArray[middle]) {
return middle;
} else if (key < sortedArray[middle]) {
return runBinarySearchRecursively(sortedArray, key, low, middle - 1);
} else {
return runBinarySearchRecursively(sortedArray, key, middle + 1, high);
}
}
public int runBinarySearchUsingJavaArrays(int[] sortedArray, Integer key) {
int index = Arrays.binarySearch(sortedArray, key);
return index;
}
public int runBinarySearchUsingJavaCollections(List<Integer> sortedList, Integer key) {
int index = Collections.binarySearch(sortedList, key);
return index;
}
}

View File

@ -1,14 +1,41 @@
import java.util.Arrays;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
public class BinarySearchTest {
@Test
public void givenASortedArrayOfIntegers_whenBinarySearchRunForANumber_thenGetIndexOfTheNumber() {
BinarySearch binSearch = new BinarySearch();
int[] sortedArray = { 0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9 };
int key = 6;
int expectedIndexForSearchKey = 7;
Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearch());
int low = 0;
int high = sortedArray.length - 1;
List<Integer> sortedList = Arrays.asList(0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9);
@Test
public void givenASortedArrayOfIntegers_whenBinarySearchRunIterativelyForANumber_thenGetIndexOfTheNumber() {
BinarySearch binSearch = new BinarySearch();
Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchIteratively(sortedArray, key, low, high));
}
@Test
public void givenASortedArrayOfIntegers_whenBinarySearchRunRecursivelyForANumber_thenGetIndexOfTheNumber() {
BinarySearch binSearch = new BinarySearch();
Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchRecursively(sortedArray, key, low, high));
}
@Test
public void givenASortedArrayOfIntegers_whenBinarySearchRunUsingArraysClassStaticMethodForANumber_thenGetIndexOfTheNumber() {
BinarySearch binSearch = new BinarySearch();
Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchUsingJavaArrays(sortedArray, key));
}
@Test
public void givenASortedListOfIntegers_whenBinarySearchRunUsingCollectionsClassStaticMethodForANumber_thenGetIndexOfTheNumber() {
BinarySearch binSearch = new BinarySearch();
Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchUsingJavaCollections(sortedList, key));
}
}

View File

@ -1,3 +1,4 @@
### Relevant articles
- [Introduction to Asciidoctor](http://www.baeldung.com/introduction-to-asciidoctor)
- [Generating a Book with Asciidoctor](http://www.baeldung.com/asciidoctor-book)

View File

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

View File

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

View File

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

View File

@ -10,9 +10,7 @@ public class DecoratorPatternDriver {
LOG.info(tree1.decorate());
// christmas tree with two Garlands and one Bubble lights
ChristmasTree tree2 = new BubbleLights(new Garland(
new Garland(new ChristmasTreeImpl()))
);
ChristmasTree tree2 = new BubbleLights(new Garland(new Garland(new ChristmasTreeImpl())));
LOG.info(tree2.decorate());
}

View File

@ -43,6 +43,7 @@ public class CustomRecursiveAction extends RecursiveAction {
private void processing(String work) {
String result = work.toUpperCase();
logger.info("This result - (" + result + ") - was processed by " + Thread.currentThread().getName());
logger.info("This result - (" + result + ") - was processed by " + Thread.currentThread()
.getName());
}
}

View File

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

View File

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

View File

@ -14,7 +14,8 @@ public class Screenshot {
}
public void getScreenshot(int timeToWait) throws Exception {
Rectangle rectangle = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
Rectangle rectangle = new Rectangle(Toolkit.getDefaultToolkit()
.getScreenSize());
Robot robot = new Robot();
BufferedImage img = robot.createScreenCapture(rectangle);
ImageIO.write(img, "jpg", new File(path));

View File

@ -60,7 +60,6 @@ public class UUIDGenerator {
return uuid;
}
public static UUID type5UUIDFromBytes(byte[] name) {
MessageDigest md;
try {
@ -89,7 +88,6 @@ public class UUIDGenerator {
return new UUID(msb, lsb);
}
/**
* Unique Keys Generation Using Message Digest and Type 4 UUID
*

View File

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

View File

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

View File

@ -15,12 +15,14 @@ public class UseLocalDateUnitTest {
@Test
public void givenValues_whenUsingFactoryOf_thenLocalDate() {
assertEquals("2016-05-10", useLocalDate.getLocalDateUsingFactoryOfMethod(2016, 5, 10).toString());
assertEquals("2016-05-10", useLocalDate.getLocalDateUsingFactoryOfMethod(2016, 5, 10)
.toString());
}
@Test
public void givenString_whenUsingParse_thenLocalDate() {
assertEquals("2016-05-10", useLocalDate.getLocalDateUsingParseMethod("2016-05-10").toString());
assertEquals("2016-05-10", useLocalDate.getLocalDateUsingParseMethod("2016-05-10")
.toString());
}
@Test
@ -30,12 +32,14 @@ public class UseLocalDateUnitTest {
@Test
public void givenDate_whenUsingPlus_thenNextDay() {
assertEquals(LocalDate.now().plusDays(1), useLocalDate.getNextDay(LocalDate.now()));
assertEquals(LocalDate.now()
.plusDays(1), useLocalDate.getNextDay(LocalDate.now()));
}
@Test
public void givenDate_whenUsingMinus_thenPreviousDay() {
assertEquals(LocalDate.now().minusDays(1), useLocalDate.getPreviousDay(LocalDate.now()));
assertEquals(LocalDate.now()
.minusDays(1), useLocalDate.getPreviousDay(LocalDate.now()));
}
@Test
@ -45,7 +49,8 @@ public class UseLocalDateUnitTest {
@Test
public void givenToday_whenUsingWithTemporalAdjuster_thenFirstDayOfMonth() {
assertEquals(1, useLocalDate.getFirstDayOfMonth().getDayOfMonth());
assertEquals(1, useLocalDate.getFirstDayOfMonth()
.getDayOfMonth());
}
@Test

View File

@ -21,7 +21,6 @@ public class FunctionalInterfaceUnitTest {
private static final Logger LOG = LoggerFactory.getLogger(FunctionalInterfaceUnitTest.class);
@Test
public void whenPassingLambdaToComputeIfAbsent_thenTheValueGetsComputedAndPutIntoMap() {
Map<String, Integer> nameMap = new HashMap<>();
@ -83,7 +82,8 @@ public class FunctionalInterfaceUnitTest {
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(1));
@ -112,7 +112,9 @@ public class FunctionalInterfaceUnitTest {
public void whenUsingPredicateInFilter_thenListValuesAreFilteredOut() {
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());
assertTrue(namesWithA.contains("Angela"));
@ -135,7 +137,8 @@ public class FunctionalInterfaceUnitTest {
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);

View File

@ -47,7 +47,8 @@ public class ConcurrentMapAggregateStatusManualTest {
executorService.awaitTermination(1, TimeUnit.MINUTES);
for (int i = 1; i <= MAX_SIZE; i++) {
assertEquals("map size should be consistently reliable", i, mapSizes.get(i - 1).intValue());
assertEquals("map size should be consistently reliable", i, mapSizes.get(i - 1)
.intValue());
}
assertEquals(MAX_SIZE, concurrentMap.size());
}
@ -69,7 +70,8 @@ public class ConcurrentMapAggregateStatusManualTest {
executorService.shutdown();
executorService.awaitTermination(1, TimeUnit.MINUTES);
assertNotEquals("map size collected with concurrent updates not reliable", MAX_SIZE, mapSizes.get(MAX_SIZE - 1).intValue());
assertNotEquals("map size collected with concurrent updates not reliable", MAX_SIZE, mapSizes.get(MAX_SIZE - 1)
.intValue());
assertEquals(MAX_SIZE, concurrentMap.size());
}

View File

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

View File

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

View File

@ -27,8 +27,8 @@ public class Java8MapAndFlatMap {
List<List<String>> list = Arrays.asList(Arrays.asList("a"), Arrays.asList("b"));
System.out.println(list);
System.out.println(list
.stream().flatMap(Collection::stream)
System.out.println(list.stream()
.flatMap(Collection::stream)
.collect(Collectors.toList()));
}
@ -40,12 +40,10 @@ public class Java8MapAndFlatMap {
@Test
public void givenOptional_whenCalledFlatMap_thenProduceFlattenedOptional() {
assertEquals(Optional.of(Optional.of("STRING")), Optional
.of("string")
assertEquals(Optional.of(Optional.of("STRING")), Optional.of("string")
.map(s -> Optional.of("STRING")));
assertEquals(Optional.of("STRING"), Optional
.of("string")
assertEquals(Optional.of("STRING"), Optional.of("string")
.flatMap(s -> Optional.of("STRING")));
}

View File

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

View File

@ -1,4 +1,5 @@
package com.baeldung.java8.comparator;
import java.util.Arrays;
import java.util.Comparator;
@ -25,37 +26,25 @@ public class Java8ComparatorUnitTest {
@Before
public void initData() {
employees = new Employee[] { new Employee("John", 25, 3000, 9922001), new Employee("Ace", 22, 2000, 5924001),
new Employee("Keith", 35, 4000, 3924401) };
employeesArrayWithNulls = new Employee[] { new Employee("John", 25, 3000, 9922001), null, new Employee("Ace", 22, 2000, 5924001),
null, new Employee("Keith", 35, 4000, 3924401) };
employees = new Employee[] { new Employee("John", 25, 3000, 9922001), new Employee("Ace", 22, 2000, 5924001), new Employee("Keith", 35, 4000, 3924401) };
employeesArrayWithNulls = new Employee[] { new Employee("John", 25, 3000, 9922001), null, new Employee("Ace", 22, 2000, 5924001), null, new Employee("Keith", 35, 4000, 3924401) };
sortedEmployeesByName = new Employee[] { new Employee("Ace", 22, 2000, 5924001),
new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) };
sortedEmployeesByNameDesc = new Employee[] { new Employee("Keith", 35, 4000, 3924401), new Employee("John", 25, 3000, 9922001),
new Employee("Ace", 22, 2000, 5924001) };
sortedEmployeesByName = new Employee[] { new Employee("Ace", 22, 2000, 5924001), new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) };
sortedEmployeesByNameDesc = new Employee[] { new Employee("Keith", 35, 4000, 3924401), new Employee("John", 25, 3000, 9922001), new Employee("Ace", 22, 2000, 5924001) };
sortedEmployeesByAge = new Employee[] { new Employee("Ace", 22, 2000, 5924001),
new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) };
sortedEmployeesByAge = new Employee[] { new Employee("Ace", 22, 2000, 5924001), new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) };
sortedEmployeesByMobile = new Employee[] { new Employee("Keith", 35, 4000, 3924401), new Employee("Ace", 22, 2000, 5924001),
new Employee("John", 25, 3000, 9922001), };
sortedEmployeesByMobile = new Employee[] { new Employee("Keith", 35, 4000, 3924401), new Employee("Ace", 22, 2000, 5924001), new Employee("John", 25, 3000, 9922001), };
sortedEmployeesBySalary = new Employee[] { new Employee("Ace", 22, 2000, 5924001), new Employee("John", 25, 3000, 9922001),
new Employee("Keith", 35, 4000, 3924401), };
sortedEmployeesBySalary = new Employee[] { new Employee("Ace", 22, 2000, 5924001), new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401), };
sortedEmployeesArray_WithNullsFirst = new Employee[] { null, null, new Employee("Ace", 22, 2000, 5924001),
new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) };
sortedEmployeesArray_WithNullsLast = new Employee[] { new Employee("Ace", 22, 2000, 5924001),
new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401), null, null };
sortedEmployeesArray_WithNullsFirst = new Employee[] { null, null, new Employee("Ace", 22, 2000, 5924001), new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) };
sortedEmployeesArray_WithNullsLast = new Employee[] { new Employee("Ace", 22, 2000, 5924001), new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401), null, null };
someMoreEmployees = new Employee[] { new Employee("Jake", 25, 3000, 9922001), new Employee("Jake", 22, 2000, 5924001),
new Employee("Ace", 22, 3000, 6423001), new Employee("Keith", 35, 4000, 3924401) };
someMoreEmployees = new Employee[] { new Employee("Jake", 25, 3000, 9922001), new Employee("Jake", 22, 2000, 5924001), new Employee("Ace", 22, 3000, 6423001), new Employee("Keith", 35, 4000, 3924401) };
sortedEmployeesByAgeName = new Employee[] { new Employee("Ace", 22, 3000, 6423001),
new Employee("Jake", 22, 2000, 5924001), new Employee("Jake", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) };
sortedEmployeesByNameAge = new Employee[] { new Employee("Ace", 22, 3000, 6423001),
new Employee("Jake", 22, 2000, 5924001), new Employee("Jake", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) };
sortedEmployeesByAgeName = new Employee[] { new Employee("Ace", 22, 3000, 6423001), new Employee("Jake", 22, 2000, 5924001), new Employee("Jake", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) };
sortedEmployeesByNameAge = new Employee[] { new Employee("Ace", 22, 3000, 6423001), new Employee("Jake", 22, 2000, 5924001), new Employee("Jake", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) };
}
@Test
@ -145,7 +134,8 @@ public class Java8ComparatorUnitTest {
@Test
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);
// System.out.println(Arrays.toString(someMoreEmployees));
@ -154,12 +144,12 @@ public class Java8ComparatorUnitTest {
@Test
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);
// System.out.println(Arrays.toString(someMoreEmployees));
assertTrue(Arrays.equals(someMoreEmployees, sortedEmployeesByNameAge));
}
}

View File

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

View File

@ -43,6 +43,8 @@ public class FlattenNestedListUnitTest {
}
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

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

View File

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

View File

@ -0,0 +1,47 @@
package com.baeldung.string;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
public class CharSequenceVsStringUnitTest {
@Test
public void givenUsingString_whenInstantiatingString_thenWrong() {
CharSequence firstString = "bealdung";
String secondString = "baeldung";
assertNotEquals(firstString, secondString);
}
@Test
public void givenIdenticalCharSequences_whenCastToString_thenEqual() {
CharSequence charSequence1 = "baeldung_1";
CharSequence charSequence2 = "baeldung_2";
assertTrue(charSequence1.toString().compareTo(charSequence2.toString()) > 0);
}
@Test
public void givenString_whenAppended_thenUnmodified() {
String test = "a";
int firstAddressOfTest = System.identityHashCode(test);
test += "b";
int secondAddressOfTest = System.identityHashCode(test);
assertEquals(firstAddressOfTest, secondAddressOfTest);
}
@Test
public void givenStringBuilder_whenAppended_thenModified() {
StringBuilder test = new StringBuilder();
test.append("a");
int firstAddressOfTest = System.identityHashCode(test);
test.append("b");
int secondAddressOfTest = System.identityHashCode(test);
assertEquals(firstAddressOfTest, secondAddressOfTest);
}
}

View File

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

View File

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

View File

@ -15,7 +15,6 @@ public class JavaTimerLongRunningUnitTest {
private static final Logger LOG = LoggerFactory.getLogger(JavaTimerLongRunningUnitTest.class);
// tests
@Test
@ -23,7 +22,8 @@ public class JavaTimerLongRunningUnitTest {
final TimerTask timerTask = new TimerTask() {
@Override
public void run() {
LOG.debug("Task performed on: " + new Date() + "\n" + "Thread's name: " + Thread.currentThread().getName());
LOG.debug("Task performed on: " + new Date() + "\n" + "Thread's name: " + Thread.currentThread()
.getName());
}
};
final Timer timer = new Timer("Timer");

View File

@ -0,0 +1,31 @@
package org.baeldung.java.lists;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
public class ListToSTring {
@Test
public void whenListToString_thenPrintDefault() {
List<Integer> intLIst = Arrays.asList(1, 2, 3);
System.out.println(intLIst);
}
@Test
public void whenCollectorsJoining_thenPrintCustom() {
List<Integer> intList = Arrays.asList(1, 2, 3);
System.out.println(intList.stream()
.map(n -> String.valueOf(n))
.collect(Collectors.joining("-", "{", "}")));
}
@Test
public void whenStringUtilsJoin_thenPrintCustom() {
List<Integer> intList = Arrays.asList(1, 2, 3);
System.out.println(StringUtils.join(intList, "|"));
}
}

View File

@ -38,7 +38,8 @@ public class Employee implements Comparable {
@Override
public boolean equals(Object obj) {
return ((Employee) obj).getName().equals(getName());
return ((Employee) obj).getName()
.equals(getName());
}
@Override
@ -49,7 +50,13 @@ public class Employee implements Comparable {
@Override
public String toString() {
return new StringBuffer().append("(").append(getName()).append(getAge()).append(",").append(getSalary()).append(")").toString();
return new StringBuffer().append("(")
.append(getName())
.append(getAge())
.append(",")
.append(getSalary())
.append(")")
.toString();
}
}

View File

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

View File

@ -14,6 +14,12 @@ public class BookControllerFeignClientBuilder {
private BookClient bookClient = createClient(BookClient.class, "http://localhost:8081/api/books");
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
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);
log.info("{}", books);
}
@Test
public void givenBookClient_shouldFindOneBook() throws Exception {
Book book = bookClient.findByIsbn("0151072558").getBook();
Book book = bookClient.findByIsbn("0151072558")
.getBook();
assertThat(book.getAuthor(), containsString("Orwell"));
log.info("{}", book);
}
@Test
public void givenBookClient_shouldPostBook() throws Exception {
String isbn = UUID.randomUUID().toString();
String isbn = UUID.randomUUID()
.toString();
Book book = new Book(isbn, "Me", "It's me!", null, null);
bookClient.create(book);
book = bookClient.findByIsbn(isbn).getBook();
book = bookClient.findByIsbn(isbn)
.getBook();
assertThat(book.getAuthor(), is("Me"));
log.info("{}", book);
}

View File

@ -0,0 +1,41 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.stackify</groupId>
<artifactId>logback-example</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.codehaus.janino</groupId>
<artifactId>janino</artifactId>
<version>3.0.7</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,28 @@
package com.stackify.logging;
import org.slf4j.Marker;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.turbo.TurboFilter;
import ch.qos.logback.core.spi.FilterReply;
public class IgnoreLoggerFilter extends TurboFilter {
private String loggerName;
@Override
public FilterReply decide(Marker marker, Logger logger, Level level, String format, Object[] params, Throwable t) {
if (loggerName == null) {
return FilterReply.NEUTRAL;
} else if (loggerName.equals(logger.getName())) {
return FilterReply.DENY;
} else
return FilterReply.NEUTRAL;
}
public void setLoggerName(String loggerName) {
this.loggerName = loggerName;
}
}

View File

@ -0,0 +1,43 @@
package com.stackify.models;
public class Employee {
private String email;
private String name;
private double salary;
public Employee() {
}
public Employee(String email, String name, double salary) {
this.email = email;
this.name = name;
this.salary = salary;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
}

View File

@ -0,0 +1,11 @@
package com.stackify.services;
import com.stackify.models.Employee;
public class EmployeeService {
public double calculateBonus(Employee user) {
return 0.1 * user.getSalary();
}
}

View File

@ -0,0 +1 @@
env=dev

View File

@ -0,0 +1,151 @@
<configuration debug="true">
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
</encoder>
<target>System.out</target>
</appender>
<property name="fileName" value="file.log" />
<property scope="context" resource="application.properties" />
<!-- configure appenders -->
<appender name="rollingFileAppender" class="ch.qos.logback.core.rolling.RollingFileAppender">
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>log-%d{yyyy-MM-dd}.log</fileNamePattern>
<maxHistory>30</maxHistory>
<totalSizeCap>3GB</totalSizeCap>
</rollingPolicy>
<triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
<maxFileSize>3MB</maxFileSize>
</triggeringPolicy>
<encoder>
<pattern>%d [%thread] %-5level %logger{50} - %msg%n</pattern>
</encoder>
</appender>
<appender name="roleSiftingAppender" class="ch.qos.logback.classic.sift.SiftingAppender">
<discriminator>
<key>userRole</key>
<defaultValue>ANONYMOUS</defaultValue>
</discriminator>
<sift>
<appender name="fileAppender" class="ch.qos.logback.core.FileAppender">
<file>${userRole}.log</file>
<layout class="ch.qos.logback.classic.PatternLayout">
<pattern>%d [%thread] %level %mdc %logger{50} - %msg%n</pattern>
</layout>
</appender>
</sift>
</appender>
<!-- configure layouts -->
<appender name="colorAppender" class="ch.qos.logback.core.ConsoleAppender">
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>%d %green([%thread]) %highlight(%level) %logger{50} - %msg%n</pattern>
</encoder>
</appender>
<appender name="htmlAppender" class="ch.qos.logback.core.FileAppender">
<encoder class="ch.qos.logback.core.encoder.LayoutWrappingEncoder">
<layout class="ch.qos.logback.classic.html.HTMLLayout">
<pattern>%thread%level%logger%msg</pattern>
</layout>
</encoder>
<file>log.html</file>
</appender>
<!-- configure filters -->
<appender name="STDOUT_LEVEL_FILTER_APPENDER" class="ch.qos.logback.core.ConsoleAppender">
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>ERROR</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
</encoder>
<target>System.err</target>
</appender>
<appender name="STDOUT_THRESHOLD_FILTER_APPENDER" class="ch.qos.logback.core.ConsoleAppender">
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>WARN</level>
</filter>
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
</encoder>
</appender>
<appender name="STDOUT_EVALUATOR_FILTER_APPENDER" class="ch.qos.logback.core.ConsoleAppender">
<filter class="ch.qos.logback.core.filter.EvaluatorFilter">
<evaluator class="ch.qos.logback.classic.boolex.JaninoEventEvaluator">
<expression>return (level > DEBUG &amp;&amp; message.toLowerCase().contains("employee"));</expression>
</evaluator>
<OnMismatch>DENY</OnMismatch>
<OnMatch>NEUTRAL</OnMatch>
</filter>
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
</encoder>
</appender>
<!-- configure turbo filters -->
<turboFilter class="ch.qos.logback.classic.turbo.DuplicateMessageFilter">
<AllowedRepetitions>2</AllowedRepetitions>
</turboFilter>
<turboFilter class="com.stackify.logging.IgnoreLoggerFilter">
<LoggerName>ignoredColorLogger</LoggerName>
</turboFilter>
<!-- configure loggers -->
<logger level="info" name="rollingFileLogger" additivity="false">
<appender-ref ref="rollingFileAppender" />
</logger>
<logger level="info" name="htmlLogger" additivity="false">
<appender-ref ref="htmlAppender" />
</logger>
<logger level="info" name="roleSiftingLogger" additivity="false">
<appender-ref ref="roleSiftingAppender" />
</logger>
<logger level="info" name="colorLogger" additivity="false">
<appender-ref ref="colorAppender" />
</logger>
<logger level="info" name="ignoredColorLogger">
<appender-ref ref="colorAppender" />
</logger>
<logger level="info" name="levelFilterLogger" additivity="false">
<appender-ref ref="STDOUT_LEVEL_FILTER_APPENDER" />
</logger>
<logger level="info" name="thresholdFilterLogger" additivity="false">
<appender-ref ref="STDOUT_THRESHOLD_FILTER_APPENDER" />
</logger>
<logger level="info" name="evaluatorFilterLogger" additivity="false">
<appender-ref ref="STDOUT_EVALUATOR_FILTER_APPENDER" />
</logger>
<!-- configure root logger -->
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
<!-- configure root logger conditionally -->
<property scope="context" resource="application.properties" />
<if condition='property("env").equals("dev")'>
<then>
<root level="TRACE">
<appender-ref ref="STDOUT" />
</root>
</then>
</if>
</configuration>

View File

@ -0,0 +1,74 @@
package com.stackify.services;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import com.stackify.models.Employee;
import ch.qos.logback.classic.Level;
public class EmployeeServiceTest {
private static final Logger logger = LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
private EmployeeService employeeService = new EmployeeService();
@Test
public void testAppenders() {
Logger rollingFileLogger = LoggerFactory.getLogger("rollingFileLogger");
rollingFileLogger.info("Testing rolling file logger");
MDC.put("userRole", "ADMIN");
Logger siftingLogger = LoggerFactory.getLogger("roleSiftingLogger");
siftingLogger.info("Admin Action");
}
@Test
public void testLayouts() {
Logger htmlLogger = LoggerFactory.getLogger("htmlLogger");
htmlLogger.error("Employee Information Update Failed");
htmlLogger.info("New Account Created");
Logger colorLogger = LoggerFactory.getLogger("colorLogger");
colorLogger.error("Employee Information Update Failed");
colorLogger.info("New Account Created");
}
@Test
public void testLogLevel() {
ch.qos.logback.classic.Logger rollingFileLogger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger("rollingFileLogger");
rollingFileLogger.setLevel(Level.DEBUG);
rollingFileLogger.debug("Testing Log Level");
}
@Test
public void testParameter() {
Employee employee = new Employee("john@gmail.com", "John", 2000);
if (logger.isDebugEnabled()) {
logger.debug("The bonus for employee: " + employee.getName() + " is " + employeeService.calculateBonus(employee));
}
logger.debug("The bonus for employee {} is {}", employee.getName(), employeeService.calculateBonus(employee));
}
@Test
public void testFilters() {
Logger levelFilterLogger = LoggerFactory.getLogger("levelFilterLogger");
levelFilterLogger.error("Employee Information Update Failed");
Logger thresholdFilterLogger = LoggerFactory.getLogger("thresholdFilterLogger");
thresholdFilterLogger.trace("Employee record inserted");
Logger evaluatorFilterLogger = LoggerFactory.getLogger("evaluatorFilterLogger");
evaluatorFilterLogger.debug("Employee account deactivated");
}
@Test
public void testIgnoredLogger() {
Logger colorLogger = LoggerFactory.getLogger("ignoredColorLogger");
colorLogger.info("Ignored Log Message");
}
@Test
public void testConditionalConfiguration() {
logger.trace("Employee record updated");
}
}

View File

@ -0,0 +1,28 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.stackify</groupId>
<artifactId>thread-pools</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,28 @@
package com.stackify.models;
public class Employee {
private String name;
private double salary;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public Employee(String name, double salary) {
super();
this.name = name;
this.salary = salary;
}
}

View File

@ -0,0 +1,9 @@
package com.stackify.services;
import com.stackify.models.Employee;
public class EmployeeService {
public double calculateBonus(Employee employee) {
return 0.1 * employee.getSalary();
}
}

View File

@ -0,0 +1,64 @@
package com.stackify.threadpools;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;
import java.util.stream.IntStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class FactorialTask extends RecursiveTask<BigInteger> {
private static final Logger logger = LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
private static final long serialVersionUID = 1L;
private int start = 1;
private int n;
private static final int THRESHOLD = 20;
public FactorialTask(int n) {
this.n = n;
}
public FactorialTask(int start, int n) {
logger.info("New FactorialTask Created");
this.start = start;
this.n = n;
}
@Override
protected BigInteger compute() {
if ((n - start) >= THRESHOLD) {
return ForkJoinTask.invokeAll(createSubtasks())
.stream()
.map(ForkJoinTask::join)
.reduce(BigInteger.ONE, BigInteger::multiply);
} else {
return calculate(start, n);
}
}
private Collection<FactorialTask> createSubtasks() {
List<FactorialTask> dividedTasks = new ArrayList<>();
int mid = (start + n) / 2;
dividedTasks.add(new FactorialTask(start, mid));
dividedTasks.add(new FactorialTask(mid + 1, n));
return dividedTasks;
}
private BigInteger calculate(int start, int n) {
logger.info("Calculate factorial from " + start + " to " + n);
return IntStream.rangeClosed(start, n)
.mapToObj(BigInteger::valueOf)
.reduce(BigInteger.ONE, BigInteger::multiply);
}
}

View File

@ -0,0 +1,102 @@
package com.stackify.threadpools;
import java.math.BigInteger;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.stackify.models.Employee;
import com.stackify.services.EmployeeService;
public class ThreadsApplication {
private static final Logger logger = LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
public static void main(String[] args) {
testExecutor();
testExecutorService();
testScheduledExecutorService();
testThreadPoolExecutor();
testForkJoinPool();
}
private static EmployeeService employeeService = new EmployeeService();
public static void testExecutor() {
Executor executor = Executors.newSingleThreadExecutor();
executor.execute(() -> System.out.println("Single thread pool test"));
}
public static void testExecutorService() {
Employee employee = new Employee("John", 2000);
ExecutorService executor = Executors.newFixedThreadPool(10);
Callable<Double> callableTask = () -> {
return employeeService.calculateBonus(employee);
};
Future<Double> future = executor.submit(callableTask);
try {
if (future.isDone()) {
double result = future.get();
System.out.println("Bonus is:" + result);
}
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
executor.shutdown();
}
public static void testScheduledExecutorService() {
Employee employee = new Employee("John", 2000);
ScheduledExecutorService executor = Executors.newScheduledThreadPool(10);
Callable<Double> callableTask = () -> {
return employeeService.calculateBonus(employee);
};
Future<Double> futureScheduled = executor.schedule(callableTask, 2, TimeUnit.MILLISECONDS);
try {
System.out.println("Bonus:" + futureScheduled.get());
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
executor.scheduleAtFixedRate(() -> System.out.println("Fixed Rate Scheduled"), 2, 2000, TimeUnit.MILLISECONDS);
executor.scheduleWithFixedDelay(() -> System.out.println("Fixed Delay Scheduled"), 2, 2000, TimeUnit.MILLISECONDS);
}
public static void testThreadPoolExecutor() {
ThreadPoolExecutor fixedPoolExecutor = (ThreadPoolExecutor) Executors.newFixedThreadPool(10);
ThreadPoolExecutor cachedPoolExecutor = (ThreadPoolExecutor) Executors.newCachedThreadPool();
ThreadPoolExecutor executor = new ThreadPoolExecutor(4, 6, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
executor.setMaximumPoolSize(8);
ScheduledThreadPoolExecutor scheduledExecutor = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(5);
}
public static void testForkJoinPool() {
ForkJoinPool pool = ForkJoinPool.commonPool();
logger.info("Thread Pool Created");
BigInteger result = pool.invoke(new FactorialTask(100));
System.out.println(result.toString());
}
}

View File

@ -129,7 +129,7 @@
<properties>
<!-- marshalling -->
<jackson.version>2.8.7</jackson.version>
<jackson.version>2.9.0</jackson.version>
<!-- util -->
<guava.version>19.0</guava.version>

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -15,9 +15,7 @@ public class MyPairSerializer extends JsonSerializer<MyPair> {
private final ObjectMapper mapper = new ObjectMapper();
@Override
public void serialize(MyPair value, JsonGenerator gen,
SerializerProvider serializers) throws IOException,
JsonProcessingException {
public void serialize(MyPair value, JsonGenerator gen, SerializerProvider serializers) throws IOException, JsonProcessingException {
StringWriter writer = new StringWriter();
mapper.writeValue(writer, value);
gen.writeFieldName(writer.toString());

View File

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

View File

@ -1,6 +1,5 @@
package com.baeldung.jackson.serialization.jsonpropertyorder;
import com.baeldung.jackson.domain.Item;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;

View File

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

View File

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

View File

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

View File

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

View File

@ -47,7 +47,8 @@ public class ExtraAnnotationUnitTest {
ObjectMapper mapper = new ObjectMapper();
BeanWithoutAppend bean = new BeanWithoutAppend(2, "Bean Without Append Annotation");
ObjectWriter writer = mapper.writerFor(BeanWithoutAppend.class).withAttribute("version", "1.0");
ObjectWriter writer = mapper.writerFor(BeanWithoutAppend.class)
.withAttribute("version", "1.0");
String jsonString = writer.writeValueAsString(bean);
assertThat(jsonString, not(containsString("version")));
@ -59,7 +60,8 @@ public class ExtraAnnotationUnitTest {
ObjectMapper mapper = new ObjectMapper();
BeanWithAppend bean = new BeanWithAppend(2, "Bean With Append Annotation");
ObjectWriter writer = mapper.writerFor(BeanWithAppend.class).withAttribute("version", "1.0");
ObjectWriter writer = mapper.writerFor(BeanWithAppend.class)
.withAttribute("version", "1.0");
String jsonString = writer.writeValueAsString(bean);
assertThat(jsonString, containsString("version"));

View File

@ -4,7 +4,6 @@ import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.JsonIdentityReference;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
public class IdentityReferenceBeans {
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
public static class BeanWithoutIdentityReference {

View File

@ -20,6 +20,7 @@ public class CustomListSerializer extends StdSerializer<List<ItemWithSerializer>
public CustomListSerializer(final Class<List<ItemWithSerializer>> t) {
super(t);
}
@Override
public void serialize(final List<ItemWithSerializer> items, final JsonGenerator generator, final SerializerProvider provider) throws IOException, JsonProcessingException {
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> {
private static final long serialVersionUID = -7449444168934819290L;
private static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");

View File

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

View File

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

View File

@ -21,8 +21,7 @@ public class JacksonMapDeserializeUnitTest {
final ObjectMapper mapper = new ObjectMapper();
@Test
public void whenSimpleMapDeserialize_thenCorrect()
throws JsonParseException, JsonMappingException, IOException {
public void whenSimpleMapDeserialize_thenCorrect() throws JsonParseException, JsonMappingException, IOException {
final String jsonInput = "{\"key\": \"value\"}";
TypeReference<HashMap<String, String>> typeRef = new TypeReference<HashMap<String, String>>() {
@ -34,8 +33,7 @@ public class JacksonMapDeserializeUnitTest {
}
@Test
public void whenObjectStringMapDeserialize_thenCorrect()
throws JsonParseException, JsonMappingException, IOException {
public void whenObjectStringMapDeserialize_thenCorrect() throws JsonParseException, JsonMappingException, IOException {
final String jsonInput = "{\"Abbott and Costello\":\"Comedy\"}";
@ -46,16 +44,14 @@ public class JacksonMapDeserializeUnitTest {
Assert.assertEquals("Comedy", map.get(new MyPair("Abbott", "Costello")));
ClassWithAMap classWithMap = mapper.readValue(jsonInput,
ClassWithAMap.class);
ClassWithAMap classWithMap = mapper.readValue(jsonInput, ClassWithAMap.class);
Assert.assertEquals("Comedy",
classWithMap.getMap().get(new MyPair("Abbott", "Costello")));
Assert.assertEquals("Comedy", classWithMap.getMap()
.get(new MyPair("Abbott", "Costello")));
}
@Test
public void whenObjectObjectMapDeserialize_thenCorrect()
throws JsonParseException, JsonMappingException, IOException {
public void whenObjectObjectMapDeserialize_thenCorrect() throws JsonParseException, JsonMappingException, IOException {
final String jsonInput = "{\"Abbott and Costello\" : \"Comedy and 1940s\"}";
TypeReference<HashMap<MyPair, MyPair>> typeRef = new TypeReference<HashMap<MyPair, MyPair>>() {
@ -63,7 +59,6 @@ public class JacksonMapDeserializeUnitTest {
cmap = mapper.readValue(jsonInput, typeRef);
Assert.assertEquals(new MyPair("Comedy", "1940s"),
cmap.get(new MyPair("Abbott", "Costello")));
Assert.assertEquals(new MyPair("Comedy", "1940s"), cmap.get(new MyPair("Abbott", "Costello")));
}
}

View File

@ -27,7 +27,9 @@ public class JacksonInjectUnitTest {
// act
InjectableValues inject = new InjectableValues.Std().addValue(UUID.class, id);
Author author = new ObjectMapper().reader(inject).forType(Author.class).readValue(authorJson);
Author author = new ObjectMapper().reader(inject)
.forType(Author.class)
.readValue(authorJson);
// assert
assertThat(author.getId()).isEqualTo(id);

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}";
// act
Inventory inventory = new ObjectMapper().readerFor(Inventory.class).readValue(json);
Inventory inventory = new ObjectMapper().readerFor(Inventory.class)
.readValue(json);
// assert
assertThat(from(json).getMap(".").get("USA")).isEqualTo(inventory.getCountryDeliveryCost().get("USA"));
assertThat(from(json).getMap(".").get("UK")).isEqualTo(inventory.getCountryDeliveryCost().get("UK"));
assertThat(from(json).getMap(".").get("China")).isEqualTo(inventory.getCountryDeliveryCost().get("China"));
assertThat(from(json).getMap(".").get("Brazil")).isEqualTo(inventory.getCountryDeliveryCost().get("Brazil"));
assertThat(from(json).getMap(".").get("France")).isEqualTo(inventory.getCountryDeliveryCost().get("France"));
assertThat(from(json).getMap(".").get("Russia")).isEqualTo(inventory.getCountryDeliveryCost().get("Russia"));
assertThat(from(json).getMap(".")
.get("USA")).isEqualTo(inventory.getCountryDeliveryCost()
.get("USA"));
assertThat(from(json).getMap(".")
.get("UK")).isEqualTo(inventory.getCountryDeliveryCost()
.get("UK"));
assertThat(from(json).getMap(".")
.get("China")).isEqualTo(inventory.getCountryDeliveryCost()
.get("China"));
assertThat(from(json).getMap(".")
.get("Brazil")).isEqualTo(inventory.getCountryDeliveryCost()
.get("Brazil"));
assertThat(from(json).getMap(".")
.get("France")).isEqualTo(inventory.getCountryDeliveryCost()
.get("France"));
assertThat(from(json).getMap(".")
.get("Russia")).isEqualTo(inventory.getCountryDeliveryCost()
.get("Russia"));
}
}

View File

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

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

View File

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

View File

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

View File

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

View File

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

View File

@ -27,13 +27,11 @@ public class JsonFormatUnitTest {
String result = new ObjectMapper().writeValueAsString(user);
// Expected to match: "2016-12-19@09:34:42.628+0000"
assertThat(from(result).getString("createdDate"))
.matches("\\d{4}\\-\\d{2}\\-\\d{2}@\\d{2}:\\d{2}:\\d{2}\\.\\d{3}\\+\\d{4}");
assertThat(from(result).getString("createdDate")).matches("\\d{4}\\-\\d{2}\\-\\d{2}@\\d{2}:\\d{2}:\\d{2}\\.\\d{3}\\+\\d{4}");
// Expected to be close to current time
long now = new Date().getTime();
assertThat(from(result).getLong("dateNum"))
.isCloseTo(now, withPercentage(10.0));
assertThat(from(result).getLong("dateNum")).isCloseTo(now, withPercentage(10.0));
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -21,10 +21,7 @@ public class JsonPropertyUnitTest {
public void whenSerializingUsingJsonProperty_thenCorrect() throws JsonProcessingException {
// arrange
Book book = new Book(
"Design Patterns: Elements of Reusable Object-oriented Software",
new Author("The", "GoF")
);
Book book = new Book("Design Patterns: Elements of Reusable Object-oriented Software", new Author("The", "GoF"));
book.configureBinding("Hardback");
// act
@ -62,12 +59,12 @@ public class JsonPropertyUnitTest {
String result = "{\"id\":\"cd941587-d1ae-4c2a-9a36-29533bf50411\",\"title\":\"Design Patterns: Elements of Reusable Object-oriented Software\",\"authors\":[{\"id\":\"c8e26318-2f5b-4fa2-9fdc-6e99be021fca\",\"firstName\":\"The\",\"lastName\":\"GoF\"}],\"binding\":\"Hardback\"}";
// act
Book book = new ObjectMapper().readerFor(Book.class).readValue(result);
Book book = new ObjectMapper().readerFor(Book.class)
.readValue(result);
// assert
assertThat(book.coverBinding()).isEqualTo("Hardback");
}
}

View File

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

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