Merge remote-tracking branch 'eugenp/master'
This commit is contained in:
commit
29d6807f80
|
@ -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);
|
||||
|
|
|
@ -27,9 +27,6 @@ public class DelayObject implements Delayed {
|
|||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "{" +
|
||||
"data='" + data + '\'' +
|
||||
", startTime=" + startTime +
|
||||
'}';
|
||||
return "{" + "data='" + data + '\'' + ", startTime=" + startTime + '}';
|
||||
}
|
||||
}
|
|
@ -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());
|
||||
}
|
||||
|
|
|
@ -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());
|
||||
}
|
||||
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
|
||||
|
|
|
@ -2,6 +2,8 @@ package com.baeldung.designpatterns.adapter;
|
|||
|
||||
public interface LuxuryCarsSpeedAdapter {
|
||||
public double bugattiVeyronInKMPH();
|
||||
|
||||
public double mcLarenInKMPH();
|
||||
|
||||
public double astonMartinInKMPH();
|
||||
}
|
||||
|
|
|
@ -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());
|
||||
|
||||
}
|
||||
|
|
|
@ -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());
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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) {
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -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));
|
||||
|
|
|
@ -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
|
||||
*
|
||||
|
|
|
@ -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());
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -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);
|
||||
|
||||
|
|
|
@ -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);
|
||||
|
|
|
@ -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")));
|
||||
}
|
||||
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
|
|
|
@ -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));
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
|
|
@ -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() {
|
||||
|
|
|
@ -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());
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
|
||||
|
|
|
@ -21,7 +21,7 @@ public class CharSequenceVsStringUnitTest {
|
|||
CharSequence charSequence1 = "baeldung_1";
|
||||
CharSequence charSequence2 = "baeldung_2";
|
||||
|
||||
assertTrue(charSequence1.toString().compareTo(charSequence2.toString()) > 0);
|
||||
assertTrue(charSequence1.toString().compareTo(charSequence2.toString()) < 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -31,7 +31,7 @@ public class CharSequenceVsStringUnitTest {
|
|||
test += "b";
|
||||
int secondAddressOfTest = System.identityHashCode(test);
|
||||
|
||||
assertEquals(firstAddressOfTest, secondAddressOfTest);
|
||||
assertNotEquals(firstAddressOfTest, secondAddressOfTest);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
|
|
|
@ -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");
|
||||
|
|
|
@ -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();
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
|
|
|
@ -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);
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
|
||||
|
|
|
@ -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);
|
||||
|
|
|
@ -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);
|
||||
|
|
|
@ -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();
|
||||
|
|
|
@ -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);
|
||||
|
|
|
@ -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);
|
||||
|
|
|
@ -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();
|
||||
|
|
|
@ -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();
|
||||
|
|
|
@ -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();
|
||||
}
|
||||
|
|
|
@ -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();
|
||||
|
|
|
@ -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);
|
||||
|
|
|
@ -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;
|
||||
|
|
|
@ -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;
|
||||
|
|
|
@ -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);
|
||||
|
|
|
@ -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();
|
||||
|
|
|
@ -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;
|
||||
|
|
|
@ -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();
|
||||
}
|
||||
}
|
|
@ -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);
|
||||
}
|
||||
|
|
|
@ -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());
|
||||
|
|
|
@ -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;
|
||||
|
|
|
@ -1,6 +1,5 @@
|
|||
package com.baeldung.jackson.serialization.jsonpropertyorder;
|
||||
|
||||
|
||||
import com.baeldung.jackson.domain.Item;
|
||||
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
|
||||
|
||||
|
|
|
@ -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);
|
||||
|
|
|
@ -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));
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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();
|
||||
|
|
|
@ -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);
|
||||
|
|
|
@ -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"));
|
||||
|
|
|
@ -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 {
|
||||
|
|
|
@ -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>();
|
||||
|
|
|
@ -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");
|
||||
|
||||
|
|
|
@ -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));
|
||||
|
|
|
@ -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));
|
||||
|
|
|
@ -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")));
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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);
|
||||
|
|
|
@ -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"));
|
||||
|
||||
}
|
||||
}
|
|
@ -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());
|
||||
|
|
|
@ -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");
|
||||
|
|
|
@ -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());
|
||||
|
||||
}
|
||||
}
|
|
@ -1,6 +1,5 @@
|
|||
package com.baeldung.jackson.dynamicIgnore;
|
||||
|
||||
|
||||
public class Address implements Hidable {
|
||||
private String city;
|
||||
private String country;
|
||||
|
|
|
@ -2,7 +2,6 @@ package com.baeldung.jackson.dynamicIgnore;
|
|||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
|
||||
|
||||
@JsonIgnoreProperties("hidden")
|
||||
public interface Hidable {
|
||||
boolean isHidden();
|
||||
|
|
|
@ -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;
|
||||
|
|
|
@ -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));
|
||||
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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();
|
||||
|
|
|
@ -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;
|
||||
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -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<>();
|
||||
|
|
|
@ -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);
|
||||
|
|
|
@ -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();
|
||||
|
|
|
@ -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();
|
||||
|
|
|
@ -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();
|
||||
|
|
|
@ -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");
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
|
@ -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;
|
||||
|
|
|
@ -22,7 +22,8 @@ public class JsonViewUnitTest {
|
|||
Order order = new Order(120);
|
||||
|
||||
// act
|
||||
String result = new ObjectMapper().writerWithView(Views.Internal.class).writeValueAsString(order);
|
||||
String result = new ObjectMapper().writerWithView(Views.Internal.class)
|
||||
.writeValueAsString(order);
|
||||
|
||||
// assert
|
||||
assertThat(from(result).getUUID("id")).isNotNull();
|
||||
|
@ -49,7 +50,8 @@ public class JsonViewUnitTest {
|
|||
Order order = new Order(120);
|
||||
|
||||
// act
|
||||
String result = new ObjectMapper().writerWithView(Views.Public.class).writeValueAsString(order);
|
||||
String result = new ObjectMapper().writerWithView(Views.Public.class)
|
||||
.writeValueAsString(order);
|
||||
|
||||
// assert
|
||||
assertThat(from(result).getUUID("id")).isNotNull();
|
||||
|
@ -68,5 +70,4 @@ public class JsonViewUnitTest {
|
|||
|
||||
}
|
||||
|
||||
|
||||
}
|
|
@ -1,6 +1,5 @@
|
|||
package com.baeldung.jackson.general.reference;
|
||||
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
|
@ -11,7 +10,9 @@ import java.util.List;
|
|||
*/
|
||||
public class Course extends Item {
|
||||
|
||||
public enum Medium {CLASSROOM, ONLINE}
|
||||
public enum Medium {
|
||||
CLASSROOM, ONLINE
|
||||
}
|
||||
|
||||
public enum Level {
|
||||
BEGINNER("Beginner", 1), INTERMEDIATE("Intermediate", 2), ADVANCED("Advanced", 3);
|
||||
|
|
|
@ -21,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();
|
||||
|
|
|
@ -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();
|
||||
|
|
|
@ -28,7 +28,6 @@ public class JsonIncludeUnitTest {
|
|||
assertThat(from(result).getString("firstName")).isEqualTo("Alex");
|
||||
assertThat(result).doesNotContain("lastName");
|
||||
|
||||
|
||||
/*
|
||||
{
|
||||
"id": "e8bb4802-6e0c-4fa5-9f68-c233272399cd",
|
||||
|
|
|
@ -30,8 +30,10 @@ public class TypeInfoInclusionUnitTest {
|
|||
String jsonDataString = mapper.writeValueAsString(serializedFleet);
|
||||
TypeInfoStructure.Fleet deserializedFleet = mapper.readValue(jsonDataString, TypeInfoStructure.Fleet.class);
|
||||
|
||||
assertThat(deserializedFleet.getVehicles().get(0), instanceOf(TypeInfoStructure.Car.class));
|
||||
assertThat(deserializedFleet.getVehicles().get(1), instanceOf(TypeInfoStructure.Truck.class));
|
||||
assertThat(deserializedFleet.getVehicles()
|
||||
.get(0), instanceOf(TypeInfoStructure.Car.class));
|
||||
assertThat(deserializedFleet.getVehicles()
|
||||
.get(1), instanceOf(TypeInfoStructure.Truck.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -51,7 +53,9 @@ public class TypeInfoInclusionUnitTest {
|
|||
String jsonDataString = mapper.writeValueAsString(serializedFleet);
|
||||
TypeInfoAnnotatedStructure.Fleet deserializedFleet = mapper.readValue(jsonDataString, TypeInfoAnnotatedStructure.Fleet.class);
|
||||
|
||||
assertThat(deserializedFleet.getVehicles().get(0), instanceOf(TypeInfoAnnotatedStructure.Car.class));
|
||||
assertThat(deserializedFleet.getVehicles().get(1), instanceOf(TypeInfoAnnotatedStructure.Truck.class));
|
||||
assertThat(deserializedFleet.getVehicles()
|
||||
.get(0), instanceOf(TypeInfoAnnotatedStructure.Car.class));
|
||||
assertThat(deserializedFleet.getVehicles()
|
||||
.get(1), instanceOf(TypeInfoAnnotatedStructure.Truck.class));
|
||||
}
|
||||
}
|
|
@ -10,7 +10,8 @@ public class ExampleStructure {
|
|||
private static ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
static JsonNode getExampleRoot() throws IOException {
|
||||
InputStream exampleInput = ExampleStructure.class.getClassLoader().getResourceAsStream("node_example.json");
|
||||
InputStream exampleInput = ExampleStructure.class.getClassLoader()
|
||||
.getResourceAsStream("node_example.json");
|
||||
JsonNode rootNode = mapper.readTree(exampleInput);
|
||||
return rootNode;
|
||||
}
|
||||
|
|
|
@ -28,8 +28,10 @@ public class NodeOperationUnitTest {
|
|||
|
||||
final JsonNode node = mapper.valueToTree(fromValue);
|
||||
|
||||
assertEquals(2016, node.get("id").intValue());
|
||||
assertEquals("baeldung.com", node.get("name").textValue());
|
||||
assertEquals(2016, node.get("id")
|
||||
.intValue());
|
||||
assertEquals("baeldung.com", node.get("name")
|
||||
.textValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -72,12 +74,21 @@ public class NodeOperationUnitTest {
|
|||
public void givenANode_whenAddingIntoATree_thenCorrect() throws IOException {
|
||||
final JsonNode rootNode = ExampleStructure.getExampleRoot();
|
||||
final ObjectNode addedNode = ((ObjectNode) rootNode).putObject("address");
|
||||
addedNode.put("city", "Seattle").put("state", "Washington").put("country", "United States");
|
||||
addedNode.put("city", "Seattle")
|
||||
.put("state", "Washington")
|
||||
.put("country", "United States");
|
||||
|
||||
assertFalse(rootNode.path("address").isMissingNode());
|
||||
assertEquals("Seattle", rootNode.path("address").path("city").textValue());
|
||||
assertEquals("Washington", rootNode.path("address").path("state").textValue());
|
||||
assertEquals("United States", rootNode.path("address").path("country").textValue());
|
||||
assertFalse(rootNode.path("address")
|
||||
.isMissingNode());
|
||||
assertEquals("Seattle", rootNode.path("address")
|
||||
.path("city")
|
||||
.textValue());
|
||||
assertEquals("Washington", rootNode.path("address")
|
||||
.path("state")
|
||||
.textValue());
|
||||
assertEquals("United States", rootNode.path("address")
|
||||
.path("country")
|
||||
.textValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -88,8 +99,12 @@ public class NodeOperationUnitTest {
|
|||
final JsonNode rootNode = ExampleStructure.getExampleRoot();
|
||||
((ObjectNode) rootNode).set("name", newNode);
|
||||
|
||||
assertFalse(rootNode.path("name").path("nick").isMissingNode());
|
||||
assertEquals("cowtowncoder", rootNode.path("name").path("nick").textValue());
|
||||
assertFalse(rootNode.path("name")
|
||||
.path("nick")
|
||||
.isMissingNode());
|
||||
assertEquals("cowtowncoder", rootNode.path("name")
|
||||
.path("nick")
|
||||
.textValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -97,7 +112,8 @@ public class NodeOperationUnitTest {
|
|||
final JsonNode rootNode = ExampleStructure.getExampleRoot();
|
||||
((ObjectNode) rootNode).remove("company");
|
||||
|
||||
assertTrue(rootNode.path("company").isMissingNode());
|
||||
assertTrue(rootNode.path("company")
|
||||
.isMissingNode());
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -25,8 +25,6 @@ public class CustomCarDeserializer extends StdDeserializer<Car> {
|
|||
super(vc);
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Override
|
||||
public Car deserialize(final JsonParser parser, final DeserializationContext deserializer) throws IOException {
|
||||
final Car car = new Car();
|
||||
|
|
|
@ -8,8 +8,7 @@ import com.fasterxml.jackson.core.JsonProcessingException;
|
|||
import com.fasterxml.jackson.databind.SerializerProvider;
|
||||
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
|
||||
|
||||
public class CustomCarSerializer extends StdSerializer<Car>
|
||||
{
|
||||
public class CustomCarSerializer extends StdSerializer<Car> {
|
||||
|
||||
private static final long serialVersionUID = 1396140685442227917L;
|
||||
|
||||
|
@ -22,8 +21,7 @@ public class CustomCarSerializer extends StdSerializer<Car>
|
|||
}
|
||||
|
||||
@Override
|
||||
public void serialize(final Car car, final JsonGenerator jsonGenerator, final SerializerProvider serializer) throws IOException, JsonProcessingException
|
||||
{
|
||||
public void serialize(final Car car, final JsonGenerator jsonGenerator, final SerializerProvider serializer) throws IOException, JsonProcessingException {
|
||||
jsonGenerator.writeStartObject();
|
||||
jsonGenerator.writeStringField("model: ", car.getType());
|
||||
jsonGenerator.writeEndObject();
|
||||
|
|
|
@ -40,7 +40,8 @@ public class JavaReadWriteJsonExampleUnitTest {
|
|||
final ObjectMapper objectMapper = new ObjectMapper();
|
||||
final JsonNode jsonNode = objectMapper.readTree(EXAMPLE_JSON);
|
||||
assertNotNull(jsonNode);
|
||||
assertThat(jsonNode.get("color").asText(), containsString("Black"));
|
||||
assertThat(jsonNode.get("color")
|
||||
.asText(), containsString("Black"));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
|
|
@ -53,12 +53,14 @@ public class PolymorphismUnitTest {
|
|||
String orderJson = "{\"type\":{\"ordertype\":\"internal\",\"id\":100,\"name\":\"directors\"}}";
|
||||
|
||||
// act
|
||||
Order order = new ObjectMapper().readerFor(Order.class).readValue(orderJson);
|
||||
Order order = new ObjectMapper().readerFor(Order.class)
|
||||
.readValue(orderJson);
|
||||
|
||||
// assert
|
||||
assertThat(from(orderJson).getString("type.ordertype")).isEqualTo("internal");
|
||||
assertThat(((Order.InternalType) order.getType()).name).isEqualTo("directors");
|
||||
assertThat(((Order.InternalType) order.getType()).id).isEqualTo(100);
|
||||
assertThat(order.getType().getClass()).isEqualTo(Order.InternalType.class);
|
||||
assertThat(order.getType()
|
||||
.getClass()).isEqualTo(Order.InternalType.class);
|
||||
}
|
||||
}
|
|
@ -33,7 +33,8 @@ public class JacksonPrettyPrintUnitTest {
|
|||
final ObjectMapper mapper = new ObjectMapper();
|
||||
try {
|
||||
final Object json = mapper.readValue(readFile(fileName, StandardCharsets.UTF_8), Object.class);
|
||||
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json));
|
||||
System.out.println(mapper.writerWithDefaultPrettyPrinter()
|
||||
.writeValueAsString(json));
|
||||
} catch (final IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
@ -42,7 +43,8 @@ public class JacksonPrettyPrintUnitTest {
|
|||
|
||||
static String readFile(final String path, final Charset encoding) throws IOException {
|
||||
final byte[] encoded = Files.readAllBytes(Paths.get(path));
|
||||
return encoding.decode(ByteBuffer.wrap(encoded)).toString();
|
||||
return encoding.decode(ByteBuffer.wrap(encoded))
|
||||
.toString();
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -17,7 +17,10 @@ public class SandboxUnitTest {
|
|||
testElement.setX(10);
|
||||
testElement.setY("adasd");
|
||||
final ObjectMapper om = new ObjectMapper();
|
||||
om.setVisibility(om.getSerializationConfig().getDefaultVisibilityChecker().withFieldVisibility(JsonAutoDetect.Visibility.ANY).withGetterVisibility(JsonAutoDetect.Visibility.NONE));
|
||||
om.setVisibility(om.getSerializationConfig()
|
||||
.getDefaultVisibilityChecker()
|
||||
.withFieldVisibility(JsonAutoDetect.Visibility.ANY)
|
||||
.withGetterVisibility(JsonAutoDetect.Visibility.NONE));
|
||||
|
||||
final String serialized = om.writeValueAsString(testElement);
|
||||
System.err.println(serialized);
|
||||
|
|
|
@ -29,8 +29,7 @@ public class JacksonMapSerializeUnitTest {
|
|||
final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
@Test
|
||||
public void whenSimpleMapSerialize_thenCorrect()
|
||||
throws JsonProcessingException {
|
||||
public void whenSimpleMapSerialize_thenCorrect() throws JsonProcessingException {
|
||||
|
||||
Map<String, String> map = new HashMap<>();
|
||||
map.put("key", "value");
|
||||
|
@ -41,8 +40,7 @@ public class JacksonMapSerializeUnitTest {
|
|||
}
|
||||
|
||||
@Test
|
||||
public void whenCustomObjectStringMapSerialize_thenCorrect()
|
||||
throws JsonProcessingException {
|
||||
public void whenCustomObjectStringMapSerialize_thenCorrect() throws JsonProcessingException {
|
||||
|
||||
map = new HashMap<>();
|
||||
MyPair key = new MyPair("Abbott", "Costello");
|
||||
|
@ -54,8 +52,7 @@ public class JacksonMapSerializeUnitTest {
|
|||
}
|
||||
|
||||
@Test
|
||||
public void whenCustomObjectObjectMapSerialize_thenCorrect()
|
||||
throws JsonProcessingException {
|
||||
public void whenCustomObjectObjectMapSerialize_thenCorrect() throws JsonProcessingException {
|
||||
|
||||
cmap = new HashMap<>();
|
||||
mapKey = new MyPair("Abbott", "Costello");
|
||||
|
@ -64,7 +61,6 @@ public class JacksonMapSerializeUnitTest {
|
|||
|
||||
final String jsonResult = mapper.writeValueAsString(cmap);
|
||||
|
||||
Assert.assertEquals("{\"Abbott and Costello\":\"Comedy and 1940's\"}",
|
||||
jsonResult);
|
||||
Assert.assertEquals("{\"Abbott and Costello\":\"Comedy and 1940's\"}", jsonResult);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -48,10 +48,13 @@ public class JacksonSerializeUnitTest {
|
|||
module.addSerializer(new ActorJacksonSerializer(ActorJackson.class));
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
final String jsonResult = mapper.registerModule(module).writer(new DefaultPrettyPrinter()).writeValueAsString(movieWithNullValue);
|
||||
final String jsonResult = mapper.registerModule(module)
|
||||
.writer(new DefaultPrettyPrinter())
|
||||
.writeValueAsString(movieWithNullValue);
|
||||
|
||||
final Object json = mapper.readValue("{\"actors\":[{\"imdbId\":\"nm2199632\",\"dateOfBirth\":\"21-09-1982\",\"N° Film: \":3,\"filmography\":\"Apocalypto-Beatdown-Wind Walkers\"}],\"imdbID\":null}", Object.class);
|
||||
final String expectedOutput = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT).writeValueAsString(json);
|
||||
final String expectedOutput = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT)
|
||||
.writeValueAsString(json);
|
||||
|
||||
Assert.assertEquals(jsonResult, expectedOutput);
|
||||
}
|
||||
|
|
|
@ -28,7 +28,6 @@ public class JsonRawValueUnitTest {
|
|||
// assert
|
||||
assertThat(result.contains(customerConfig));
|
||||
|
||||
|
||||
/*
|
||||
{
|
||||
"firstName": "Alex",
|
||||
|
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue