Merge remote-tracking branch 'eugenp/master'
This commit is contained in:
commit
29d6807f80
|
@ -19,13 +19,15 @@ public class NumbersProducer implements Runnable {
|
||||||
try {
|
try {
|
||||||
generateNumbers();
|
generateNumbers();
|
||||||
} catch (InterruptedException e) {
|
} catch (InterruptedException e) {
|
||||||
Thread.currentThread().interrupt();
|
Thread.currentThread()
|
||||||
|
.interrupt();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void generateNumbers() throws InterruptedException {
|
private void generateNumbers() throws InterruptedException {
|
||||||
for (int i = 0; i < 100; i++) {
|
for (int i = 0; i < 100; i++) {
|
||||||
numbersQueue.put(ThreadLocalRandom.current().nextInt(100));
|
numbersQueue.put(ThreadLocalRandom.current()
|
||||||
|
.nextInt(100));
|
||||||
}
|
}
|
||||||
for (int j = 0; j < poisonPillPerProducer; j++) {
|
for (int j = 0; j < poisonPillPerProducer; j++) {
|
||||||
numbersQueue.put(poisonPill);
|
numbersQueue.put(poisonPill);
|
||||||
|
|
|
@ -27,9 +27,6 @@ public class DelayObject implements Delayed {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
return "{" +
|
return "{" + "data='" + data + '\'' + ", startTime=" + startTime + '}';
|
||||||
"data='" + data + '\'' +
|
|
||||||
", startTime=" + startTime +
|
|
||||||
'}';
|
|
||||||
}
|
}
|
||||||
}
|
}
|
|
@ -15,7 +15,6 @@ public class CompletableFutureLongRunningUnitTest {
|
||||||
|
|
||||||
private static final Logger LOG = LoggerFactory.getLogger(CompletableFutureLongRunningUnitTest.class);
|
private static final Logger LOG = LoggerFactory.getLogger(CompletableFutureLongRunningUnitTest.class);
|
||||||
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenRunningCompletableFutureAsynchronously_thenGetMethodWaitsForResult() throws InterruptedException, ExecutionException {
|
public void whenRunningCompletableFutureAsynchronously_thenGetMethodWaitsForResult() throws InterruptedException, ExecutionException {
|
||||||
Future<String> completableFuture = calculateAsync();
|
Future<String> completableFuture = calculateAsync();
|
||||||
|
@ -27,11 +26,12 @@ public class CompletableFutureLongRunningUnitTest {
|
||||||
private Future<String> calculateAsync() throws InterruptedException {
|
private Future<String> calculateAsync() throws InterruptedException {
|
||||||
CompletableFuture<String> completableFuture = new CompletableFuture<>();
|
CompletableFuture<String> completableFuture = new CompletableFuture<>();
|
||||||
|
|
||||||
Executors.newCachedThreadPool().submit(() -> {
|
Executors.newCachedThreadPool()
|
||||||
Thread.sleep(500);
|
.submit(() -> {
|
||||||
completableFuture.complete("Hello");
|
Thread.sleep(500);
|
||||||
return null;
|
completableFuture.complete("Hello");
|
||||||
});
|
return null;
|
||||||
|
});
|
||||||
|
|
||||||
return completableFuture;
|
return completableFuture;
|
||||||
}
|
}
|
||||||
|
@ -47,11 +47,12 @@ public class CompletableFutureLongRunningUnitTest {
|
||||||
private Future<String> calculateAsyncWithCancellation() throws InterruptedException {
|
private Future<String> calculateAsyncWithCancellation() throws InterruptedException {
|
||||||
CompletableFuture<String> completableFuture = new CompletableFuture<>();
|
CompletableFuture<String> completableFuture = new CompletableFuture<>();
|
||||||
|
|
||||||
Executors.newCachedThreadPool().submit(() -> {
|
Executors.newCachedThreadPool()
|
||||||
Thread.sleep(500);
|
.submit(() -> {
|
||||||
completableFuture.cancel(false);
|
Thread.sleep(500);
|
||||||
return null;
|
completableFuture.cancel(false);
|
||||||
});
|
return null;
|
||||||
|
});
|
||||||
|
|
||||||
return completableFuture;
|
return completableFuture;
|
||||||
}
|
}
|
||||||
|
@ -98,21 +99,24 @@ public class CompletableFutureLongRunningUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenUsingThenCompose_thenFuturesExecuteSequentially() throws ExecutionException, InterruptedException {
|
public void whenUsingThenCompose_thenFuturesExecuteSequentially() throws ExecutionException, InterruptedException {
|
||||||
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> "Hello").thenCompose(s -> CompletableFuture.supplyAsync(() -> s + " World"));
|
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> "Hello")
|
||||||
|
.thenCompose(s -> CompletableFuture.supplyAsync(() -> s + " World"));
|
||||||
|
|
||||||
assertEquals("Hello World", completableFuture.get());
|
assertEquals("Hello World", completableFuture.get());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenUsingThenCombine_thenWaitForExecutionOfBothFutures() throws ExecutionException, InterruptedException {
|
public void whenUsingThenCombine_thenWaitForExecutionOfBothFutures() throws ExecutionException, InterruptedException {
|
||||||
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> "Hello").thenCombine(CompletableFuture.supplyAsync(() -> " World"), (s1, s2) -> s1 + s2);
|
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> "Hello")
|
||||||
|
.thenCombine(CompletableFuture.supplyAsync(() -> " World"), (s1, s2) -> s1 + s2);
|
||||||
|
|
||||||
assertEquals("Hello World", completableFuture.get());
|
assertEquals("Hello World", completableFuture.get());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenUsingThenAcceptBoth_thenWaitForExecutionOfBothFutures() throws ExecutionException, InterruptedException {
|
public void whenUsingThenAcceptBoth_thenWaitForExecutionOfBothFutures() throws ExecutionException, InterruptedException {
|
||||||
CompletableFuture.supplyAsync(() -> "Hello").thenAcceptBoth(CompletableFuture.supplyAsync(() -> " World"), (s1, s2) -> LOG.debug(s1 + s2));
|
CompletableFuture.supplyAsync(() -> "Hello")
|
||||||
|
.thenAcceptBoth(CompletableFuture.supplyAsync(() -> " World"), (s1, s2) -> LOG.debug(s1 + s2));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -131,7 +135,9 @@ public class CompletableFutureLongRunningUnitTest {
|
||||||
assertTrue(future2.isDone());
|
assertTrue(future2.isDone());
|
||||||
assertTrue(future3.isDone());
|
assertTrue(future3.isDone());
|
||||||
|
|
||||||
String combined = Stream.of(future1, future2, future3).map(CompletableFuture::join).collect(Collectors.joining(" "));
|
String combined = Stream.of(future1, future2, future3)
|
||||||
|
.map(CompletableFuture::join)
|
||||||
|
.collect(Collectors.joining(" "));
|
||||||
|
|
||||||
assertEquals("Hello Beautiful World", combined);
|
assertEquals("Hello Beautiful World", combined);
|
||||||
}
|
}
|
||||||
|
@ -147,7 +153,8 @@ public class CompletableFutureLongRunningUnitTest {
|
||||||
throw new RuntimeException("Computation error!");
|
throw new RuntimeException("Computation error!");
|
||||||
}
|
}
|
||||||
return "Hello, " + name;
|
return "Hello, " + name;
|
||||||
}).handle((s, t) -> s != null ? s : "Hello, Stranger!");
|
})
|
||||||
|
.handle((s, t) -> s != null ? s : "Hello, Stranger!");
|
||||||
|
|
||||||
assertEquals("Hello, Stranger!", completableFuture.get());
|
assertEquals("Hello, Stranger!", completableFuture.get());
|
||||||
}
|
}
|
||||||
|
|
|
@ -47,7 +47,8 @@ public class ConcurrentMapAggregateStatusManualTest {
|
||||||
executorService.awaitTermination(1, TimeUnit.MINUTES);
|
executorService.awaitTermination(1, TimeUnit.MINUTES);
|
||||||
|
|
||||||
for (int i = 1; i <= MAX_SIZE; i++) {
|
for (int i = 1; i <= MAX_SIZE; i++) {
|
||||||
assertEquals("map size should be consistently reliable", i, mapSizes.get(i - 1).intValue());
|
assertEquals("map size should be consistently reliable", i, mapSizes.get(i - 1)
|
||||||
|
.intValue());
|
||||||
}
|
}
|
||||||
assertEquals(MAX_SIZE, concurrentMap.size());
|
assertEquals(MAX_SIZE, concurrentMap.size());
|
||||||
}
|
}
|
||||||
|
@ -69,7 +70,8 @@ public class ConcurrentMapAggregateStatusManualTest {
|
||||||
executorService.shutdown();
|
executorService.shutdown();
|
||||||
executorService.awaitTermination(1, TimeUnit.MINUTES);
|
executorService.awaitTermination(1, TimeUnit.MINUTES);
|
||||||
|
|
||||||
assertNotEquals("map size collected with concurrent updates not reliable", MAX_SIZE, mapSizes.get(MAX_SIZE - 1).intValue());
|
assertNotEquals("map size collected with concurrent updates not reliable", MAX_SIZE, mapSizes.get(MAX_SIZE - 1)
|
||||||
|
.intValue());
|
||||||
assertEquals(MAX_SIZE, concurrentMap.size());
|
assertEquals(MAX_SIZE, concurrentMap.size());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -16,8 +16,12 @@ public class ConcurretMapMemoryConsistencyManualTest {
|
||||||
public void givenConcurrentMap_whenSumParallel_thenCorrect() throws Exception {
|
public void givenConcurrentMap_whenSumParallel_thenCorrect() throws Exception {
|
||||||
Map<String, Integer> map = new ConcurrentHashMap<>();
|
Map<String, Integer> map = new ConcurrentHashMap<>();
|
||||||
List<Integer> sumList = parallelSum100(map, 1000);
|
List<Integer> sumList = parallelSum100(map, 1000);
|
||||||
assertEquals(1, sumList.stream().distinct().count());
|
assertEquals(1, sumList.stream()
|
||||||
long wrongResultCount = sumList.stream().filter(num -> num != 100).count();
|
.distinct()
|
||||||
|
.count());
|
||||||
|
long wrongResultCount = sumList.stream()
|
||||||
|
.filter(num -> num != 100)
|
||||||
|
.count();
|
||||||
assertEquals(0, wrongResultCount);
|
assertEquals(0, wrongResultCount);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -25,8 +29,12 @@ public class ConcurretMapMemoryConsistencyManualTest {
|
||||||
public void givenHashtable_whenSumParallel_thenCorrect() throws Exception {
|
public void givenHashtable_whenSumParallel_thenCorrect() throws Exception {
|
||||||
Map<String, Integer> map = new Hashtable<>();
|
Map<String, Integer> map = new Hashtable<>();
|
||||||
List<Integer> sumList = parallelSum100(map, 1000);
|
List<Integer> sumList = parallelSum100(map, 1000);
|
||||||
assertEquals(1, sumList.stream().distinct().count());
|
assertEquals(1, sumList.stream()
|
||||||
long wrongResultCount = sumList.stream().filter(num -> num != 100).count();
|
.distinct()
|
||||||
|
.count());
|
||||||
|
long wrongResultCount = sumList.stream()
|
||||||
|
.filter(num -> num != 100)
|
||||||
|
.count();
|
||||||
assertEquals(0, wrongResultCount);
|
assertEquals(0, wrongResultCount);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -34,8 +42,12 @@ public class ConcurretMapMemoryConsistencyManualTest {
|
||||||
public void givenHashMap_whenSumParallel_thenError() throws Exception {
|
public void givenHashMap_whenSumParallel_thenError() throws Exception {
|
||||||
Map<String, Integer> map = new HashMap<>();
|
Map<String, Integer> map = new HashMap<>();
|
||||||
List<Integer> sumList = parallelSum100(map, 100);
|
List<Integer> sumList = parallelSum100(map, 100);
|
||||||
assertNotEquals(1, sumList.stream().distinct().count());
|
assertNotEquals(1, sumList.stream()
|
||||||
long wrongResultCount = sumList.stream().filter(num -> num != 100).count();
|
.distinct()
|
||||||
|
.count());
|
||||||
|
long wrongResultCount = sumList.stream()
|
||||||
|
.filter(num -> num != 100)
|
||||||
|
.count();
|
||||||
assertTrue(wrongResultCount > 0);
|
assertTrue(wrongResultCount > 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -2,6 +2,8 @@ package com.baeldung.designpatterns.adapter;
|
||||||
|
|
||||||
public interface LuxuryCarsSpeedAdapter {
|
public interface LuxuryCarsSpeedAdapter {
|
||||||
public double bugattiVeyronInKMPH();
|
public double bugattiVeyronInKMPH();
|
||||||
|
|
||||||
public double mcLarenInKMPH();
|
public double mcLarenInKMPH();
|
||||||
|
|
||||||
public double astonMartinInKMPH();
|
public double astonMartinInKMPH();
|
||||||
}
|
}
|
||||||
|
|
|
@ -5,14 +5,12 @@ import static com.baeldung.designpatterns.util.LogerUtil.LOG;
|
||||||
public class DecoratorPatternDriver {
|
public class DecoratorPatternDriver {
|
||||||
|
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
//christmas tree with just one Garland
|
// christmas tree with just one Garland
|
||||||
ChristmasTree tree1 = new Garland(new ChristmasTreeImpl());
|
ChristmasTree tree1 = new Garland(new ChristmasTreeImpl());
|
||||||
LOG.info(tree1.decorate());
|
LOG.info(tree1.decorate());
|
||||||
|
|
||||||
//christmas tree with two Garlands and one Bubble lights
|
// christmas tree with two Garlands and one Bubble lights
|
||||||
ChristmasTree tree2 = new BubbleLights(new Garland(
|
ChristmasTree tree2 = new BubbleLights(new Garland(new Garland(new ChristmasTreeImpl())));
|
||||||
new Garland(new ChristmasTreeImpl()))
|
|
||||||
);
|
|
||||||
LOG.info(tree2.decorate());
|
LOG.info(tree2.decorate());
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -43,6 +43,7 @@ public class CustomRecursiveAction extends RecursiveAction {
|
||||||
|
|
||||||
private void processing(String work) {
|
private void processing(String work) {
|
||||||
String result = work.toUpperCase();
|
String result = work.toUpperCase();
|
||||||
logger.info("This result - (" + result + ") - was processed by " + Thread.currentThread().getName());
|
logger.info("This result - (" + result + ") - was processed by " + Thread.currentThread()
|
||||||
|
.getName());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -44,7 +44,8 @@ public class MapIteration {
|
||||||
}
|
}
|
||||||
|
|
||||||
public void iterateUsingIteratorAndEntry(Map<String, Integer> map) {
|
public void iterateUsingIteratorAndEntry(Map<String, Integer> map) {
|
||||||
Iterator<Map.Entry<String, Integer>> iterator = map.entrySet().iterator();
|
Iterator<Map.Entry<String, Integer>> iterator = map.entrySet()
|
||||||
|
.iterator();
|
||||||
while (iterator.hasNext()) {
|
while (iterator.hasNext()) {
|
||||||
Map.Entry<String, Integer> pair = iterator.next();
|
Map.Entry<String, Integer> pair = iterator.next();
|
||||||
System.out.println(pair.getKey() + ":" + pair.getValue());
|
System.out.println(pair.getKey() + ":" + pair.getValue());
|
||||||
|
@ -58,7 +59,9 @@ public class MapIteration {
|
||||||
}
|
}
|
||||||
|
|
||||||
public void iterateUsingStreamAPI(Map<String, Integer> map) {
|
public void iterateUsingStreamAPI(Map<String, Integer> map) {
|
||||||
map.entrySet().stream().forEach(e -> System.out.println(e.getKey() + ":" + e.getValue()));
|
map.entrySet()
|
||||||
|
.stream()
|
||||||
|
.forEach(e -> System.out.println(e.getKey() + ":" + e.getValue()));
|
||||||
}
|
}
|
||||||
|
|
||||||
public void iterateKeys(Map<String, Integer> map) {
|
public void iterateKeys(Map<String, Integer> map) {
|
||||||
|
|
|
@ -9,7 +9,8 @@ public class PersistentCookieStore implements CookieStore, Runnable {
|
||||||
public PersistentCookieStore() {
|
public PersistentCookieStore() {
|
||||||
store = new CookieManager().getCookieStore();
|
store = new CookieManager().getCookieStore();
|
||||||
// deserialize cookies into store
|
// deserialize cookies into store
|
||||||
Runtime.getRuntime().addShutdownHook(new Thread(this));
|
Runtime.getRuntime()
|
||||||
|
.addShutdownHook(new Thread(this));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
|
|
@ -14,7 +14,8 @@ public class Screenshot {
|
||||||
}
|
}
|
||||||
|
|
||||||
public void getScreenshot(int timeToWait) throws Exception {
|
public void getScreenshot(int timeToWait) throws Exception {
|
||||||
Rectangle rectangle = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
|
Rectangle rectangle = new Rectangle(Toolkit.getDefaultToolkit()
|
||||||
|
.getScreenSize());
|
||||||
Robot robot = new Robot();
|
Robot robot = new Robot();
|
||||||
BufferedImage img = robot.createScreenCapture(rectangle);
|
BufferedImage img = robot.createScreenCapture(rectangle);
|
||||||
ImageIO.write(img, "jpg", new File(path));
|
ImageIO.write(img, "jpg", new File(path));
|
||||||
|
|
|
@ -10,12 +10,12 @@ public class UUIDGenerator {
|
||||||
/**
|
/**
|
||||||
* These are predefined UUID for name spaces
|
* These are predefined UUID for name spaces
|
||||||
*/
|
*/
|
||||||
private static final String NAMESPACE_DNS = "6ba7b810-9dad-11d1-80b4-00c04fd430c8";
|
private static final String NAMESPACE_DNS = "6ba7b810-9dad-11d1-80b4-00c04fd430c8";
|
||||||
private static final String NAMESPACE_URL = "6ba7b811-9dad-11d1-80b4-00c04fd430c8";
|
private static final String NAMESPACE_URL = "6ba7b811-9dad-11d1-80b4-00c04fd430c8";
|
||||||
private static final String NAMESPACE_OID = "6ba7b812-9dad-11d1-80b4-00c04fd430c8";
|
private static final String NAMESPACE_OID = "6ba7b812-9dad-11d1-80b4-00c04fd430c8";
|
||||||
private static final String NAMESPACE_X500 = "6ba7b814-9dad-11d1-80b4-00c04fd430c8";
|
private static final String NAMESPACE_X500 = "6ba7b814-9dad-11d1-80b4-00c04fd430c8";
|
||||||
|
|
||||||
private static final char[] hexArray = "0123456789ABCDEF".toCharArray();
|
private static final char[] hexArray = "0123456789ABCDEF".toCharArray();
|
||||||
|
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
try {
|
try {
|
||||||
|
@ -60,7 +60,6 @@ public class UUIDGenerator {
|
||||||
return uuid;
|
return uuid;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
public static UUID type5UUIDFromBytes(byte[] name) {
|
public static UUID type5UUIDFromBytes(byte[] name) {
|
||||||
MessageDigest md;
|
MessageDigest md;
|
||||||
try {
|
try {
|
||||||
|
@ -69,10 +68,10 @@ public class UUIDGenerator {
|
||||||
throw new InternalError("MD5 not supported", nsae);
|
throw new InternalError("MD5 not supported", nsae);
|
||||||
}
|
}
|
||||||
byte[] bytes = md.digest(name);
|
byte[] bytes = md.digest(name);
|
||||||
bytes[6] &= 0x0f; /* clear version */
|
bytes[6] &= 0x0f; /* clear version */
|
||||||
bytes[6] |= 0x50; /* set to version 5 */
|
bytes[6] |= 0x50; /* set to version 5 */
|
||||||
bytes[8] &= 0x3f; /* clear variant */
|
bytes[8] &= 0x3f; /* clear variant */
|
||||||
bytes[8] |= 0x80; /* set to IETF variant */
|
bytes[8] |= 0x80; /* set to IETF variant */
|
||||||
return constructType5UUID(bytes);
|
return constructType5UUID(bytes);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -81,15 +80,14 @@ public class UUIDGenerator {
|
||||||
long lsb = 0;
|
long lsb = 0;
|
||||||
assert data.length == 16 : "data must be 16 bytes in length";
|
assert data.length == 16 : "data must be 16 bytes in length";
|
||||||
|
|
||||||
for (int i=0; i<8; i++)
|
for (int i = 0; i < 8; i++)
|
||||||
msb = (msb << 8) | (data[i] & 0xff);
|
msb = (msb << 8) | (data[i] & 0xff);
|
||||||
|
|
||||||
for (int i=8; i<16; i++)
|
for (int i = 8; i < 16; i++)
|
||||||
lsb = (lsb << 8) | (data[i] & 0xff);
|
lsb = (lsb << 8) | (data[i] & 0xff);
|
||||||
return new UUID(msb, lsb);
|
return new UUID(msb, lsb);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Unique Keys Generation Using Message Digest and Type 4 UUID
|
* Unique Keys Generation Using Message Digest and Type 4 UUID
|
||||||
*
|
*
|
||||||
|
|
|
@ -15,7 +15,9 @@ public class UseLocalDateTimeUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenString_whenUsingParse_thenLocalDateTime() {
|
public void givenString_whenUsingParse_thenLocalDateTime() {
|
||||||
assertEquals(LocalDate.of(2016, Month.MAY, 10), useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30").toLocalDate());
|
assertEquals(LocalDate.of(2016, Month.MAY, 10), useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30")
|
||||||
assertEquals(LocalTime.of(6, 30), useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30").toLocalTime());
|
.toLocalDate());
|
||||||
|
assertEquals(LocalTime.of(6, 30), useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30")
|
||||||
|
.toLocalTime());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -15,12 +15,14 @@ public class UseLocalDateUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenValues_whenUsingFactoryOf_thenLocalDate() {
|
public void givenValues_whenUsingFactoryOf_thenLocalDate() {
|
||||||
assertEquals("2016-05-10", useLocalDate.getLocalDateUsingFactoryOfMethod(2016, 5, 10).toString());
|
assertEquals("2016-05-10", useLocalDate.getLocalDateUsingFactoryOfMethod(2016, 5, 10)
|
||||||
|
.toString());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenString_whenUsingParse_thenLocalDate() {
|
public void givenString_whenUsingParse_thenLocalDate() {
|
||||||
assertEquals("2016-05-10", useLocalDate.getLocalDateUsingParseMethod("2016-05-10").toString());
|
assertEquals("2016-05-10", useLocalDate.getLocalDateUsingParseMethod("2016-05-10")
|
||||||
|
.toString());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -30,12 +32,14 @@ public class UseLocalDateUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenDate_whenUsingPlus_thenNextDay() {
|
public void givenDate_whenUsingPlus_thenNextDay() {
|
||||||
assertEquals(LocalDate.now().plusDays(1), useLocalDate.getNextDay(LocalDate.now()));
|
assertEquals(LocalDate.now()
|
||||||
|
.plusDays(1), useLocalDate.getNextDay(LocalDate.now()));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenDate_whenUsingMinus_thenPreviousDay() {
|
public void givenDate_whenUsingMinus_thenPreviousDay() {
|
||||||
assertEquals(LocalDate.now().minusDays(1), useLocalDate.getPreviousDay(LocalDate.now()));
|
assertEquals(LocalDate.now()
|
||||||
|
.minusDays(1), useLocalDate.getPreviousDay(LocalDate.now()));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -45,7 +49,8 @@ public class UseLocalDateUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenToday_whenUsingWithTemporalAdjuster_thenFirstDayOfMonth() {
|
public void givenToday_whenUsingWithTemporalAdjuster_thenFirstDayOfMonth() {
|
||||||
assertEquals(1, useLocalDate.getFirstDayOfMonth().getDayOfMonth());
|
assertEquals(1, useLocalDate.getFirstDayOfMonth()
|
||||||
|
.getDayOfMonth());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
|
|
@ -21,7 +21,6 @@ public class FunctionalInterfaceUnitTest {
|
||||||
|
|
||||||
private static final Logger LOG = LoggerFactory.getLogger(FunctionalInterfaceUnitTest.class);
|
private static final Logger LOG = LoggerFactory.getLogger(FunctionalInterfaceUnitTest.class);
|
||||||
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenPassingLambdaToComputeIfAbsent_thenTheValueGetsComputedAndPutIntoMap() {
|
public void whenPassingLambdaToComputeIfAbsent_thenTheValueGetsComputedAndPutIntoMap() {
|
||||||
Map<String, Integer> nameMap = new HashMap<>();
|
Map<String, Integer> nameMap = new HashMap<>();
|
||||||
|
@ -83,7 +82,8 @@ public class FunctionalInterfaceUnitTest {
|
||||||
return result;
|
return result;
|
||||||
});
|
});
|
||||||
|
|
||||||
List<Integer> fibonacci5 = fibonacci.limit(5).collect(Collectors.toList());
|
List<Integer> fibonacci5 = fibonacci.limit(5)
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
|
||||||
assertEquals(new Integer(1), fibonacci5.get(0));
|
assertEquals(new Integer(1), fibonacci5.get(0));
|
||||||
assertEquals(new Integer(1), fibonacci5.get(1));
|
assertEquals(new Integer(1), fibonacci5.get(1));
|
||||||
|
@ -112,7 +112,9 @@ public class FunctionalInterfaceUnitTest {
|
||||||
public void whenUsingPredicateInFilter_thenListValuesAreFilteredOut() {
|
public void whenUsingPredicateInFilter_thenListValuesAreFilteredOut() {
|
||||||
List<String> names = Arrays.asList("Angela", "Aaron", "Bob", "Claire", "David");
|
List<String> names = Arrays.asList("Angela", "Aaron", "Bob", "Claire", "David");
|
||||||
|
|
||||||
List<String> namesWithA = names.stream().filter(name -> name.startsWith("A")).collect(Collectors.toList());
|
List<String> namesWithA = names.stream()
|
||||||
|
.filter(name -> name.startsWith("A"))
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
|
||||||
assertEquals(2, namesWithA.size());
|
assertEquals(2, namesWithA.size());
|
||||||
assertTrue(namesWithA.contains("Angela"));
|
assertTrue(namesWithA.contains("Angela"));
|
||||||
|
@ -135,7 +137,8 @@ public class FunctionalInterfaceUnitTest {
|
||||||
|
|
||||||
List<Integer> values = Arrays.asList(3, 5, 8, 9, 12);
|
List<Integer> values = Arrays.asList(3, 5, 8, 9, 12);
|
||||||
|
|
||||||
int sum = values.stream().reduce(0, (i1, i2) -> i1 + i2);
|
int sum = values.stream()
|
||||||
|
.reduce(0, (i1, i2) -> i1 + i2);
|
||||||
|
|
||||||
assertEquals(37, sum);
|
assertEquals(37, sum);
|
||||||
|
|
||||||
|
|
|
@ -13,35 +13,26 @@ import static org.junit.Assert.*;
|
||||||
|
|
||||||
public class Java8GroupingByCollectorUnitTest {
|
public class Java8GroupingByCollectorUnitTest {
|
||||||
|
|
||||||
private static final List<BlogPost> posts = Arrays.asList(
|
private static final List<BlogPost> posts = Arrays.asList(new BlogPost("News item 1", "Author 1", BlogPostType.NEWS, 15), new BlogPost("Tech review 1", "Author 2", BlogPostType.REVIEW, 5),
|
||||||
new BlogPost("News item 1", "Author 1", BlogPostType.NEWS, 15),
|
new BlogPost("Programming guide", "Author 1", BlogPostType.GUIDE, 20), new BlogPost("News item 2", "Author 2", BlogPostType.NEWS, 35), new BlogPost("Tech review 2", "Author 1", BlogPostType.REVIEW, 15));
|
||||||
new BlogPost("Tech review 1", "Author 2", BlogPostType.REVIEW, 5),
|
|
||||||
new BlogPost("Programming guide", "Author 1", BlogPostType.GUIDE, 20),
|
|
||||||
new BlogPost("News item 2", "Author 2", BlogPostType.NEWS, 35),
|
|
||||||
new BlogPost("Tech review 2", "Author 1", BlogPostType.REVIEW, 15));
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenAListOfPosts_whenGroupedByType_thenGetAMapBetweenTypeAndPosts() {
|
public void givenAListOfPosts_whenGroupedByType_thenGetAMapBetweenTypeAndPosts() {
|
||||||
Map<BlogPostType, List<BlogPost>> postsPerType = posts
|
Map<BlogPostType, List<BlogPost>> postsPerType = posts.stream()
|
||||||
.stream()
|
.collect(groupingBy(BlogPost::getType));
|
||||||
.collect(groupingBy(BlogPost::getType));
|
|
||||||
|
|
||||||
assertEquals(2, postsPerType
|
assertEquals(2, postsPerType.get(BlogPostType.NEWS)
|
||||||
.get(BlogPostType.NEWS)
|
.size());
|
||||||
.size());
|
assertEquals(1, postsPerType.get(BlogPostType.GUIDE)
|
||||||
assertEquals(1, postsPerType
|
.size());
|
||||||
.get(BlogPostType.GUIDE)
|
assertEquals(2, postsPerType.get(BlogPostType.REVIEW)
|
||||||
.size());
|
.size());
|
||||||
assertEquals(2, postsPerType
|
|
||||||
.get(BlogPostType.REVIEW)
|
|
||||||
.size());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenAListOfPosts_whenGroupedByTypeAndTheirTitlesAreJoinedInAString_thenGetAMapBetweenTypeAndCsvTitles() {
|
public void givenAListOfPosts_whenGroupedByTypeAndTheirTitlesAreJoinedInAString_thenGetAMapBetweenTypeAndCsvTitles() {
|
||||||
Map<BlogPostType, String> postsPerType = posts
|
Map<BlogPostType, String> postsPerType = posts.stream()
|
||||||
.stream()
|
.collect(groupingBy(BlogPost::getType, mapping(BlogPost::getTitle, joining(", ", "Post titles: [", "]"))));
|
||||||
.collect(groupingBy(BlogPost::getType, mapping(BlogPost::getTitle, joining(", ", "Post titles: [", "]"))));
|
|
||||||
|
|
||||||
assertEquals("Post titles: [News item 1, News item 2]", postsPerType.get(BlogPostType.NEWS));
|
assertEquals("Post titles: [News item 1, News item 2]", postsPerType.get(BlogPostType.NEWS));
|
||||||
assertEquals("Post titles: [Programming guide]", postsPerType.get(BlogPostType.GUIDE));
|
assertEquals("Post titles: [Programming guide]", postsPerType.get(BlogPostType.GUIDE));
|
||||||
|
@ -50,174 +41,135 @@ public class Java8GroupingByCollectorUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenAListOfPosts_whenGroupedByTypeAndSumTheLikes_thenGetAMapBetweenTypeAndPostLikes() {
|
public void givenAListOfPosts_whenGroupedByTypeAndSumTheLikes_thenGetAMapBetweenTypeAndPostLikes() {
|
||||||
Map<BlogPostType, Integer> likesPerType = posts
|
Map<BlogPostType, Integer> likesPerType = posts.stream()
|
||||||
.stream()
|
.collect(groupingBy(BlogPost::getType, summingInt(BlogPost::getLikes)));
|
||||||
.collect(groupingBy(BlogPost::getType, summingInt(BlogPost::getLikes)));
|
|
||||||
|
|
||||||
assertEquals(50, likesPerType
|
assertEquals(50, likesPerType.get(BlogPostType.NEWS)
|
||||||
.get(BlogPostType.NEWS)
|
.intValue());
|
||||||
.intValue());
|
assertEquals(20, likesPerType.get(BlogPostType.REVIEW)
|
||||||
assertEquals(20, likesPerType
|
.intValue());
|
||||||
.get(BlogPostType.REVIEW)
|
assertEquals(20, likesPerType.get(BlogPostType.GUIDE)
|
||||||
.intValue());
|
.intValue());
|
||||||
assertEquals(20, likesPerType
|
|
||||||
.get(BlogPostType.GUIDE)
|
|
||||||
.intValue());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenAListOfPosts_whenGroupedByTypeInAnEnumMap_thenGetAnEnumMapBetweenTypeAndPosts() {
|
public void givenAListOfPosts_whenGroupedByTypeInAnEnumMap_thenGetAnEnumMapBetweenTypeAndPosts() {
|
||||||
EnumMap<BlogPostType, List<BlogPost>> postsPerType = posts
|
EnumMap<BlogPostType, List<BlogPost>> postsPerType = posts.stream()
|
||||||
.stream()
|
.collect(groupingBy(BlogPost::getType, () -> new EnumMap<>(BlogPostType.class), toList()));
|
||||||
.collect(groupingBy(BlogPost::getType, () -> new EnumMap<>(BlogPostType.class), toList()));
|
|
||||||
|
|
||||||
assertEquals(2, postsPerType
|
assertEquals(2, postsPerType.get(BlogPostType.NEWS)
|
||||||
.get(BlogPostType.NEWS)
|
.size());
|
||||||
.size());
|
assertEquals(1, postsPerType.get(BlogPostType.GUIDE)
|
||||||
assertEquals(1, postsPerType
|
.size());
|
||||||
.get(BlogPostType.GUIDE)
|
assertEquals(2, postsPerType.get(BlogPostType.REVIEW)
|
||||||
.size());
|
.size());
|
||||||
assertEquals(2, postsPerType
|
|
||||||
.get(BlogPostType.REVIEW)
|
|
||||||
.size());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenAListOfPosts_whenGroupedByTypeInSets_thenGetAMapBetweenTypesAndSetsOfPosts() {
|
public void givenAListOfPosts_whenGroupedByTypeInSets_thenGetAMapBetweenTypesAndSetsOfPosts() {
|
||||||
Map<BlogPostType, Set<BlogPost>> postsPerType = posts
|
Map<BlogPostType, Set<BlogPost>> postsPerType = posts.stream()
|
||||||
.stream()
|
.collect(groupingBy(BlogPost::getType, toSet()));
|
||||||
.collect(groupingBy(BlogPost::getType, toSet()));
|
|
||||||
|
|
||||||
assertEquals(2, postsPerType
|
assertEquals(2, postsPerType.get(BlogPostType.NEWS)
|
||||||
.get(BlogPostType.NEWS)
|
.size());
|
||||||
.size());
|
assertEquals(1, postsPerType.get(BlogPostType.GUIDE)
|
||||||
assertEquals(1, postsPerType
|
.size());
|
||||||
.get(BlogPostType.GUIDE)
|
assertEquals(2, postsPerType.get(BlogPostType.REVIEW)
|
||||||
.size());
|
.size());
|
||||||
assertEquals(2, postsPerType
|
|
||||||
.get(BlogPostType.REVIEW)
|
|
||||||
.size());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenAListOfPosts_whenGroupedByTypeConcurrently_thenGetAMapBetweenTypeAndPosts() {
|
public void givenAListOfPosts_whenGroupedByTypeConcurrently_thenGetAMapBetweenTypeAndPosts() {
|
||||||
ConcurrentMap<BlogPostType, List<BlogPost>> postsPerType = posts
|
ConcurrentMap<BlogPostType, List<BlogPost>> postsPerType = posts.parallelStream()
|
||||||
.parallelStream()
|
.collect(groupingByConcurrent(BlogPost::getType));
|
||||||
.collect(groupingByConcurrent(BlogPost::getType));
|
|
||||||
|
|
||||||
assertEquals(2, postsPerType
|
assertEquals(2, postsPerType.get(BlogPostType.NEWS)
|
||||||
.get(BlogPostType.NEWS)
|
.size());
|
||||||
.size());
|
assertEquals(1, postsPerType.get(BlogPostType.GUIDE)
|
||||||
assertEquals(1, postsPerType
|
.size());
|
||||||
.get(BlogPostType.GUIDE)
|
assertEquals(2, postsPerType.get(BlogPostType.REVIEW)
|
||||||
.size());
|
.size());
|
||||||
assertEquals(2, postsPerType
|
|
||||||
.get(BlogPostType.REVIEW)
|
|
||||||
.size());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenAListOfPosts_whenGroupedByTypeAndAveragingLikes_thenGetAMapBetweenTypeAndAverageNumberOfLikes() {
|
public void givenAListOfPosts_whenGroupedByTypeAndAveragingLikes_thenGetAMapBetweenTypeAndAverageNumberOfLikes() {
|
||||||
Map<BlogPostType, Double> averageLikesPerType = posts
|
Map<BlogPostType, Double> averageLikesPerType = posts.stream()
|
||||||
.stream()
|
.collect(groupingBy(BlogPost::getType, averagingInt(BlogPost::getLikes)));
|
||||||
.collect(groupingBy(BlogPost::getType, averagingInt(BlogPost::getLikes)));
|
|
||||||
|
|
||||||
assertEquals(25, averageLikesPerType
|
assertEquals(25, averageLikesPerType.get(BlogPostType.NEWS)
|
||||||
.get(BlogPostType.NEWS)
|
.intValue());
|
||||||
.intValue());
|
assertEquals(20, averageLikesPerType.get(BlogPostType.GUIDE)
|
||||||
assertEquals(20, averageLikesPerType
|
.intValue());
|
||||||
.get(BlogPostType.GUIDE)
|
assertEquals(10, averageLikesPerType.get(BlogPostType.REVIEW)
|
||||||
.intValue());
|
.intValue());
|
||||||
assertEquals(10, averageLikesPerType
|
|
||||||
.get(BlogPostType.REVIEW)
|
|
||||||
.intValue());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenAListOfPosts_whenGroupedByTypeAndCounted_thenGetAMapBetweenTypeAndNumberOfPosts() {
|
public void givenAListOfPosts_whenGroupedByTypeAndCounted_thenGetAMapBetweenTypeAndNumberOfPosts() {
|
||||||
Map<BlogPostType, Long> numberOfPostsPerType = posts
|
Map<BlogPostType, Long> numberOfPostsPerType = posts.stream()
|
||||||
.stream()
|
.collect(groupingBy(BlogPost::getType, counting()));
|
||||||
.collect(groupingBy(BlogPost::getType, counting()));
|
|
||||||
|
|
||||||
assertEquals(2, numberOfPostsPerType
|
assertEquals(2, numberOfPostsPerType.get(BlogPostType.NEWS)
|
||||||
.get(BlogPostType.NEWS)
|
.intValue());
|
||||||
.intValue());
|
assertEquals(1, numberOfPostsPerType.get(BlogPostType.GUIDE)
|
||||||
assertEquals(1, numberOfPostsPerType
|
.intValue());
|
||||||
.get(BlogPostType.GUIDE)
|
assertEquals(2, numberOfPostsPerType.get(BlogPostType.REVIEW)
|
||||||
.intValue());
|
.intValue());
|
||||||
assertEquals(2, numberOfPostsPerType
|
|
||||||
.get(BlogPostType.REVIEW)
|
|
||||||
.intValue());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenAListOfPosts_whenGroupedByTypeAndMaxingLikes_thenGetAMapBetweenTypeAndMaximumNumberOfLikes() {
|
public void givenAListOfPosts_whenGroupedByTypeAndMaxingLikes_thenGetAMapBetweenTypeAndMaximumNumberOfLikes() {
|
||||||
Map<BlogPostType, Optional<BlogPost>> maxLikesPerPostType = posts
|
Map<BlogPostType, Optional<BlogPost>> maxLikesPerPostType = posts.stream()
|
||||||
.stream()
|
.collect(groupingBy(BlogPost::getType, maxBy(comparingInt(BlogPost::getLikes))));
|
||||||
.collect(groupingBy(BlogPost::getType, maxBy(comparingInt(BlogPost::getLikes))));
|
|
||||||
|
|
||||||
assertTrue(maxLikesPerPostType
|
assertTrue(maxLikesPerPostType.get(BlogPostType.NEWS)
|
||||||
.get(BlogPostType.NEWS)
|
.isPresent());
|
||||||
.isPresent());
|
assertEquals(35, maxLikesPerPostType.get(BlogPostType.NEWS)
|
||||||
assertEquals(35, maxLikesPerPostType
|
.get()
|
||||||
.get(BlogPostType.NEWS)
|
.getLikes());
|
||||||
.get()
|
|
||||||
.getLikes());
|
|
||||||
|
|
||||||
assertTrue(maxLikesPerPostType
|
assertTrue(maxLikesPerPostType.get(BlogPostType.GUIDE)
|
||||||
.get(BlogPostType.GUIDE)
|
.isPresent());
|
||||||
.isPresent());
|
assertEquals(20, maxLikesPerPostType.get(BlogPostType.GUIDE)
|
||||||
assertEquals(20, maxLikesPerPostType
|
.get()
|
||||||
.get(BlogPostType.GUIDE)
|
.getLikes());
|
||||||
.get()
|
|
||||||
.getLikes());
|
|
||||||
|
|
||||||
assertTrue(maxLikesPerPostType
|
assertTrue(maxLikesPerPostType.get(BlogPostType.REVIEW)
|
||||||
.get(BlogPostType.REVIEW)
|
.isPresent());
|
||||||
.isPresent());
|
assertEquals(15, maxLikesPerPostType.get(BlogPostType.REVIEW)
|
||||||
assertEquals(15, maxLikesPerPostType
|
.get()
|
||||||
.get(BlogPostType.REVIEW)
|
.getLikes());
|
||||||
.get()
|
|
||||||
.getLikes());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenAListOfPosts_whenGroupedByAuthorAndThenByType_thenGetAMapBetweenAuthorAndMapsBetweenTypeAndBlogPosts() {
|
public void givenAListOfPosts_whenGroupedByAuthorAndThenByType_thenGetAMapBetweenAuthorAndMapsBetweenTypeAndBlogPosts() {
|
||||||
Map<String, Map<BlogPostType, List<BlogPost>>> map = posts
|
Map<String, Map<BlogPostType, List<BlogPost>>> map = posts.stream()
|
||||||
.stream()
|
.collect(groupingBy(BlogPost::getAuthor, groupingBy(BlogPost::getType)));
|
||||||
.collect(groupingBy(BlogPost::getAuthor, groupingBy(BlogPost::getType)));
|
|
||||||
|
|
||||||
assertEquals(1, map
|
assertEquals(1, map.get("Author 1")
|
||||||
.get("Author 1")
|
.get(BlogPostType.NEWS)
|
||||||
.get(BlogPostType.NEWS)
|
.size());
|
||||||
.size());
|
assertEquals(1, map.get("Author 1")
|
||||||
assertEquals(1, map
|
.get(BlogPostType.GUIDE)
|
||||||
.get("Author 1")
|
.size());
|
||||||
.get(BlogPostType.GUIDE)
|
assertEquals(1, map.get("Author 1")
|
||||||
.size());
|
.get(BlogPostType.REVIEW)
|
||||||
assertEquals(1, map
|
.size());
|
||||||
.get("Author 1")
|
|
||||||
.get(BlogPostType.REVIEW)
|
|
||||||
.size());
|
|
||||||
|
|
||||||
assertEquals(1, map
|
assertEquals(1, map.get("Author 2")
|
||||||
.get("Author 2")
|
.get(BlogPostType.NEWS)
|
||||||
.get(BlogPostType.NEWS)
|
.size());
|
||||||
.size());
|
assertEquals(1, map.get("Author 2")
|
||||||
assertEquals(1, map
|
.get(BlogPostType.REVIEW)
|
||||||
.get("Author 2")
|
.size());
|
||||||
.get(BlogPostType.REVIEW)
|
assertNull(map.get("Author 2")
|
||||||
.size());
|
.get(BlogPostType.GUIDE));
|
||||||
assertNull(map
|
|
||||||
.get("Author 2")
|
|
||||||
.get(BlogPostType.GUIDE));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenAListOfPosts_whenGroupedByTypeAndSummarizingLikes_thenGetAMapBetweenTypeAndSummary() {
|
public void givenAListOfPosts_whenGroupedByTypeAndSummarizingLikes_thenGetAMapBetweenTypeAndSummary() {
|
||||||
Map<BlogPostType, IntSummaryStatistics> likeStatisticsPerType = posts
|
Map<BlogPostType, IntSummaryStatistics> likeStatisticsPerType = posts.stream()
|
||||||
.stream()
|
.collect(groupingBy(BlogPost::getType, summarizingInt(BlogPost::getLikes)));
|
||||||
.collect(groupingBy(BlogPost::getType, summarizingInt(BlogPost::getLikes)));
|
|
||||||
|
|
||||||
IntSummaryStatistics newsLikeStatistics = likeStatisticsPerType.get(BlogPostType.NEWS);
|
IntSummaryStatistics newsLikeStatistics = likeStatisticsPerType.get(BlogPostType.NEWS);
|
||||||
|
|
||||||
|
|
|
@ -17,8 +17,8 @@ public class Java8MapAndFlatMap {
|
||||||
@Test
|
@Test
|
||||||
public void givenStream_whenCalledMap_thenProduceList() {
|
public void givenStream_whenCalledMap_thenProduceList() {
|
||||||
List<String> myList = Stream.of("a", "b")
|
List<String> myList = Stream.of("a", "b")
|
||||||
.map(String::toUpperCase)
|
.map(String::toUpperCase)
|
||||||
.collect(Collectors.toList());
|
.collect(Collectors.toList());
|
||||||
assertEquals(asList("A", "B"), myList);
|
assertEquals(asList("A", "B"), myList);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -27,9 +27,9 @@ public class Java8MapAndFlatMap {
|
||||||
List<List<String>> list = Arrays.asList(Arrays.asList("a"), Arrays.asList("b"));
|
List<List<String>> list = Arrays.asList(Arrays.asList("a"), Arrays.asList("b"));
|
||||||
System.out.println(list);
|
System.out.println(list);
|
||||||
|
|
||||||
System.out.println(list
|
System.out.println(list.stream()
|
||||||
.stream().flatMap(Collection::stream)
|
.flatMap(Collection::stream)
|
||||||
.collect(Collectors.toList()));
|
.collect(Collectors.toList()));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -40,13 +40,11 @@ public class Java8MapAndFlatMap {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenOptional_whenCalledFlatMap_thenProduceFlattenedOptional() {
|
public void givenOptional_whenCalledFlatMap_thenProduceFlattenedOptional() {
|
||||||
assertEquals(Optional.of(Optional.of("STRING")), Optional
|
assertEquals(Optional.of(Optional.of("STRING")), Optional.of("string")
|
||||||
.of("string")
|
.map(s -> Optional.of("STRING")));
|
||||||
.map(s -> Optional.of("STRING")));
|
|
||||||
|
|
||||||
assertEquals(Optional.of("STRING"), Optional
|
assertEquals(Optional.of("STRING"), Optional.of("string")
|
||||||
.of("string")
|
.flatMap(s -> Optional.of("STRING")));
|
||||||
.flatMap(s -> Optional.of("STRING")));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -55,7 +55,12 @@ public class JavaFolderSizeUnitTest {
|
||||||
@Test
|
@Test
|
||||||
public void whenGetFolderSizeUsingJava8_thenCorrect() throws IOException {
|
public void whenGetFolderSizeUsingJava8_thenCorrect() throws IOException {
|
||||||
final Path folder = Paths.get(path);
|
final Path folder = Paths.get(path);
|
||||||
final long size = Files.walk(folder).filter(p -> p.toFile().isFile()).mapToLong(p -> p.toFile().length()).sum();
|
final long size = Files.walk(folder)
|
||||||
|
.filter(p -> p.toFile()
|
||||||
|
.isFile())
|
||||||
|
.mapToLong(p -> p.toFile()
|
||||||
|
.length())
|
||||||
|
.sum();
|
||||||
|
|
||||||
assertEquals(EXPECTED_SIZE, size);
|
assertEquals(EXPECTED_SIZE, size);
|
||||||
}
|
}
|
||||||
|
@ -72,8 +77,12 @@ public class JavaFolderSizeUnitTest {
|
||||||
public void whenGetFolderSizeUsingGuava_thenCorrect() {
|
public void whenGetFolderSizeUsingGuava_thenCorrect() {
|
||||||
final File folder = new File(path);
|
final File folder = new File(path);
|
||||||
|
|
||||||
final Iterable<File> files = com.google.common.io.Files.fileTreeTraverser().breadthFirstTraversal(folder);
|
final Iterable<File> files = com.google.common.io.Files.fileTreeTraverser()
|
||||||
final long size = StreamSupport.stream(files.spliterator(), false).filter(File::isFile).mapToLong(File::length).sum();
|
.breadthFirstTraversal(folder);
|
||||||
|
final long size = StreamSupport.stream(files.spliterator(), false)
|
||||||
|
.filter(File::isFile)
|
||||||
|
.mapToLong(File::length)
|
||||||
|
.sum();
|
||||||
|
|
||||||
assertEquals(EXPECTED_SIZE, size);
|
assertEquals(EXPECTED_SIZE, size);
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,4 +1,5 @@
|
||||||
package com.baeldung.java8.comparator;
|
package com.baeldung.java8.comparator;
|
||||||
|
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
import java.util.Comparator;
|
import java.util.Comparator;
|
||||||
|
|
||||||
|
@ -25,44 +26,32 @@ public class Java8ComparatorUnitTest {
|
||||||
|
|
||||||
@Before
|
@Before
|
||||||
public void initData() {
|
public void initData() {
|
||||||
employees = new Employee[] { new Employee("John", 25, 3000, 9922001), new Employee("Ace", 22, 2000, 5924001),
|
employees = new Employee[] { new Employee("John", 25, 3000, 9922001), new Employee("Ace", 22, 2000, 5924001), new Employee("Keith", 35, 4000, 3924401) };
|
||||||
new Employee("Keith", 35, 4000, 3924401) };
|
employeesArrayWithNulls = new Employee[] { new Employee("John", 25, 3000, 9922001), null, new Employee("Ace", 22, 2000, 5924001), null, new Employee("Keith", 35, 4000, 3924401) };
|
||||||
employeesArrayWithNulls = new Employee[] { new Employee("John", 25, 3000, 9922001), null, new Employee("Ace", 22, 2000, 5924001),
|
|
||||||
null, new Employee("Keith", 35, 4000, 3924401) };
|
|
||||||
|
|
||||||
sortedEmployeesByName = new Employee[] { new Employee("Ace", 22, 2000, 5924001),
|
sortedEmployeesByName = new Employee[] { new Employee("Ace", 22, 2000, 5924001), new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) };
|
||||||
new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) };
|
sortedEmployeesByNameDesc = new Employee[] { new Employee("Keith", 35, 4000, 3924401), new Employee("John", 25, 3000, 9922001), new Employee("Ace", 22, 2000, 5924001) };
|
||||||
sortedEmployeesByNameDesc = new Employee[] { new Employee("Keith", 35, 4000, 3924401), new Employee("John", 25, 3000, 9922001),
|
|
||||||
new Employee("Ace", 22, 2000, 5924001) };
|
|
||||||
|
|
||||||
sortedEmployeesByAge = new Employee[] { new Employee("Ace", 22, 2000, 5924001),
|
sortedEmployeesByAge = new Employee[] { new Employee("Ace", 22, 2000, 5924001), new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) };
|
||||||
new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) };
|
|
||||||
|
|
||||||
sortedEmployeesByMobile = new Employee[] { new Employee("Keith", 35, 4000, 3924401), new Employee("Ace", 22, 2000, 5924001),
|
sortedEmployeesByMobile = new Employee[] { new Employee("Keith", 35, 4000, 3924401), new Employee("Ace", 22, 2000, 5924001), new Employee("John", 25, 3000, 9922001), };
|
||||||
new Employee("John", 25, 3000, 9922001), };
|
|
||||||
|
|
||||||
sortedEmployeesBySalary = new Employee[] { new Employee("Ace", 22, 2000, 5924001), new Employee("John", 25, 3000, 9922001),
|
sortedEmployeesBySalary = new Employee[] { new Employee("Ace", 22, 2000, 5924001), new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401), };
|
||||||
new Employee("Keith", 35, 4000, 3924401), };
|
|
||||||
|
|
||||||
sortedEmployeesArray_WithNullsFirst = new Employee[] { null, null, new Employee("Ace", 22, 2000, 5924001),
|
sortedEmployeesArray_WithNullsFirst = new Employee[] { null, null, new Employee("Ace", 22, 2000, 5924001), new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) };
|
||||||
new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) };
|
sortedEmployeesArray_WithNullsLast = new Employee[] { new Employee("Ace", 22, 2000, 5924001), new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401), null, null };
|
||||||
sortedEmployeesArray_WithNullsLast = new Employee[] { new Employee("Ace", 22, 2000, 5924001),
|
|
||||||
new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401), null, null };
|
|
||||||
|
|
||||||
someMoreEmployees = new Employee[] { new Employee("Jake", 25, 3000, 9922001), new Employee("Jake", 22, 2000, 5924001),
|
someMoreEmployees = new Employee[] { new Employee("Jake", 25, 3000, 9922001), new Employee("Jake", 22, 2000, 5924001), new Employee("Ace", 22, 3000, 6423001), new Employee("Keith", 35, 4000, 3924401) };
|
||||||
new Employee("Ace", 22, 3000, 6423001), new Employee("Keith", 35, 4000, 3924401) };
|
|
||||||
|
|
||||||
sortedEmployeesByAgeName = new Employee[] { new Employee("Ace", 22, 3000, 6423001),
|
sortedEmployeesByAgeName = new Employee[] { new Employee("Ace", 22, 3000, 6423001), new Employee("Jake", 22, 2000, 5924001), new Employee("Jake", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) };
|
||||||
new Employee("Jake", 22, 2000, 5924001), new Employee("Jake", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) };
|
sortedEmployeesByNameAge = new Employee[] { new Employee("Ace", 22, 3000, 6423001), new Employee("Jake", 22, 2000, 5924001), new Employee("Jake", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) };
|
||||||
sortedEmployeesByNameAge = new Employee[] { new Employee("Ace", 22, 3000, 6423001),
|
|
||||||
new Employee("Jake", 22, 2000, 5924001), new Employee("Jake", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) };
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenComparing_thenSortedByName() {
|
public void whenComparing_thenSortedByName() {
|
||||||
Comparator<Employee> employeeNameComparator = Comparator.comparing(Employee::getName);
|
Comparator<Employee> employeeNameComparator = Comparator.comparing(Employee::getName);
|
||||||
Arrays.sort(employees, employeeNameComparator);
|
Arrays.sort(employees, employeeNameComparator);
|
||||||
// System.out.println(Arrays.toString(employees));
|
// System.out.println(Arrays.toString(employees));
|
||||||
assertTrue(Arrays.equals(employees, sortedEmployeesByName));
|
assertTrue(Arrays.equals(employees, sortedEmployeesByName));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -72,16 +61,16 @@ public class Java8ComparatorUnitTest {
|
||||||
return s2.compareTo(s1);
|
return s2.compareTo(s1);
|
||||||
});
|
});
|
||||||
Arrays.sort(employees, employeeNameComparator);
|
Arrays.sort(employees, employeeNameComparator);
|
||||||
// System.out.println(Arrays.toString(employees));
|
// System.out.println(Arrays.toString(employees));
|
||||||
assertTrue(Arrays.equals(employees, sortedEmployeesByNameDesc));
|
assertTrue(Arrays.equals(employees, sortedEmployeesByNameDesc));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenReversed_thenSortedByNameDesc() {
|
public void whenReversed_thenSortedByNameDesc() {
|
||||||
Comparator<Employee> employeeNameComparator = Comparator.comparing(Employee::getName);
|
Comparator<Employee> employeeNameComparator = Comparator.comparing(Employee::getName);
|
||||||
Comparator<Employee> employeeNameComparatorReversed = employeeNameComparator.reversed();
|
Comparator<Employee> employeeNameComparatorReversed = employeeNameComparator.reversed();
|
||||||
Arrays.sort(employees, employeeNameComparatorReversed);
|
Arrays.sort(employees, employeeNameComparatorReversed);
|
||||||
// System.out.println(Arrays.toString(employees));
|
// System.out.println(Arrays.toString(employees));
|
||||||
assertTrue(Arrays.equals(employees, sortedEmployeesByNameDesc));
|
assertTrue(Arrays.equals(employees, sortedEmployeesByNameDesc));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -89,7 +78,7 @@ public class Java8ComparatorUnitTest {
|
||||||
public void whenComparingInt_thenSortedByAge() {
|
public void whenComparingInt_thenSortedByAge() {
|
||||||
Comparator<Employee> employeeAgeComparator = Comparator.comparingInt(Employee::getAge);
|
Comparator<Employee> employeeAgeComparator = Comparator.comparingInt(Employee::getAge);
|
||||||
Arrays.sort(employees, employeeAgeComparator);
|
Arrays.sort(employees, employeeAgeComparator);
|
||||||
// System.out.println(Arrays.toString(employees));
|
// System.out.println(Arrays.toString(employees));
|
||||||
assertTrue(Arrays.equals(employees, sortedEmployeesByAge));
|
assertTrue(Arrays.equals(employees, sortedEmployeesByAge));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -97,7 +86,7 @@ public class Java8ComparatorUnitTest {
|
||||||
public void whenComparingLong_thenSortedByMobile() {
|
public void whenComparingLong_thenSortedByMobile() {
|
||||||
Comparator<Employee> employeeMobileComparator = Comparator.comparingLong(Employee::getMobile);
|
Comparator<Employee> employeeMobileComparator = Comparator.comparingLong(Employee::getMobile);
|
||||||
Arrays.sort(employees, employeeMobileComparator);
|
Arrays.sort(employees, employeeMobileComparator);
|
||||||
// System.out.println(Arrays.toString(employees));
|
// System.out.println(Arrays.toString(employees));
|
||||||
assertTrue(Arrays.equals(employees, sortedEmployeesByMobile));
|
assertTrue(Arrays.equals(employees, sortedEmployeesByMobile));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -105,7 +94,7 @@ public class Java8ComparatorUnitTest {
|
||||||
public void whenComparingDouble_thenSortedBySalary() {
|
public void whenComparingDouble_thenSortedBySalary() {
|
||||||
Comparator<Employee> employeeSalaryComparator = Comparator.comparingDouble(Employee::getSalary);
|
Comparator<Employee> employeeSalaryComparator = Comparator.comparingDouble(Employee::getSalary);
|
||||||
Arrays.sort(employees, employeeSalaryComparator);
|
Arrays.sort(employees, employeeSalaryComparator);
|
||||||
// System.out.println(Arrays.toString(employees));
|
// System.out.println(Arrays.toString(employees));
|
||||||
assertTrue(Arrays.equals(employees, sortedEmployeesBySalary));
|
assertTrue(Arrays.equals(employees, sortedEmployeesBySalary));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -113,7 +102,7 @@ public class Java8ComparatorUnitTest {
|
||||||
public void whenNaturalOrder_thenSortedByName() {
|
public void whenNaturalOrder_thenSortedByName() {
|
||||||
Comparator<Employee> employeeNameComparator = Comparator.<Employee> naturalOrder();
|
Comparator<Employee> employeeNameComparator = Comparator.<Employee> naturalOrder();
|
||||||
Arrays.sort(employees, employeeNameComparator);
|
Arrays.sort(employees, employeeNameComparator);
|
||||||
// System.out.println(Arrays.toString(employees));
|
// System.out.println(Arrays.toString(employees));
|
||||||
assertTrue(Arrays.equals(employees, sortedEmployeesByName));
|
assertTrue(Arrays.equals(employees, sortedEmployeesByName));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -121,7 +110,7 @@ public class Java8ComparatorUnitTest {
|
||||||
public void whenReverseOrder_thenSortedByNameDesc() {
|
public void whenReverseOrder_thenSortedByNameDesc() {
|
||||||
Comparator<Employee> employeeNameComparator = Comparator.<Employee> reverseOrder();
|
Comparator<Employee> employeeNameComparator = Comparator.<Employee> reverseOrder();
|
||||||
Arrays.sort(employees, employeeNameComparator);
|
Arrays.sort(employees, employeeNameComparator);
|
||||||
// System.out.println(Arrays.toString(employees));
|
// System.out.println(Arrays.toString(employees));
|
||||||
assertTrue(Arrays.equals(employees, sortedEmployeesByNameDesc));
|
assertTrue(Arrays.equals(employees, sortedEmployeesByNameDesc));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -130,7 +119,7 @@ public class Java8ComparatorUnitTest {
|
||||||
Comparator<Employee> employeeNameComparator = Comparator.comparing(Employee::getName);
|
Comparator<Employee> employeeNameComparator = Comparator.comparing(Employee::getName);
|
||||||
Comparator<Employee> employeeNameComparator_nullFirst = Comparator.nullsFirst(employeeNameComparator);
|
Comparator<Employee> employeeNameComparator_nullFirst = Comparator.nullsFirst(employeeNameComparator);
|
||||||
Arrays.sort(employeesArrayWithNulls, employeeNameComparator_nullFirst);
|
Arrays.sort(employeesArrayWithNulls, employeeNameComparator_nullFirst);
|
||||||
// System.out.println(Arrays.toString(employeesArrayWithNulls));
|
// System.out.println(Arrays.toString(employeesArrayWithNulls));
|
||||||
assertTrue(Arrays.equals(employeesArrayWithNulls, sortedEmployeesArray_WithNullsFirst));
|
assertTrue(Arrays.equals(employeesArrayWithNulls, sortedEmployeesArray_WithNullsFirst));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -139,27 +128,28 @@ public class Java8ComparatorUnitTest {
|
||||||
Comparator<Employee> employeeNameComparator = Comparator.comparing(Employee::getName);
|
Comparator<Employee> employeeNameComparator = Comparator.comparing(Employee::getName);
|
||||||
Comparator<Employee> employeeNameComparator_nullLast = Comparator.nullsLast(employeeNameComparator);
|
Comparator<Employee> employeeNameComparator_nullLast = Comparator.nullsLast(employeeNameComparator);
|
||||||
Arrays.sort(employeesArrayWithNulls, employeeNameComparator_nullLast);
|
Arrays.sort(employeesArrayWithNulls, employeeNameComparator_nullLast);
|
||||||
// System.out.println(Arrays.toString(employeesArrayWithNulls));
|
// System.out.println(Arrays.toString(employeesArrayWithNulls));
|
||||||
assertTrue(Arrays.equals(employeesArrayWithNulls, sortedEmployeesArray_WithNullsLast));
|
assertTrue(Arrays.equals(employeesArrayWithNulls, sortedEmployeesArray_WithNullsLast));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenThenComparing_thenSortedByAgeName() {
|
public void whenThenComparing_thenSortedByAgeName() {
|
||||||
Comparator<Employee> employee_Age_Name_Comparator = Comparator.comparing(Employee::getAge).thenComparing(Employee::getName);
|
Comparator<Employee> employee_Age_Name_Comparator = Comparator.comparing(Employee::getAge)
|
||||||
|
.thenComparing(Employee::getName);
|
||||||
|
|
||||||
Arrays.sort(someMoreEmployees, employee_Age_Name_Comparator);
|
Arrays.sort(someMoreEmployees, employee_Age_Name_Comparator);
|
||||||
// System.out.println(Arrays.toString(someMoreEmployees));
|
// System.out.println(Arrays.toString(someMoreEmployees));
|
||||||
assertTrue(Arrays.equals(someMoreEmployees, sortedEmployeesByAgeName));
|
assertTrue(Arrays.equals(someMoreEmployees, sortedEmployeesByAgeName));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenThenComparing_thenSortedByNameAge() {
|
public void whenThenComparing_thenSortedByNameAge() {
|
||||||
Comparator<Employee> employee_Name_Age_Comparator = Comparator.comparing(Employee::getName).thenComparingInt(Employee::getAge);
|
Comparator<Employee> employee_Name_Age_Comparator = Comparator.comparing(Employee::getName)
|
||||||
|
.thenComparingInt(Employee::getAge);
|
||||||
|
|
||||||
Arrays.sort(someMoreEmployees, employee_Name_Age_Comparator);
|
Arrays.sort(someMoreEmployees, employee_Name_Age_Comparator);
|
||||||
// System.out.println(Arrays.toString(someMoreEmployees));
|
// System.out.println(Arrays.toString(someMoreEmployees));
|
||||||
assertTrue(Arrays.equals(someMoreEmployees, sortedEmployeesByNameAge));
|
assertTrue(Arrays.equals(someMoreEmployees, sortedEmployeesByNameAge));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -17,7 +17,6 @@ public class OptionalUnitTest {
|
||||||
|
|
||||||
private static final Logger LOG = LoggerFactory.getLogger(OptionalUnitTest.class);
|
private static final Logger LOG = LoggerFactory.getLogger(OptionalUnitTest.class);
|
||||||
|
|
||||||
|
|
||||||
// creating Optional
|
// creating Optional
|
||||||
@Test
|
@Test
|
||||||
public void whenCreatesEmptyOptional_thenCorrect() {
|
public void whenCreatesEmptyOptional_thenCorrect() {
|
||||||
|
@ -94,9 +93,11 @@ public class OptionalUnitTest {
|
||||||
public void whenOptionalFilterWorks_thenCorrect() {
|
public void whenOptionalFilterWorks_thenCorrect() {
|
||||||
Integer year = 2016;
|
Integer year = 2016;
|
||||||
Optional<Integer> yearOptional = Optional.of(year);
|
Optional<Integer> yearOptional = Optional.of(year);
|
||||||
boolean is2016 = yearOptional.filter(y -> y == 2016).isPresent();
|
boolean is2016 = yearOptional.filter(y -> y == 2016)
|
||||||
|
.isPresent();
|
||||||
assertTrue(is2016);
|
assertTrue(is2016);
|
||||||
boolean is2017 = yearOptional.filter(y -> y == 2017).isPresent();
|
boolean is2017 = yearOptional.filter(y -> y == 2017)
|
||||||
|
.isPresent();
|
||||||
assertFalse(is2017);
|
assertFalse(is2017);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -128,7 +129,11 @@ public class OptionalUnitTest {
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean priceIsInRange2(Modem modem2) {
|
public boolean priceIsInRange2(Modem modem2) {
|
||||||
return Optional.ofNullable(modem2).map(Modem::getPrice).filter(p -> p >= 10).filter(p -> p <= 15).isPresent();
|
return Optional.ofNullable(modem2)
|
||||||
|
.map(Modem::getPrice)
|
||||||
|
.filter(p -> p >= 10)
|
||||||
|
.filter(p -> p <= 15)
|
||||||
|
.isPresent();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Transforming Value With map()
|
// Transforming Value With map()
|
||||||
|
@ -137,7 +142,8 @@ public class OptionalUnitTest {
|
||||||
List<String> companyNames = Arrays.asList("paypal", "oracle", "", "microsoft", "", "apple");
|
List<String> companyNames = Arrays.asList("paypal", "oracle", "", "microsoft", "", "apple");
|
||||||
Optional<List<String>> listOptional = Optional.of(companyNames);
|
Optional<List<String>> listOptional = Optional.of(companyNames);
|
||||||
|
|
||||||
int size = listOptional.map(List::size).orElse(0);
|
int size = listOptional.map(List::size)
|
||||||
|
.orElse(0);
|
||||||
assertEquals(6, size);
|
assertEquals(6, size);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -146,7 +152,8 @@ public class OptionalUnitTest {
|
||||||
String name = "baeldung";
|
String name = "baeldung";
|
||||||
Optional<String> nameOptional = Optional.of(name);
|
Optional<String> nameOptional = Optional.of(name);
|
||||||
|
|
||||||
int len = nameOptional.map(String::length).orElse(0);
|
int len = nameOptional.map(String::length)
|
||||||
|
.orElse(0);
|
||||||
assertEquals(8, len);
|
assertEquals(8, len);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -154,10 +161,13 @@ public class OptionalUnitTest {
|
||||||
public void givenOptional_whenMapWorksWithFilter_thenCorrect() {
|
public void givenOptional_whenMapWorksWithFilter_thenCorrect() {
|
||||||
String password = " password ";
|
String password = " password ";
|
||||||
Optional<String> passOpt = Optional.of(password);
|
Optional<String> passOpt = Optional.of(password);
|
||||||
boolean correctPassword = passOpt.filter(pass -> pass.equals("password")).isPresent();
|
boolean correctPassword = passOpt.filter(pass -> pass.equals("password"))
|
||||||
|
.isPresent();
|
||||||
assertFalse(correctPassword);
|
assertFalse(correctPassword);
|
||||||
|
|
||||||
correctPassword = passOpt.map(String::trim).filter(pass -> pass.equals("password")).isPresent();
|
correctPassword = passOpt.map(String::trim)
|
||||||
|
.filter(pass -> pass.equals("password"))
|
||||||
|
.isPresent();
|
||||||
assertTrue(correctPassword);
|
assertTrue(correctPassword);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -172,7 +182,8 @@ public class OptionalUnitTest {
|
||||||
String name1 = nameOptional.orElseThrow(IllegalArgumentException::new);
|
String name1 = nameOptional.orElseThrow(IllegalArgumentException::new);
|
||||||
assertEquals("john", name1);
|
assertEquals("john", name1);
|
||||||
|
|
||||||
String name = personOptional.flatMap(Person::getName).orElseThrow(IllegalArgumentException::new);
|
String name = personOptional.flatMap(Person::getName)
|
||||||
|
.orElseThrow(IllegalArgumentException::new);
|
||||||
assertEquals("john", name);
|
assertEquals("john", name);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -182,7 +193,9 @@ public class OptionalUnitTest {
|
||||||
person.setPassword("password");
|
person.setPassword("password");
|
||||||
Optional<Person> personOptional = Optional.of(person);
|
Optional<Person> personOptional = Optional.of(person);
|
||||||
|
|
||||||
String password = personOptional.flatMap(Person::getPassword).filter(cleanPass -> cleanPass.equals("password")).orElseThrow(IllegalArgumentException::new);
|
String password = personOptional.flatMap(Person::getPassword)
|
||||||
|
.filter(cleanPass -> cleanPass.equals("password"))
|
||||||
|
.orElseThrow(IllegalArgumentException::new);
|
||||||
assertEquals("password", password);
|
assertEquals("password", password);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -190,7 +203,8 @@ public class OptionalUnitTest {
|
||||||
@Test
|
@Test
|
||||||
public void whenOrElseWorks_thenCorrect() {
|
public void whenOrElseWorks_thenCorrect() {
|
||||||
String nullName = null;
|
String nullName = null;
|
||||||
String name = Optional.ofNullable(nullName).orElse("john");
|
String name = Optional.ofNullable(nullName)
|
||||||
|
.orElse("john");
|
||||||
assertEquals("john", name);
|
assertEquals("john", name);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -198,7 +212,8 @@ public class OptionalUnitTest {
|
||||||
@Test
|
@Test
|
||||||
public void whenOrElseGetWorks_thenCorrect() {
|
public void whenOrElseGetWorks_thenCorrect() {
|
||||||
String nullName = null;
|
String nullName = null;
|
||||||
String name = Optional.ofNullable(nullName).orElseGet(() -> "john");
|
String name = Optional.ofNullable(nullName)
|
||||||
|
.orElseGet(() -> "john");
|
||||||
assertEquals("john", name);
|
assertEquals("john", name);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -207,11 +222,13 @@ public class OptionalUnitTest {
|
||||||
public void whenOrElseGetAndOrElseOverlap_thenCorrect() {
|
public void whenOrElseGetAndOrElseOverlap_thenCorrect() {
|
||||||
String text = null;
|
String text = null;
|
||||||
LOG.debug("Using orElseGet:");
|
LOG.debug("Using orElseGet:");
|
||||||
String defaultText = Optional.ofNullable(text).orElseGet(this::getMyDefault);
|
String defaultText = Optional.ofNullable(text)
|
||||||
|
.orElseGet(this::getMyDefault);
|
||||||
assertEquals("Default Value", defaultText);
|
assertEquals("Default Value", defaultText);
|
||||||
|
|
||||||
LOG.debug("Using orElse:");
|
LOG.debug("Using orElse:");
|
||||||
defaultText = Optional.ofNullable(text).orElse(getMyDefault());
|
defaultText = Optional.ofNullable(text)
|
||||||
|
.orElse(getMyDefault());
|
||||||
assertEquals("Default Value", defaultText);
|
assertEquals("Default Value", defaultText);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -219,11 +236,13 @@ public class OptionalUnitTest {
|
||||||
public void whenOrElseGetAndOrElseDiffer_thenCorrect() {
|
public void whenOrElseGetAndOrElseDiffer_thenCorrect() {
|
||||||
String text = "Text present";
|
String text = "Text present";
|
||||||
LOG.debug("Using orElseGet:");
|
LOG.debug("Using orElseGet:");
|
||||||
String defaultText = Optional.ofNullable(text).orElseGet(this::getMyDefault);
|
String defaultText = Optional.ofNullable(text)
|
||||||
|
.orElseGet(this::getMyDefault);
|
||||||
assertEquals("Text present", defaultText);
|
assertEquals("Text present", defaultText);
|
||||||
|
|
||||||
LOG.debug("Using orElse:");
|
LOG.debug("Using orElse:");
|
||||||
defaultText = Optional.ofNullable(text).orElse(getMyDefault());
|
defaultText = Optional.ofNullable(text)
|
||||||
|
.orElse(getMyDefault());
|
||||||
assertEquals("Text present", defaultText);
|
assertEquals("Text present", defaultText);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -231,7 +250,8 @@ public class OptionalUnitTest {
|
||||||
@Test(expected = IllegalArgumentException.class)
|
@Test(expected = IllegalArgumentException.class)
|
||||||
public void whenOrElseThrowWorks_thenCorrect() {
|
public void whenOrElseThrowWorks_thenCorrect() {
|
||||||
String nullName = null;
|
String nullName = null;
|
||||||
String name = Optional.ofNullable(nullName).orElseThrow(IllegalArgumentException::new);
|
String name = Optional.ofNullable(nullName)
|
||||||
|
.orElseThrow(IllegalArgumentException::new);
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getMyDefault() {
|
public String getMyDefault() {
|
||||||
|
|
|
@ -43,6 +43,8 @@ public class FlattenNestedListUnitTest {
|
||||||
}
|
}
|
||||||
|
|
||||||
private <T> List<T> flattenListOfListsStream(List<List<T>> list) {
|
private <T> List<T> flattenListOfListsStream(List<List<T>> list) {
|
||||||
return list.stream().flatMap(Collection::stream).collect(Collectors.toList());
|
return list.stream()
|
||||||
|
.flatMap(Collection::stream)
|
||||||
|
.collect(Collectors.toList());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -14,7 +14,8 @@ public class EchoIntegrationTest {
|
||||||
|
|
||||||
@BeforeClass
|
@BeforeClass
|
||||||
public static void start() throws InterruptedException {
|
public static void start() throws InterruptedException {
|
||||||
Executors.newSingleThreadExecutor().submit(() -> new EchoServer().start(PORT));
|
Executors.newSingleThreadExecutor()
|
||||||
|
.submit(() -> new EchoServer().start(PORT));
|
||||||
Thread.sleep(500);
|
Thread.sleep(500);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -17,7 +17,8 @@ public class GreetServerIntegrationTest {
|
||||||
|
|
||||||
@BeforeClass
|
@BeforeClass
|
||||||
public static void start() throws InterruptedException {
|
public static void start() throws InterruptedException {
|
||||||
Executors.newSingleThreadExecutor().submit(() -> new GreetServer().start(PORT));
|
Executors.newSingleThreadExecutor()
|
||||||
|
.submit(() -> new GreetServer().start(PORT));
|
||||||
Thread.sleep(500);
|
Thread.sleep(500);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -21,7 +21,7 @@ public class CharSequenceVsStringUnitTest {
|
||||||
CharSequence charSequence1 = "baeldung_1";
|
CharSequence charSequence1 = "baeldung_1";
|
||||||
CharSequence charSequence2 = "baeldung_2";
|
CharSequence charSequence2 = "baeldung_2";
|
||||||
|
|
||||||
assertTrue(charSequence1.toString().compareTo(charSequence2.toString()) > 0);
|
assertTrue(charSequence1.toString().compareTo(charSequence2.toString()) < 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -31,7 +31,7 @@ public class CharSequenceVsStringUnitTest {
|
||||||
test += "b";
|
test += "b";
|
||||||
int secondAddressOfTest = System.identityHashCode(test);
|
int secondAddressOfTest = System.identityHashCode(test);
|
||||||
|
|
||||||
assertEquals(firstAddressOfTest, secondAddressOfTest);
|
assertNotEquals(firstAddressOfTest, secondAddressOfTest);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
|
|
@ -96,9 +96,12 @@ public class JavaIoUnitTest {
|
||||||
// utils
|
// utils
|
||||||
|
|
||||||
private final void logMemory() {
|
private final void logMemory() {
|
||||||
logger.info("Max Memory: {} Mb", Runtime.getRuntime().maxMemory() / 1048576);
|
logger.info("Max Memory: {} Mb", Runtime.getRuntime()
|
||||||
logger.info("Total Memory: {} Mb", Runtime.getRuntime().totalMemory() / 1048576);
|
.maxMemory() / 1048576);
|
||||||
logger.info("Free Memory: {} Mb", Runtime.getRuntime().freeMemory() / 1048576);
|
logger.info("Total Memory: {} Mb", Runtime.getRuntime()
|
||||||
|
.totalMemory() / 1048576);
|
||||||
|
logger.info("Free Memory: {} Mb", Runtime.getRuntime()
|
||||||
|
.freeMemory() / 1048576);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -13,7 +13,6 @@ public class JavaRandomUnitTest {
|
||||||
|
|
||||||
private static final Logger LOG = LoggerFactory.getLogger(JavaRandomUnitTest.class);
|
private static final Logger LOG = LoggerFactory.getLogger(JavaRandomUnitTest.class);
|
||||||
|
|
||||||
|
|
||||||
// tests - random long
|
// tests - random long
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -25,7 +24,8 @@ public class JavaRandomUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenUsingApacheCommons_whenGeneratingRandomLongUnbounded_thenCorrect() {
|
public void givenUsingApacheCommons_whenGeneratingRandomLongUnbounded_thenCorrect() {
|
||||||
final long generatedLong = new RandomDataGenerator().getRandomGenerator().nextLong();
|
final long generatedLong = new RandomDataGenerator().getRandomGenerator()
|
||||||
|
.nextLong();
|
||||||
|
|
||||||
LOG.debug("{}", generatedLong);
|
LOG.debug("{}", generatedLong);
|
||||||
}
|
}
|
||||||
|
@ -68,7 +68,8 @@ public class JavaRandomUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenUsingApache_whenGeneratingRandomIntegerUnbounded_thenCorrect() {
|
public void givenUsingApache_whenGeneratingRandomIntegerUnbounded_thenCorrect() {
|
||||||
final Integer generatedInteger = new RandomDataGenerator().getRandomGenerator().nextInt();
|
final Integer generatedInteger = new RandomDataGenerator().getRandomGenerator()
|
||||||
|
.nextInt();
|
||||||
|
|
||||||
LOG.debug("{}", generatedInteger);
|
LOG.debug("{}", generatedInteger);
|
||||||
}
|
}
|
||||||
|
@ -93,7 +94,8 @@ public class JavaRandomUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenUsingApache_whenGeneratingRandomFloatUnbounded_thenCorrect() {
|
public void givenUsingApache_whenGeneratingRandomFloatUnbounded_thenCorrect() {
|
||||||
final float generatedFloat = new RandomDataGenerator().getRandomGenerator().nextFloat();
|
final float generatedFloat = new RandomDataGenerator().getRandomGenerator()
|
||||||
|
.nextFloat();
|
||||||
|
|
||||||
LOG.debug("{}", generatedFloat);
|
LOG.debug("{}", generatedFloat);
|
||||||
}
|
}
|
||||||
|
@ -111,7 +113,8 @@ public class JavaRandomUnitTest {
|
||||||
public void givenUsingApache_whenGeneratingRandomFloatBounded_thenCorrect() {
|
public void givenUsingApache_whenGeneratingRandomFloatBounded_thenCorrect() {
|
||||||
final float leftLimit = 1F;
|
final float leftLimit = 1F;
|
||||||
final float rightLimit = 10F;
|
final float rightLimit = 10F;
|
||||||
final float randomFloat = new RandomDataGenerator().getRandomGenerator().nextFloat();
|
final float randomFloat = new RandomDataGenerator().getRandomGenerator()
|
||||||
|
.nextFloat();
|
||||||
final float generatedFloat = leftLimit + randomFloat * (rightLimit - leftLimit);
|
final float generatedFloat = leftLimit + randomFloat * (rightLimit - leftLimit);
|
||||||
|
|
||||||
LOG.debug("{}", generatedFloat);
|
LOG.debug("{}", generatedFloat);
|
||||||
|
@ -128,7 +131,8 @@ public class JavaRandomUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenUsingApache_whenGeneratingRandomDoubleUnbounded_thenCorrect() {
|
public void givenUsingApache_whenGeneratingRandomDoubleUnbounded_thenCorrect() {
|
||||||
final double generatedDouble = new RandomDataGenerator().getRandomGenerator().nextDouble();
|
final double generatedDouble = new RandomDataGenerator().getRandomGenerator()
|
||||||
|
.nextDouble();
|
||||||
|
|
||||||
LOG.debug("{}", generatedDouble);
|
LOG.debug("{}", generatedDouble);
|
||||||
}
|
}
|
||||||
|
|
|
@ -15,7 +15,6 @@ public class JavaTimerLongRunningUnitTest {
|
||||||
|
|
||||||
private static final Logger LOG = LoggerFactory.getLogger(JavaTimerLongRunningUnitTest.class);
|
private static final Logger LOG = LoggerFactory.getLogger(JavaTimerLongRunningUnitTest.class);
|
||||||
|
|
||||||
|
|
||||||
// tests
|
// tests
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -23,7 +22,8 @@ public class JavaTimerLongRunningUnitTest {
|
||||||
final TimerTask timerTask = new TimerTask() {
|
final TimerTask timerTask = new TimerTask() {
|
||||||
@Override
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
LOG.debug("Task performed on: " + new Date() + "\n" + "Thread's name: " + Thread.currentThread().getName());
|
LOG.debug("Task performed on: " + new Date() + "\n" + "Thread's name: " + Thread.currentThread()
|
||||||
|
.getName());
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
final Timer timer = new Timer("Timer");
|
final Timer timer = new Timer("Timer");
|
||||||
|
|
|
@ -38,7 +38,8 @@ public class Employee implements Comparable {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean equals(Object obj) {
|
public boolean equals(Object obj) {
|
||||||
return ((Employee) obj).getName().equals(getName());
|
return ((Employee) obj).getName()
|
||||||
|
.equals(getName());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
@ -49,7 +50,13 @@ public class Employee implements Comparable {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
return new StringBuffer().append("(").append(getName()).append(getAge()).append(",").append(getSalary()).append(")").toString();
|
return new StringBuffer().append("(")
|
||||||
|
.append(getName())
|
||||||
|
.append(getAge())
|
||||||
|
.append(",")
|
||||||
|
.append(getSalary())
|
||||||
|
.append(")")
|
||||||
|
.toString();
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -113,7 +113,8 @@ public class JavaSortingUnitTest {
|
||||||
sortedMap.put(entry.getKey(), entry.getValue());
|
sortedMap.put(entry.getKey(), entry.getValue());
|
||||||
}
|
}
|
||||||
|
|
||||||
assertTrue(Arrays.equals(sortedMap.keySet().toArray(), sortedKeys));
|
assertTrue(Arrays.equals(sortedMap.keySet()
|
||||||
|
.toArray(), sortedKeys));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -127,7 +128,8 @@ public class JavaSortingUnitTest {
|
||||||
sortedMap.put(entry.getKey(), entry.getValue());
|
sortedMap.put(entry.getKey(), entry.getValue());
|
||||||
}
|
}
|
||||||
|
|
||||||
assertTrue(Arrays.equals(sortedMap.values().toArray(), sortedValues));
|
assertTrue(Arrays.equals(sortedMap.values()
|
||||||
|
.toArray(), sortedValues));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
|
|
@ -14,6 +14,12 @@ public class BookControllerFeignClientBuilder {
|
||||||
private BookClient bookClient = createClient(BookClient.class, "http://localhost:8081/api/books");
|
private BookClient bookClient = createClient(BookClient.class, "http://localhost:8081/api/books");
|
||||||
|
|
||||||
private static <T> T createClient(Class<T> type, String uri) {
|
private static <T> T createClient(Class<T> type, String uri) {
|
||||||
return Feign.builder().client(new OkHttpClient()).encoder(new GsonEncoder()).decoder(new GsonDecoder()).logger(new Slf4jLogger(type)).logLevel(Logger.Level.FULL).target(type, uri);
|
return Feign.builder()
|
||||||
|
.client(new OkHttpClient())
|
||||||
|
.encoder(new GsonEncoder())
|
||||||
|
.decoder(new GsonDecoder())
|
||||||
|
.logger(new Slf4jLogger(type))
|
||||||
|
.logLevel(Logger.Level.FULL)
|
||||||
|
.target(type, uri);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -34,25 +34,31 @@ public class BookClientLiveTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenBookClient_shouldRunSuccessfully() throws Exception {
|
public void givenBookClient_shouldRunSuccessfully() throws Exception {
|
||||||
List<Book> books = bookClient.findAll().stream().map(BookResource::getBook).collect(Collectors.toList());
|
List<Book> books = bookClient.findAll()
|
||||||
|
.stream()
|
||||||
|
.map(BookResource::getBook)
|
||||||
|
.collect(Collectors.toList());
|
||||||
assertTrue(books.size() > 2);
|
assertTrue(books.size() > 2);
|
||||||
log.info("{}", books);
|
log.info("{}", books);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenBookClient_shouldFindOneBook() throws Exception {
|
public void givenBookClient_shouldFindOneBook() throws Exception {
|
||||||
Book book = bookClient.findByIsbn("0151072558").getBook();
|
Book book = bookClient.findByIsbn("0151072558")
|
||||||
|
.getBook();
|
||||||
assertThat(book.getAuthor(), containsString("Orwell"));
|
assertThat(book.getAuthor(), containsString("Orwell"));
|
||||||
log.info("{}", book);
|
log.info("{}", book);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenBookClient_shouldPostBook() throws Exception {
|
public void givenBookClient_shouldPostBook() throws Exception {
|
||||||
String isbn = UUID.randomUUID().toString();
|
String isbn = UUID.randomUUID()
|
||||||
|
.toString();
|
||||||
Book book = new Book(isbn, "Me", "It's me!", null, null);
|
Book book = new Book(isbn, "Me", "It's me!", null, null);
|
||||||
bookClient.create(book);
|
bookClient.create(book);
|
||||||
|
|
||||||
book = bookClient.findByIsbn(isbn).getBook();
|
book = bookClient.findByIsbn(isbn)
|
||||||
|
.getBook();
|
||||||
assertThat(book.getAuthor(), is("Me"));
|
assertThat(book.getAuthor(), is("Me"));
|
||||||
log.info("{}", book);
|
log.info("{}", book);
|
||||||
}
|
}
|
||||||
|
|
|
@ -9,7 +9,8 @@ public class Author extends Person {
|
||||||
|
|
||||||
List<Item> items = new ArrayList<>();
|
List<Item> items = new ArrayList<>();
|
||||||
|
|
||||||
public Author(){}
|
public Author() {
|
||||||
|
}
|
||||||
|
|
||||||
public Author(String firstName, String lastName) {
|
public Author(String firstName, String lastName) {
|
||||||
super(firstName, lastName);
|
super(firstName, lastName);
|
||||||
|
|
|
@ -11,7 +11,7 @@ public class Person {
|
||||||
private String firstName;
|
private String firstName;
|
||||||
private String lastName;
|
private String lastName;
|
||||||
|
|
||||||
public Person(){
|
public Person() {
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -1,6 +1,5 @@
|
||||||
package com.baeldung.jackson.deserialization.jsoncreator;
|
package com.baeldung.jackson.deserialization.jsoncreator;
|
||||||
|
|
||||||
|
|
||||||
import com.baeldung.jackson.domain.Person;
|
import com.baeldung.jackson.domain.Person;
|
||||||
import com.baeldung.jackson.domain.Item;
|
import com.baeldung.jackson.domain.Item;
|
||||||
import com.fasterxml.jackson.annotation.JsonCreator;
|
import com.fasterxml.jackson.annotation.JsonCreator;
|
||||||
|
@ -14,9 +13,7 @@ public class Author extends Person {
|
||||||
List<Item> items = new ArrayList<>();
|
List<Item> items = new ArrayList<>();
|
||||||
|
|
||||||
@JsonCreator
|
@JsonCreator
|
||||||
public Author(
|
public Author(@JsonProperty("christianName") String firstName, @JsonProperty("surname") String lastName) {
|
||||||
@JsonProperty("christianName") String firstName,
|
|
||||||
@JsonProperty("surname") String lastName) {
|
|
||||||
super(firstName, lastName);
|
super(firstName, lastName);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -13,7 +13,8 @@ public class Book extends Item {
|
||||||
private Date published;
|
private Date published;
|
||||||
private BigDecimal pages;
|
private BigDecimal pages;
|
||||||
|
|
||||||
public Book() {}
|
public Book() {
|
||||||
|
}
|
||||||
|
|
||||||
public Book(String title, Author author) {
|
public Book(String title, Author author) {
|
||||||
super(title, author);
|
super(title, author);
|
||||||
|
|
|
@ -11,8 +11,7 @@ import java.util.Date;
|
||||||
|
|
||||||
public class CustomDateDeserializer extends StdDeserializer<Date> {
|
public class CustomDateDeserializer extends StdDeserializer<Date> {
|
||||||
|
|
||||||
private static SimpleDateFormat formatter =
|
private static SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
|
||||||
new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
|
|
||||||
|
|
||||||
public CustomDateDeserializer() {
|
public CustomDateDeserializer() {
|
||||||
this(null);
|
this(null);
|
||||||
|
@ -23,8 +22,7 @@ public class CustomDateDeserializer extends StdDeserializer<Date> {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Date deserialize(JsonParser jsonparser, DeserializationContext context)
|
public Date deserialize(JsonParser jsonparser, DeserializationContext context) throws IOException {
|
||||||
throws IOException {
|
|
||||||
String date = jsonparser.getText();
|
String date = jsonparser.getText();
|
||||||
try {
|
try {
|
||||||
return formatter.parse(date);
|
return formatter.parse(date);
|
||||||
|
|
|
@ -19,7 +19,8 @@ public class Item {
|
||||||
private List<Person> authors = new ArrayList<>();
|
private List<Person> authors = new ArrayList<>();
|
||||||
private float price;
|
private float price;
|
||||||
|
|
||||||
public Item(){}
|
public Item() {
|
||||||
|
}
|
||||||
|
|
||||||
public Item(String title, Author author) {
|
public Item(String title, Author author) {
|
||||||
this.id = UUID.randomUUID();
|
this.id = UUID.randomUUID();
|
||||||
|
|
|
@ -18,7 +18,8 @@ public class Author extends Person {
|
||||||
|
|
||||||
private List<Item> items = new ArrayList<>();
|
private List<Item> items = new ArrayList<>();
|
||||||
|
|
||||||
public Author(){}
|
public Author() {
|
||||||
|
}
|
||||||
|
|
||||||
public Author(String firstName, String lastName) {
|
public Author(String firstName, String lastName) {
|
||||||
super(firstName, lastName);
|
super(firstName, lastName);
|
||||||
|
|
|
@ -15,7 +15,7 @@ public class Book extends Item {
|
||||||
private Date published;
|
private Date published;
|
||||||
private BigDecimal pages;
|
private BigDecimal pages;
|
||||||
|
|
||||||
public Book(){
|
public Book() {
|
||||||
}
|
}
|
||||||
|
|
||||||
public Book(String title, Author author) {
|
public Book(String title, Author author) {
|
||||||
|
|
|
@ -10,7 +10,9 @@ import java.util.List;
|
||||||
*/
|
*/
|
||||||
public class Course extends Item {
|
public class Course extends Item {
|
||||||
|
|
||||||
public enum Medium {CLASSROOM, ONLINE}
|
public enum Medium {
|
||||||
|
CLASSROOM, ONLINE
|
||||||
|
}
|
||||||
|
|
||||||
public enum Level {
|
public enum Level {
|
||||||
BEGINNER("Beginner", 1), INTERMEDIATE("Intermediate", 2), ADVANCED("Advanced", 3);
|
BEGINNER("Beginner", 1), INTERMEDIATE("Intermediate", 2), ADVANCED("Advanced", 3);
|
||||||
|
|
|
@ -17,7 +17,8 @@ public class Item {
|
||||||
private List<Person> authors = new ArrayList<>();
|
private List<Person> authors = new ArrayList<>();
|
||||||
private float price;
|
private float price;
|
||||||
|
|
||||||
public Item(){}
|
public Item() {
|
||||||
|
}
|
||||||
|
|
||||||
public Item(String title, Author author) {
|
public Item(String title, Author author) {
|
||||||
this.id = UUID.randomUUID();
|
this.id = UUID.randomUUID();
|
||||||
|
|
|
@ -14,7 +14,8 @@ public class Person {
|
||||||
private String firstName;
|
private String firstName;
|
||||||
private String lastName;
|
private String lastName;
|
||||||
|
|
||||||
public Person(){}
|
public Person() {
|
||||||
|
}
|
||||||
|
|
||||||
public Person(String firstName, String lastName) {
|
public Person(String firstName, String lastName) {
|
||||||
this.id = UUID.randomUUID();
|
this.id = UUID.randomUUID();
|
||||||
|
|
|
@ -9,16 +9,16 @@ import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||||
|
|
||||||
public class ClassWithAMap {
|
public class ClassWithAMap {
|
||||||
|
|
||||||
@JsonProperty("map")
|
@JsonProperty("map")
|
||||||
@JsonDeserialize(keyUsing = MyPairDeserializer.class)
|
@JsonDeserialize(keyUsing = MyPairDeserializer.class)
|
||||||
private final Map<MyPair, String> map;
|
private final Map<MyPair, String> map;
|
||||||
|
|
||||||
@JsonCreator
|
@JsonCreator
|
||||||
public ClassWithAMap(Map<MyPair, String> map) {
|
public ClassWithAMap(Map<MyPair, String> map) {
|
||||||
this.map = map;
|
this.map = map;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Map<MyPair, String> getMap() {
|
public Map<MyPair, String> getMap() {
|
||||||
return map;
|
return map;
|
||||||
}
|
}
|
||||||
}
|
}
|
|
@ -4,77 +4,77 @@ import com.fasterxml.jackson.annotation.JsonValue;
|
||||||
|
|
||||||
public class MyPair {
|
public class MyPair {
|
||||||
|
|
||||||
private String first;
|
private String first;
|
||||||
private String second;
|
private String second;
|
||||||
|
|
||||||
public MyPair(String first, String second) {
|
public MyPair(String first, String second) {
|
||||||
this.first = first;
|
this.first = first;
|
||||||
this.second = second;
|
this.second = second;
|
||||||
}
|
}
|
||||||
|
|
||||||
public MyPair(String both) {
|
public MyPair(String both) {
|
||||||
String[] pairs = both.split("and");
|
String[] pairs = both.split("and");
|
||||||
this.first = pairs[0].trim();
|
this.first = pairs[0].trim();
|
||||||
this.second = pairs[1].trim();
|
this.second = pairs[1].trim();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@JsonValue
|
@JsonValue
|
||||||
public String toString() {
|
public String toString() {
|
||||||
return first + " and " + second;
|
return first + " and " + second;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public int hashCode() {
|
public int hashCode() {
|
||||||
final int prime = 31;
|
final int prime = 31;
|
||||||
int result = 1;
|
int result = 1;
|
||||||
result = prime * result + ((first == null) ? 0 : first.hashCode());
|
result = prime * result + ((first == null) ? 0 : first.hashCode());
|
||||||
result = prime * result + ((second == null) ? 0 : second.hashCode());
|
result = prime * result + ((second == null) ? 0 : second.hashCode());
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean equals(Object obj) {
|
public boolean equals(Object obj) {
|
||||||
if (this == obj) {
|
if (this == obj) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
if (obj == null) {
|
if (obj == null) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
if (!(obj instanceof MyPair)) {
|
if (!(obj instanceof MyPair)) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
MyPair other = (MyPair) obj;
|
MyPair other = (MyPair) obj;
|
||||||
if (first == null) {
|
if (first == null) {
|
||||||
if (other.first != null) {
|
if (other.first != null) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
} else if (!first.equals(other.first)) {
|
} else if (!first.equals(other.first)) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
if (second == null) {
|
if (second == null) {
|
||||||
if (other.second != null) {
|
if (other.second != null) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
} else if (!second.equals(other.second)) {
|
} else if (!second.equals(other.second)) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getFirst() {
|
public String getFirst() {
|
||||||
return first;
|
return first;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setFirst(String first) {
|
public void setFirst(String first) {
|
||||||
this.first = first;
|
this.first = first;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getSecond() {
|
public String getSecond() {
|
||||||
return second;
|
return second;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setSecond(String second) {
|
public void setSecond(String second) {
|
||||||
this.second = second;
|
this.second = second;
|
||||||
}
|
}
|
||||||
}
|
}
|
|
@ -13,28 +13,25 @@ public class User extends Person {
|
||||||
private String firstName;
|
private String firstName;
|
||||||
private String lastName;
|
private String lastName;
|
||||||
|
|
||||||
@JsonFormat(shape = JsonFormat.Shape.STRING,
|
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd@HH:mm:ss.SSSZ")
|
||||||
pattern = "yyyy-MM-dd@HH:mm:ss.SSSZ")
|
|
||||||
private Date createdDate;
|
private Date createdDate;
|
||||||
|
|
||||||
public User(String firstName,String lastName) {
|
public User(String firstName, String lastName) {
|
||||||
super(firstName, lastName);
|
super(firstName, lastName);
|
||||||
this.createdDate = new Date();
|
this.createdDate = new Date();
|
||||||
}
|
}
|
||||||
|
|
||||||
public Date getCreatedDate() {
|
public Date getCreatedDate() {
|
||||||
return createdDate;
|
return createdDate;
|
||||||
}
|
}
|
||||||
|
|
||||||
@JsonFormat(shape = JsonFormat.Shape.STRING,
|
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd@HH:mm:ss.SSSZ", locale = "en_GB")
|
||||||
pattern = "yyyy-MM-dd@HH:mm:ss.SSSZ",
|
|
||||||
locale = "en_GB")
|
|
||||||
public Date getCurrentDate() {
|
public Date getCurrentDate() {
|
||||||
return new Date();
|
return new Date();
|
||||||
}
|
}
|
||||||
|
|
||||||
@JsonFormat(shape = JsonFormat.Shape.NUMBER)
|
@JsonFormat(shape = JsonFormat.Shape.NUMBER)
|
||||||
public Date getDateNum() {
|
public Date getDateNum() {
|
||||||
return new Date();
|
return new Date();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -17,7 +17,8 @@ public class Person {
|
||||||
private String firstName;
|
private String firstName;
|
||||||
private String lastName;
|
private String lastName;
|
||||||
|
|
||||||
public Person(){}
|
public Person() {
|
||||||
|
}
|
||||||
|
|
||||||
public Person(String firstName, String lastName) {
|
public Person(String firstName, String lastName) {
|
||||||
this.id = UUID.randomUUID();
|
this.id = UUID.randomUUID();
|
||||||
|
|
|
@ -12,10 +12,12 @@ import java.util.List;
|
||||||
* @author Alex Theedom www.readlearncode.com
|
* @author Alex Theedom www.readlearncode.com
|
||||||
* @version 1.0
|
* @version 1.0
|
||||||
*/
|
*/
|
||||||
@JsonIgnoreProperties({"medium"})
|
@JsonIgnoreProperties({ "medium" })
|
||||||
public class Course extends Item {
|
public class Course extends Item {
|
||||||
|
|
||||||
public enum Medium {CLASSROOM, ONLINE}
|
public enum Medium {
|
||||||
|
CLASSROOM, ONLINE
|
||||||
|
}
|
||||||
|
|
||||||
public enum Level {
|
public enum Level {
|
||||||
BEGINNER("Beginner", 1), INTERMEDIATE("Intermediate", 2), ADVANCED("Advanced", 3);
|
BEGINNER("Beginner", 1), INTERMEDIATE("Intermediate", 2), ADVANCED("Advanced", 3);
|
||||||
|
|
|
@ -12,10 +12,7 @@ public class ItemIdAddedToUser extends Event {
|
||||||
private final Long quantity;
|
private final Long quantity;
|
||||||
|
|
||||||
@JsonCreator
|
@JsonCreator
|
||||||
public ItemIdAddedToUser(@JsonProperty("id") String id,
|
public ItemIdAddedToUser(@JsonProperty("id") String id, @JsonProperty("timestamp") Long timestamp, @JsonProperty("itemId") String itemId, @JsonProperty("quantity") Long quantity) {
|
||||||
@JsonProperty("timestamp") Long timestamp,
|
|
||||||
@JsonProperty("itemId") String itemId,
|
|
||||||
@JsonProperty("quantity") Long quantity) {
|
|
||||||
super(id, timestamp);
|
super(id, timestamp);
|
||||||
this.itemId = itemId;
|
this.itemId = itemId;
|
||||||
this.quantity = quantity;
|
this.quantity = quantity;
|
||||||
|
|
|
@ -10,10 +10,7 @@ public class ItemIdRemovedFromUser extends Event {
|
||||||
private final Long quantity;
|
private final Long quantity;
|
||||||
|
|
||||||
@JsonCreator
|
@JsonCreator
|
||||||
public ItemIdRemovedFromUser(@JsonProperty("id") String id,
|
public ItemIdRemovedFromUser(@JsonProperty("id") String id, @JsonProperty("timestamp") Long timestamp, @JsonProperty("itemId") String itemId, @JsonProperty("quantity") Long quantity) {
|
||||||
@JsonProperty("timestamp") Long timestamp,
|
|
||||||
@JsonProperty("itemId") String itemId,
|
|
||||||
@JsonProperty("quantity") Long quantity) {
|
|
||||||
super(id, timestamp);
|
super(id, timestamp);
|
||||||
this.itemId = itemId;
|
this.itemId = itemId;
|
||||||
this.quantity = quantity;
|
this.quantity = quantity;
|
||||||
|
|
|
@ -13,7 +13,9 @@ import java.util.List;
|
||||||
@CustomCourseAnnotation
|
@CustomCourseAnnotation
|
||||||
public class Course extends Item {
|
public class Course extends Item {
|
||||||
|
|
||||||
public enum Medium {CLASSROOM, ONLINE}
|
public enum Medium {
|
||||||
|
CLASSROOM, ONLINE
|
||||||
|
}
|
||||||
|
|
||||||
public enum Level {
|
public enum Level {
|
||||||
BEGINNER("Beginner", 1), INTERMEDIATE("Intermediate", 2), ADVANCED("Advanced", 3);
|
BEGINNER("Beginner", 1), INTERMEDIATE("Intermediate", 2), ADVANCED("Advanced", 3);
|
||||||
|
|
|
@ -14,7 +14,7 @@ import java.lang.annotation.RetentionPolicy;
|
||||||
@Retention(RetentionPolicy.RUNTIME)
|
@Retention(RetentionPolicy.RUNTIME)
|
||||||
@JacksonAnnotationsInside
|
@JacksonAnnotationsInside
|
||||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||||
@JsonPropertyOrder({"title", "price", "id", "duration", "authors", "level"})
|
@JsonPropertyOrder({ "title", "price", "id", "duration", "authors", "level" })
|
||||||
@JsonIgnoreProperties({"prerequisite"})
|
@JsonIgnoreProperties({ "prerequisite" })
|
||||||
public @interface CustomCourseAnnotation {
|
public @interface CustomCourseAnnotation {
|
||||||
}
|
}
|
||||||
|
|
|
@ -20,7 +20,8 @@ public class Item {
|
||||||
private List<Person> authors = new ArrayList<>();
|
private List<Person> authors = new ArrayList<>();
|
||||||
private float price;
|
private float price;
|
||||||
|
|
||||||
public Item(){}
|
public Item() {
|
||||||
|
}
|
||||||
|
|
||||||
public Item(String title, Author author) {
|
public Item(String title, Author author) {
|
||||||
this.id = UUID.randomUUID();
|
this.id = UUID.randomUUID();
|
||||||
|
|
|
@ -16,7 +16,7 @@ import java.util.List;
|
||||||
* @version 1.0
|
* @version 1.0
|
||||||
*/
|
*/
|
||||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||||
@JsonPropertyOrder({"lastName", "items", "firstName", "id"})
|
@JsonPropertyOrder({ "lastName", "items", "firstName", "id" })
|
||||||
public class Author extends Person {
|
public class Author extends Person {
|
||||||
|
|
||||||
@JsonIgnore
|
@JsonIgnore
|
||||||
|
|
|
@ -18,12 +18,8 @@ public class Order {
|
||||||
private Type type;
|
private Type type;
|
||||||
private int internalAudit;
|
private int internalAudit;
|
||||||
|
|
||||||
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME,
|
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "ordertype")
|
||||||
include = JsonTypeInfo.As.PROPERTY,
|
@JsonSubTypes({ @JsonSubTypes.Type(value = InternalType.class, name = "internal") })
|
||||||
property = "ordertype")
|
|
||||||
@JsonSubTypes({
|
|
||||||
@JsonSubTypes.Type(value = InternalType.class, name = "internal")
|
|
||||||
})
|
|
||||||
public static class Type {
|
public static class Type {
|
||||||
public long id;
|
public long id;
|
||||||
public String name;
|
public String name;
|
||||||
|
|
|
@ -24,8 +24,11 @@ public class ActorJacksonSerializer extends StdSerializer<ActorJackson> {
|
||||||
jsonGenerator.writeStartObject();
|
jsonGenerator.writeStartObject();
|
||||||
jsonGenerator.writeStringField("imdbId", actor.getImdbId());
|
jsonGenerator.writeStringField("imdbId", actor.getImdbId());
|
||||||
jsonGenerator.writeObjectField("dateOfBirth", actor.getDateOfBirth() != null ? sdf.format(actor.getDateOfBirth()) : null);
|
jsonGenerator.writeObjectField("dateOfBirth", actor.getDateOfBirth() != null ? sdf.format(actor.getDateOfBirth()) : null);
|
||||||
jsonGenerator.writeNumberField("N° Film: ", actor.getFilmography() != null ? actor.getFilmography().size() : null);
|
jsonGenerator.writeNumberField("N° Film: ", actor.getFilmography() != null ? actor.getFilmography()
|
||||||
jsonGenerator.writeStringField("filmography", actor.getFilmography().stream().collect(Collectors.joining("-")));
|
.size() : null);
|
||||||
|
jsonGenerator.writeStringField("filmography", actor.getFilmography()
|
||||||
|
.stream()
|
||||||
|
.collect(Collectors.joining("-")));
|
||||||
jsonGenerator.writeEndObject();
|
jsonGenerator.writeEndObject();
|
||||||
}
|
}
|
||||||
}
|
}
|
|
@ -9,10 +9,9 @@ import com.fasterxml.jackson.databind.KeyDeserializer;
|
||||||
|
|
||||||
public class MyPairDeserializer extends KeyDeserializer {
|
public class MyPairDeserializer extends KeyDeserializer {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public MyPair deserializeKey(String key, DeserializationContext ctxt)
|
public MyPair deserializeKey(String key, DeserializationContext ctxt) throws IOException, JsonProcessingException {
|
||||||
throws IOException, JsonProcessingException {
|
|
||||||
|
|
||||||
return new MyPair(key);
|
return new MyPair(key);
|
||||||
}
|
}
|
||||||
}
|
}
|
|
@ -12,14 +12,12 @@ import com.fasterxml.jackson.databind.SerializerProvider;
|
||||||
|
|
||||||
public class MyPairSerializer extends JsonSerializer<MyPair> {
|
public class MyPairSerializer extends JsonSerializer<MyPair> {
|
||||||
|
|
||||||
private final ObjectMapper mapper = new ObjectMapper();
|
private final ObjectMapper mapper = new ObjectMapper();
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void serialize(MyPair value, JsonGenerator gen,
|
public void serialize(MyPair value, JsonGenerator gen, SerializerProvider serializers) throws IOException, JsonProcessingException {
|
||||||
SerializerProvider serializers) throws IOException,
|
StringWriter writer = new StringWriter();
|
||||||
JsonProcessingException {
|
mapper.writeValue(writer, value);
|
||||||
StringWriter writer = new StringWriter();
|
gen.writeFieldName(writer.toString());
|
||||||
mapper.writeValue(writer, value);
|
}
|
||||||
gen.writeFieldName(writer.toString());
|
|
||||||
}
|
|
||||||
}
|
}
|
|
@ -1,6 +1,5 @@
|
||||||
package com.baeldung.jackson.serialization.jsongetter;
|
package com.baeldung.jackson.serialization.jsongetter;
|
||||||
|
|
||||||
|
|
||||||
import com.baeldung.jackson.domain.Item;
|
import com.baeldung.jackson.domain.Item;
|
||||||
import com.baeldung.jackson.domain.Person;
|
import com.baeldung.jackson.domain.Person;
|
||||||
import com.fasterxml.jackson.annotation.JsonGetter;
|
import com.fasterxml.jackson.annotation.JsonGetter;
|
||||||
|
|
|
@ -1,6 +1,5 @@
|
||||||
package com.baeldung.jackson.serialization.jsonpropertyorder;
|
package com.baeldung.jackson.serialization.jsonpropertyorder;
|
||||||
|
|
||||||
|
|
||||||
import com.baeldung.jackson.domain.Item;
|
import com.baeldung.jackson.domain.Item;
|
||||||
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
|
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
|
||||||
|
|
||||||
|
@ -13,7 +12,7 @@ import java.util.List;
|
||||||
* @author Alex Theedom www.readlearncode.com
|
* @author Alex Theedom www.readlearncode.com
|
||||||
* @version 1.0
|
* @version 1.0
|
||||||
*/
|
*/
|
||||||
@JsonPropertyOrder({"items", "firstName", "lastName", "id"})
|
@JsonPropertyOrder({ "items", "firstName", "lastName", "id" })
|
||||||
public class Author extends Person {
|
public class Author extends Person {
|
||||||
|
|
||||||
List<Item> items = new ArrayList<>();
|
List<Item> items = new ArrayList<>();
|
||||||
|
|
|
@ -19,7 +19,8 @@ public class Book extends Item {
|
||||||
private Date published;
|
private Date published;
|
||||||
private BigDecimal pages;
|
private BigDecimal pages;
|
||||||
|
|
||||||
public Book(){}
|
public Book() {
|
||||||
|
}
|
||||||
|
|
||||||
public Book(String title, Author author) {
|
public Book(String title, Author author) {
|
||||||
super(title, author);
|
super(title, author);
|
||||||
|
|
|
@ -17,8 +17,7 @@ import java.util.Date;
|
||||||
*/
|
*/
|
||||||
public class CustomDateSerializer extends StdSerializer<Date> {
|
public class CustomDateSerializer extends StdSerializer<Date> {
|
||||||
|
|
||||||
private static SimpleDateFormat formatter =
|
private static SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
|
||||||
new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
|
|
||||||
|
|
||||||
public CustomDateSerializer() {
|
public CustomDateSerializer() {
|
||||||
this(null);
|
this(null);
|
||||||
|
@ -29,8 +28,7 @@ public class CustomDateSerializer extends StdSerializer<Date> {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void serialize(Date value, JsonGenerator gen, SerializerProvider arg2)
|
public void serialize(Date value, JsonGenerator gen, SerializerProvider arg2) throws IOException, JsonProcessingException {
|
||||||
throws IOException, JsonProcessingException {
|
|
||||||
gen.writeString(formatter.format(value));
|
gen.writeString(formatter.format(value));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -19,7 +19,8 @@ public class Item {
|
||||||
private List<Person> authors = new ArrayList<>();
|
private List<Person> authors = new ArrayList<>();
|
||||||
private float price;
|
private float price;
|
||||||
|
|
||||||
public Item(){}
|
public Item() {
|
||||||
|
}
|
||||||
|
|
||||||
public Item(String title, Author author) {
|
public Item(String title, Author author) {
|
||||||
this.id = UUID.randomUUID();
|
this.id = UUID.randomUUID();
|
||||||
|
|
|
@ -14,7 +14,9 @@ import java.util.List;
|
||||||
*/
|
*/
|
||||||
public class Course extends Item {
|
public class Course extends Item {
|
||||||
|
|
||||||
public enum Medium {CLASSROOM, ONLINE}
|
public enum Medium {
|
||||||
|
CLASSROOM, ONLINE
|
||||||
|
}
|
||||||
|
|
||||||
public enum Level {
|
public enum Level {
|
||||||
BEGINNER("Beginner", 1), INTERMEDIATE("Intermediate", 2), ADVANCED("Advanced", 3);
|
BEGINNER("Beginner", 1), INTERMEDIATE("Intermediate", 2), ADVANCED("Advanced", 3);
|
||||||
|
|
|
@ -47,7 +47,8 @@ public class ExtraAnnotationUnitTest {
|
||||||
ObjectMapper mapper = new ObjectMapper();
|
ObjectMapper mapper = new ObjectMapper();
|
||||||
|
|
||||||
BeanWithoutAppend bean = new BeanWithoutAppend(2, "Bean Without Append Annotation");
|
BeanWithoutAppend bean = new BeanWithoutAppend(2, "Bean Without Append Annotation");
|
||||||
ObjectWriter writer = mapper.writerFor(BeanWithoutAppend.class).withAttribute("version", "1.0");
|
ObjectWriter writer = mapper.writerFor(BeanWithoutAppend.class)
|
||||||
|
.withAttribute("version", "1.0");
|
||||||
String jsonString = writer.writeValueAsString(bean);
|
String jsonString = writer.writeValueAsString(bean);
|
||||||
|
|
||||||
assertThat(jsonString, not(containsString("version")));
|
assertThat(jsonString, not(containsString("version")));
|
||||||
|
@ -59,7 +60,8 @@ public class ExtraAnnotationUnitTest {
|
||||||
ObjectMapper mapper = new ObjectMapper();
|
ObjectMapper mapper = new ObjectMapper();
|
||||||
|
|
||||||
BeanWithAppend bean = new BeanWithAppend(2, "Bean With Append Annotation");
|
BeanWithAppend bean = new BeanWithAppend(2, "Bean With Append Annotation");
|
||||||
ObjectWriter writer = mapper.writerFor(BeanWithAppend.class).withAttribute("version", "1.0");
|
ObjectWriter writer = mapper.writerFor(BeanWithAppend.class)
|
||||||
|
.withAttribute("version", "1.0");
|
||||||
String jsonString = writer.writeValueAsString(bean);
|
String jsonString = writer.writeValueAsString(bean);
|
||||||
|
|
||||||
assertThat(jsonString, containsString("version"));
|
assertThat(jsonString, containsString("version"));
|
||||||
|
|
|
@ -4,7 +4,6 @@ import com.fasterxml.jackson.annotation.JsonIdentityInfo;
|
||||||
import com.fasterxml.jackson.annotation.JsonIdentityReference;
|
import com.fasterxml.jackson.annotation.JsonIdentityReference;
|
||||||
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
|
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
|
||||||
|
|
||||||
|
|
||||||
public class IdentityReferenceBeans {
|
public class IdentityReferenceBeans {
|
||||||
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
|
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
|
||||||
public static class BeanWithoutIdentityReference {
|
public static class BeanWithoutIdentityReference {
|
||||||
|
|
|
@ -20,6 +20,7 @@ public class CustomListSerializer extends StdSerializer<List<ItemWithSerializer>
|
||||||
public CustomListSerializer(final Class<List<ItemWithSerializer>> t) {
|
public CustomListSerializer(final Class<List<ItemWithSerializer>> t) {
|
||||||
super(t);
|
super(t);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void serialize(final List<ItemWithSerializer> items, final JsonGenerator generator, final SerializerProvider provider) throws IOException, JsonProcessingException {
|
public void serialize(final List<ItemWithSerializer> items, final JsonGenerator generator, final SerializerProvider provider) throws IOException, JsonProcessingException {
|
||||||
final List<Integer> ids = new ArrayList<Integer>();
|
final List<Integer> ids = new ArrayList<Integer>();
|
||||||
|
|
|
@ -11,7 +11,6 @@ import com.fasterxml.jackson.databind.ser.std.StdSerializer;
|
||||||
|
|
||||||
public class CustomLocalDateTimeSerializer extends StdSerializer<LocalDateTime> {
|
public class CustomLocalDateTimeSerializer extends StdSerializer<LocalDateTime> {
|
||||||
|
|
||||||
|
|
||||||
private static final long serialVersionUID = -7449444168934819290L;
|
private static final long serialVersionUID = -7449444168934819290L;
|
||||||
private static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
|
private static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
|
||||||
|
|
||||||
|
|
|
@ -28,9 +28,11 @@ public class ItemDeserializer extends StdDeserializer<Item> {
|
||||||
*/
|
*/
|
||||||
@Override
|
@Override
|
||||||
public Item deserialize(final JsonParser jp, final DeserializationContext ctxt) throws IOException, JsonProcessingException {
|
public Item deserialize(final JsonParser jp, final DeserializationContext ctxt) throws IOException, JsonProcessingException {
|
||||||
final JsonNode node = jp.getCodec().readTree(jp);
|
final JsonNode node = jp.getCodec()
|
||||||
|
.readTree(jp);
|
||||||
final int id = (Integer) ((IntNode) node.get("id")).numberValue();
|
final int id = (Integer) ((IntNode) node.get("id")).numberValue();
|
||||||
final String itemName = node.get("itemName").asText();
|
final String itemName = node.get("itemName")
|
||||||
|
.asText();
|
||||||
final int userId = (Integer) ((IntNode) node.get("createdBy")).numberValue();
|
final int userId = (Integer) ((IntNode) node.get("createdBy")).numberValue();
|
||||||
|
|
||||||
return new Item(id, itemName, new User(userId, null));
|
return new Item(id, itemName, new User(userId, null));
|
||||||
|
|
|
@ -28,9 +28,11 @@ public class ItemDeserializerOnClass extends StdDeserializer<ItemWithSerializer>
|
||||||
*/
|
*/
|
||||||
@Override
|
@Override
|
||||||
public ItemWithSerializer deserialize(final JsonParser jp, final DeserializationContext ctxt) throws IOException, JsonProcessingException {
|
public ItemWithSerializer deserialize(final JsonParser jp, final DeserializationContext ctxt) throws IOException, JsonProcessingException {
|
||||||
final JsonNode node = jp.getCodec().readTree(jp);
|
final JsonNode node = jp.getCodec()
|
||||||
|
.readTree(jp);
|
||||||
final int id = (Integer) ((IntNode) node.get("id")).numberValue();
|
final int id = (Integer) ((IntNode) node.get("id")).numberValue();
|
||||||
final String itemName = node.get("itemName").asText();
|
final String itemName = node.get("itemName")
|
||||||
|
.asText();
|
||||||
final int userId = (Integer) ((IntNode) node.get("owner")).numberValue();
|
final int userId = (Integer) ((IntNode) node.get("owner")).numberValue();
|
||||||
|
|
||||||
return new ItemWithSerializer(id, itemName, new User(userId, null));
|
return new ItemWithSerializer(id, itemName, new User(userId, null));
|
||||||
|
|
|
@ -16,54 +16,49 @@ import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
|
||||||
public class JacksonMapDeserializeUnitTest {
|
public class JacksonMapDeserializeUnitTest {
|
||||||
|
|
||||||
private Map<MyPair, String> map;
|
private Map<MyPair, String> map;
|
||||||
private Map<MyPair, MyPair> cmap;
|
private Map<MyPair, MyPair> cmap;
|
||||||
final ObjectMapper mapper = new ObjectMapper();
|
final ObjectMapper mapper = new ObjectMapper();
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenSimpleMapDeserialize_thenCorrect()
|
public void whenSimpleMapDeserialize_thenCorrect() throws JsonParseException, JsonMappingException, IOException {
|
||||||
throws JsonParseException, JsonMappingException, IOException {
|
|
||||||
|
|
||||||
final String jsonInput = "{\"key\": \"value\"}";
|
final String jsonInput = "{\"key\": \"value\"}";
|
||||||
TypeReference<HashMap<String, String>> typeRef = new TypeReference<HashMap<String, String>>() {
|
TypeReference<HashMap<String, String>> typeRef = new TypeReference<HashMap<String, String>>() {
|
||||||
};
|
};
|
||||||
|
|
||||||
final Map<String, String> map = mapper.readValue(jsonInput, typeRef);
|
final Map<String, String> map = mapper.readValue(jsonInput, typeRef);
|
||||||
|
|
||||||
Assert.assertEquals("value", map.get("key"));
|
Assert.assertEquals("value", map.get("key"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenObjectStringMapDeserialize_thenCorrect()
|
public void whenObjectStringMapDeserialize_thenCorrect() throws JsonParseException, JsonMappingException, IOException {
|
||||||
throws JsonParseException, JsonMappingException, IOException {
|
|
||||||
|
|
||||||
final String jsonInput = "{\"Abbott and Costello\":\"Comedy\"}";
|
final String jsonInput = "{\"Abbott and Costello\":\"Comedy\"}";
|
||||||
|
|
||||||
TypeReference<HashMap<MyPair, String>> typeRef = new TypeReference<HashMap<MyPair, String>>() {
|
TypeReference<HashMap<MyPair, String>> typeRef = new TypeReference<HashMap<MyPair, String>>() {
|
||||||
};
|
};
|
||||||
|
|
||||||
map = mapper.readValue(jsonInput, typeRef);
|
map = mapper.readValue(jsonInput, typeRef);
|
||||||
|
|
||||||
Assert.assertEquals("Comedy", map.get(new MyPair("Abbott", "Costello")));
|
Assert.assertEquals("Comedy", map.get(new MyPair("Abbott", "Costello")));
|
||||||
|
|
||||||
ClassWithAMap classWithMap = mapper.readValue(jsonInput,
|
ClassWithAMap classWithMap = mapper.readValue(jsonInput, ClassWithAMap.class);
|
||||||
ClassWithAMap.class);
|
|
||||||
|
|
||||||
Assert.assertEquals("Comedy",
|
Assert.assertEquals("Comedy", classWithMap.getMap()
|
||||||
classWithMap.getMap().get(new MyPair("Abbott", "Costello")));
|
.get(new MyPair("Abbott", "Costello")));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenObjectObjectMapDeserialize_thenCorrect()
|
public void whenObjectObjectMapDeserialize_thenCorrect() throws JsonParseException, JsonMappingException, IOException {
|
||||||
throws JsonParseException, JsonMappingException, IOException {
|
|
||||||
|
|
||||||
final String jsonInput = "{\"Abbott and Costello\" : \"Comedy and 1940s\"}";
|
final String jsonInput = "{\"Abbott and Costello\" : \"Comedy and 1940s\"}";
|
||||||
TypeReference<HashMap<MyPair, MyPair>> typeRef = new TypeReference<HashMap<MyPair, MyPair>>() {
|
TypeReference<HashMap<MyPair, MyPair>> typeRef = new TypeReference<HashMap<MyPair, MyPair>>() {
|
||||||
};
|
};
|
||||||
|
|
||||||
cmap = mapper.readValue(jsonInput, typeRef);
|
cmap = mapper.readValue(jsonInput, typeRef);
|
||||||
|
|
||||||
Assert.assertEquals(new MyPair("Comedy", "1940s"),
|
Assert.assertEquals(new MyPair("Comedy", "1940s"), cmap.get(new MyPair("Abbott", "Costello")));
|
||||||
cmap.get(new MyPair("Abbott", "Costello")));
|
}
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -27,7 +27,9 @@ public class JacksonInjectUnitTest {
|
||||||
|
|
||||||
// act
|
// act
|
||||||
InjectableValues inject = new InjectableValues.Std().addValue(UUID.class, id);
|
InjectableValues inject = new InjectableValues.Std().addValue(UUID.class, id);
|
||||||
Author author = new ObjectMapper().reader(inject).forType(Author.class).readValue(authorJson);
|
Author author = new ObjectMapper().reader(inject)
|
||||||
|
.forType(Author.class)
|
||||||
|
.readValue(authorJson);
|
||||||
|
|
||||||
// assert
|
// assert
|
||||||
assertThat(author.getId()).isEqualTo(id);
|
assertThat(author.getId()).isEqualTo(id);
|
||||||
|
|
|
@ -23,15 +23,28 @@ public class JsonAnySetterUnitTest {
|
||||||
String json = "{\"USA\":10.00,\"UK\":15.00,\"China\":23.00,\"Brazil\":12.00,\"France\":8.00,\"Russia\":18.00}";
|
String json = "{\"USA\":10.00,\"UK\":15.00,\"China\":23.00,\"Brazil\":12.00,\"France\":8.00,\"Russia\":18.00}";
|
||||||
|
|
||||||
// act
|
// act
|
||||||
Inventory inventory = new ObjectMapper().readerFor(Inventory.class).readValue(json);
|
Inventory inventory = new ObjectMapper().readerFor(Inventory.class)
|
||||||
|
.readValue(json);
|
||||||
|
|
||||||
// assert
|
// assert
|
||||||
assertThat(from(json).getMap(".").get("USA")).isEqualTo(inventory.getCountryDeliveryCost().get("USA"));
|
assertThat(from(json).getMap(".")
|
||||||
assertThat(from(json).getMap(".").get("UK")).isEqualTo(inventory.getCountryDeliveryCost().get("UK"));
|
.get("USA")).isEqualTo(inventory.getCountryDeliveryCost()
|
||||||
assertThat(from(json).getMap(".").get("China")).isEqualTo(inventory.getCountryDeliveryCost().get("China"));
|
.get("USA"));
|
||||||
assertThat(from(json).getMap(".").get("Brazil")).isEqualTo(inventory.getCountryDeliveryCost().get("Brazil"));
|
assertThat(from(json).getMap(".")
|
||||||
assertThat(from(json).getMap(".").get("France")).isEqualTo(inventory.getCountryDeliveryCost().get("France"));
|
.get("UK")).isEqualTo(inventory.getCountryDeliveryCost()
|
||||||
assertThat(from(json).getMap(".").get("Russia")).isEqualTo(inventory.getCountryDeliveryCost().get("Russia"));
|
.get("UK"));
|
||||||
|
assertThat(from(json).getMap(".")
|
||||||
|
.get("China")).isEqualTo(inventory.getCountryDeliveryCost()
|
||||||
|
.get("China"));
|
||||||
|
assertThat(from(json).getMap(".")
|
||||||
|
.get("Brazil")).isEqualTo(inventory.getCountryDeliveryCost()
|
||||||
|
.get("Brazil"));
|
||||||
|
assertThat(from(json).getMap(".")
|
||||||
|
.get("France")).isEqualTo(inventory.getCountryDeliveryCost()
|
||||||
|
.get("France"));
|
||||||
|
assertThat(from(json).getMap(".")
|
||||||
|
.get("Russia")).isEqualTo(inventory.getCountryDeliveryCost()
|
||||||
|
.get("Russia"));
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
|
@ -20,14 +20,11 @@ public class JsonCreatorUnitTest {
|
||||||
public void whenDeserializingUsingJsonCreator_thenCorrect() throws IOException {
|
public void whenDeserializingUsingJsonCreator_thenCorrect() throws IOException {
|
||||||
|
|
||||||
// arrange
|
// arrange
|
||||||
String authorJson =
|
String authorJson = "{" + " \"christianName\": \"Alex\"," + " \"surname\": \"Theedom\"" + "}";
|
||||||
"{" +
|
|
||||||
" \"christianName\": \"Alex\"," +
|
|
||||||
" \"surname\": \"Theedom\"" +
|
|
||||||
"}";
|
|
||||||
|
|
||||||
// act
|
// act
|
||||||
final Author author = new ObjectMapper().readerFor(Author.class).readValue(authorJson);
|
final Author author = new ObjectMapper().readerFor(Author.class)
|
||||||
|
.readValue(authorJson);
|
||||||
|
|
||||||
// assert
|
// assert
|
||||||
assertThat(from(authorJson).getString("christianName")).isEqualTo(author.getFirstName());
|
assertThat(from(authorJson).getString("christianName")).isEqualTo(author.getFirstName());
|
||||||
|
|
|
@ -24,7 +24,8 @@ public class JsonDeserializeUnitTest {
|
||||||
String bookJson = "{\"id\":\"957c43f2-fa2e-42f9-bf75-6e3d5bb6960a\",\"title\":\"Effective Java\",\"authors\":[{\"id\":\"9bcd817d-0141-42e6-8f04-e5aaab0980b6\",\"firstName\":\"Joshua\",\"lastName\":\"Bloch\"}],\"price\":0,\"published\":\"25-12-2017 13:30:25\",\"pages\":null,\"isbn\":null}";
|
String bookJson = "{\"id\":\"957c43f2-fa2e-42f9-bf75-6e3d5bb6960a\",\"title\":\"Effective Java\",\"authors\":[{\"id\":\"9bcd817d-0141-42e6-8f04-e5aaab0980b6\",\"firstName\":\"Joshua\",\"lastName\":\"Bloch\"}],\"price\":0,\"published\":\"25-12-2017 13:30:25\",\"pages\":null,\"isbn\":null}";
|
||||||
|
|
||||||
// act
|
// act
|
||||||
Book book = new ObjectMapper().readerFor(Book.class).readValue(bookJson);
|
Book book = new ObjectMapper().readerFor(Book.class)
|
||||||
|
.readValue(bookJson);
|
||||||
|
|
||||||
// assert
|
// assert
|
||||||
SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
|
SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
|
||||||
|
|
|
@ -23,10 +23,13 @@ public class JsonSetterUnitTest {
|
||||||
String json = "{\"firstName\":\"Alex\",\"lastName\":\"Theedom\",\"publications\":[{\"title\":\"Professional Java EE Design Patterns\"}]}";
|
String json = "{\"firstName\":\"Alex\",\"lastName\":\"Theedom\",\"publications\":[{\"title\":\"Professional Java EE Design Patterns\"}]}";
|
||||||
|
|
||||||
// act
|
// act
|
||||||
Author author = new ObjectMapper().readerFor(Author.class).readValue(json);
|
Author author = new ObjectMapper().readerFor(Author.class)
|
||||||
|
.readValue(json);
|
||||||
|
|
||||||
// assert
|
// assert
|
||||||
assertThat(from(json).getList("publications").size()).isEqualTo(author.getItems().size());
|
assertThat(from(json).getList("publications")
|
||||||
|
.size()).isEqualTo(author.getItems()
|
||||||
|
.size());
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
|
@ -1,6 +1,5 @@
|
||||||
package com.baeldung.jackson.dynamicIgnore;
|
package com.baeldung.jackson.dynamicIgnore;
|
||||||
|
|
||||||
|
|
||||||
public class Address implements Hidable {
|
public class Address implements Hidable {
|
||||||
private String city;
|
private String city;
|
||||||
private String country;
|
private String country;
|
||||||
|
|
|
@ -2,7 +2,6 @@ package com.baeldung.jackson.dynamicIgnore;
|
||||||
|
|
||||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||||
|
|
||||||
|
|
||||||
@JsonIgnoreProperties("hidden")
|
@JsonIgnoreProperties("hidden")
|
||||||
public interface Hidable {
|
public interface Hidable {
|
||||||
boolean isHidden();
|
boolean isHidden();
|
||||||
|
|
|
@ -1,6 +1,5 @@
|
||||||
package com.baeldung.jackson.dynamicIgnore;
|
package com.baeldung.jackson.dynamicIgnore;
|
||||||
|
|
||||||
|
|
||||||
public class Person implements Hidable {
|
public class Person implements Hidable {
|
||||||
private String name;
|
private String name;
|
||||||
private Address address;
|
private Address address;
|
||||||
|
@ -13,7 +12,6 @@ public class Person implements Hidable {
|
||||||
this.hidden = hidden;
|
this.hidden = hidden;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
public String getName() {
|
public String getName() {
|
||||||
return name;
|
return name;
|
||||||
}
|
}
|
||||||
|
@ -29,6 +27,7 @@ public class Person implements Hidable {
|
||||||
public void setAddress(final Address address) {
|
public void setAddress(final Address address) {
|
||||||
this.address = address;
|
this.address = address;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean isHidden() {
|
public boolean isHidden() {
|
||||||
return hidden;
|
return hidden;
|
||||||
|
|
|
@ -22,18 +22,16 @@ public class JsonFormatUnitTest {
|
||||||
@Test
|
@Test
|
||||||
public void whenSerializedDateFormat_thenCorrect() throws JsonProcessingException {
|
public void whenSerializedDateFormat_thenCorrect() throws JsonProcessingException {
|
||||||
|
|
||||||
User user = new User("Jay", "Sridhar");
|
User user = new User("Jay", "Sridhar");
|
||||||
|
|
||||||
String result = new ObjectMapper().writeValueAsString(user);
|
String result = new ObjectMapper().writeValueAsString(user);
|
||||||
|
|
||||||
// Expected to match: "2016-12-19@09:34:42.628+0000"
|
// Expected to match: "2016-12-19@09:34:42.628+0000"
|
||||||
assertThat(from(result).getString("createdDate"))
|
assertThat(from(result).getString("createdDate")).matches("\\d{4}\\-\\d{2}\\-\\d{2}@\\d{2}:\\d{2}:\\d{2}\\.\\d{3}\\+\\d{4}");
|
||||||
.matches("\\d{4}\\-\\d{2}\\-\\d{2}@\\d{2}:\\d{2}:\\d{2}\\.\\d{3}\\+\\d{4}");
|
|
||||||
|
|
||||||
// Expected to be close to current time
|
// Expected to be close to current time
|
||||||
long now = new Date().getTime();
|
long now = new Date().getTime();
|
||||||
assertThat(from(result).getLong("dateNum"))
|
assertThat(from(result).getLong("dateNum")).isCloseTo(now, withPercentage(10.0));
|
||||||
.isCloseTo(now, withPercentage(10.0));
|
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -23,11 +23,11 @@ public class JsonFilterUnitTest {
|
||||||
|
|
||||||
// arrange
|
// arrange
|
||||||
Author author = new Author("Alex", "Theedom");
|
Author author = new Author("Alex", "Theedom");
|
||||||
FilterProvider filters = new SimpleFilterProvider()
|
FilterProvider filters = new SimpleFilterProvider().addFilter("authorFilter", SimpleBeanPropertyFilter.filterOutAllExcept("lastName"));
|
||||||
.addFilter("authorFilter", SimpleBeanPropertyFilter.filterOutAllExcept("lastName"));
|
|
||||||
|
|
||||||
// act
|
// act
|
||||||
String result = new ObjectMapper().writer(filters).writeValueAsString(author);
|
String result = new ObjectMapper().writer(filters)
|
||||||
|
.writeValueAsString(author);
|
||||||
|
|
||||||
// assert
|
// assert
|
||||||
assertThat(from(result).getList("items")).isNull();
|
assertThat(from(result).getList("items")).isNull();
|
||||||
|
|
|
@ -17,9 +17,7 @@ public class Book extends Item {
|
||||||
|
|
||||||
private String ISBN;
|
private String ISBN;
|
||||||
|
|
||||||
@JsonFormat(
|
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy HH:mm:ss")
|
||||||
shape = JsonFormat.Shape.STRING,
|
|
||||||
pattern = "dd-MM-yyyy HH:mm:ss")
|
|
||||||
private Date published;
|
private Date published;
|
||||||
private BigDecimal pages;
|
private BigDecimal pages;
|
||||||
|
|
||||||
|
|
|
@ -31,10 +31,7 @@ public class JsonFormatUnitTest {
|
||||||
String toParse = "20-12-2014 14:30:00";
|
String toParse = "20-12-2014 14:30:00";
|
||||||
Date date = df.parse(toParse);
|
Date date = df.parse(toParse);
|
||||||
|
|
||||||
Book book = new Book(
|
Book book = new Book("Design Patterns: Elements of Reusable Object-oriented Software", new Author("The", "GoF"));
|
||||||
"Design Patterns: Elements of Reusable Object-oriented Software",
|
|
||||||
new Author("The", "GoF")
|
|
||||||
);
|
|
||||||
book.setPublished(date);
|
book.setPublished(date);
|
||||||
|
|
||||||
// act
|
// act
|
||||||
|
|
|
@ -12,9 +12,7 @@ import java.util.List;
|
||||||
* @author Alex Theedom www.readlearncode.com
|
* @author Alex Theedom www.readlearncode.com
|
||||||
* @version 1.0
|
* @version 1.0
|
||||||
*/
|
*/
|
||||||
@JsonIdentityInfo(
|
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
|
||||||
generator = ObjectIdGenerators.PropertyGenerator.class,
|
|
||||||
property = "id")
|
|
||||||
public class Author extends Person {
|
public class Author extends Person {
|
||||||
|
|
||||||
private List<Item> items = new ArrayList<>();
|
private List<Item> items = new ArrayList<>();
|
||||||
|
|
|
@ -1,6 +1,5 @@
|
||||||
package com.baeldung.jackson.general.jsonidentityinfo;
|
package com.baeldung.jackson.general.jsonidentityinfo;
|
||||||
|
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -11,7 +10,9 @@ import java.util.List;
|
||||||
*/
|
*/
|
||||||
public class Course extends Item {
|
public class Course extends Item {
|
||||||
|
|
||||||
public enum Medium {CLASSROOM, ONLINE}
|
public enum Medium {
|
||||||
|
CLASSROOM, ONLINE
|
||||||
|
}
|
||||||
|
|
||||||
public enum Level {
|
public enum Level {
|
||||||
BEGINNER("Beginner", 1), INTERMEDIATE("Intermediate", 2), ADVANCED("Advanced", 3);
|
BEGINNER("Beginner", 1), INTERMEDIATE("Intermediate", 2), ADVANCED("Advanced", 3);
|
||||||
|
|
|
@ -13,9 +13,7 @@ import java.util.UUID;
|
||||||
* @author Alex Theedom www.readlearncode.com
|
* @author Alex Theedom www.readlearncode.com
|
||||||
* @version 1.0
|
* @version 1.0
|
||||||
*/
|
*/
|
||||||
@JsonIdentityInfo(
|
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
|
||||||
generator = ObjectIdGenerators.PropertyGenerator.class,
|
|
||||||
property = "id")
|
|
||||||
public class Item {
|
public class Item {
|
||||||
|
|
||||||
private UUID id;
|
private UUID id;
|
||||||
|
@ -23,7 +21,8 @@ public class Item {
|
||||||
private List<Person> authors = new ArrayList<>();
|
private List<Person> authors = new ArrayList<>();
|
||||||
private float price;
|
private float price;
|
||||||
|
|
||||||
public Item(){}
|
public Item() {
|
||||||
|
}
|
||||||
|
|
||||||
public Item(String title, Author author) {
|
public Item(String title, Author author) {
|
||||||
this.id = UUID.randomUUID();
|
this.id = UUID.randomUUID();
|
||||||
|
|
|
@ -14,7 +14,8 @@ public class Person {
|
||||||
private String firstName;
|
private String firstName;
|
||||||
private String lastName;
|
private String lastName;
|
||||||
|
|
||||||
public Person(){}
|
public Person() {
|
||||||
|
}
|
||||||
|
|
||||||
public Person(String firstName, String lastName) {
|
public Person(String firstName, String lastName) {
|
||||||
this.id = UUID.randomUUID();
|
this.id = UUID.randomUUID();
|
||||||
|
|
|
@ -19,7 +19,8 @@ public class Item {
|
||||||
private List<Person> authors = new ArrayList<>();
|
private List<Person> authors = new ArrayList<>();
|
||||||
private float price;
|
private float price;
|
||||||
|
|
||||||
public Item(){}
|
public Item() {
|
||||||
|
}
|
||||||
|
|
||||||
public Item(String title, Author author) {
|
public Item(String title, Author author) {
|
||||||
this.id = UUID.randomUUID();
|
this.id = UUID.randomUUID();
|
||||||
|
|
|
@ -21,10 +21,7 @@ public class JsonPropertyUnitTest {
|
||||||
public void whenSerializingUsingJsonProperty_thenCorrect() throws JsonProcessingException {
|
public void whenSerializingUsingJsonProperty_thenCorrect() throws JsonProcessingException {
|
||||||
|
|
||||||
// arrange
|
// arrange
|
||||||
Book book = new Book(
|
Book book = new Book("Design Patterns: Elements of Reusable Object-oriented Software", new Author("The", "GoF"));
|
||||||
"Design Patterns: Elements of Reusable Object-oriented Software",
|
|
||||||
new Author("The", "GoF")
|
|
||||||
);
|
|
||||||
book.configureBinding("Hardback");
|
book.configureBinding("Hardback");
|
||||||
|
|
||||||
// act
|
// act
|
||||||
|
@ -62,12 +59,12 @@ public class JsonPropertyUnitTest {
|
||||||
String result = "{\"id\":\"cd941587-d1ae-4c2a-9a36-29533bf50411\",\"title\":\"Design Patterns: Elements of Reusable Object-oriented Software\",\"authors\":[{\"id\":\"c8e26318-2f5b-4fa2-9fdc-6e99be021fca\",\"firstName\":\"The\",\"lastName\":\"GoF\"}],\"binding\":\"Hardback\"}";
|
String result = "{\"id\":\"cd941587-d1ae-4c2a-9a36-29533bf50411\",\"title\":\"Design Patterns: Elements of Reusable Object-oriented Software\",\"authors\":[{\"id\":\"c8e26318-2f5b-4fa2-9fdc-6e99be021fca\",\"firstName\":\"The\",\"lastName\":\"GoF\"}],\"binding\":\"Hardback\"}";
|
||||||
|
|
||||||
// act
|
// act
|
||||||
Book book = new ObjectMapper().readerFor(Book.class).readValue(result);
|
Book book = new ObjectMapper().readerFor(Book.class)
|
||||||
|
.readValue(result);
|
||||||
|
|
||||||
// assert
|
// assert
|
||||||
assertThat(book.coverBinding()).isEqualTo("Hardback");
|
assertThat(book.coverBinding()).isEqualTo("Hardback");
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
|
@ -1,6 +1,5 @@
|
||||||
package com.baeldung.jackson.general.jsonunwrapped;
|
package com.baeldung.jackson.general.jsonunwrapped;
|
||||||
|
|
||||||
|
|
||||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
|
@ -22,7 +22,8 @@ public class JsonViewUnitTest {
|
||||||
Order order = new Order(120);
|
Order order = new Order(120);
|
||||||
|
|
||||||
// act
|
// act
|
||||||
String result = new ObjectMapper().writerWithView(Views.Internal.class).writeValueAsString(order);
|
String result = new ObjectMapper().writerWithView(Views.Internal.class)
|
||||||
|
.writeValueAsString(order);
|
||||||
|
|
||||||
// assert
|
// assert
|
||||||
assertThat(from(result).getUUID("id")).isNotNull();
|
assertThat(from(result).getUUID("id")).isNotNull();
|
||||||
|
@ -49,7 +50,8 @@ public class JsonViewUnitTest {
|
||||||
Order order = new Order(120);
|
Order order = new Order(120);
|
||||||
|
|
||||||
// act
|
// act
|
||||||
String result = new ObjectMapper().writerWithView(Views.Public.class).writeValueAsString(order);
|
String result = new ObjectMapper().writerWithView(Views.Public.class)
|
||||||
|
.writeValueAsString(order);
|
||||||
|
|
||||||
// assert
|
// assert
|
||||||
assertThat(from(result).getUUID("id")).isNotNull();
|
assertThat(from(result).getUUID("id")).isNotNull();
|
||||||
|
@ -68,5 +70,4 @@ public class JsonViewUnitTest {
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
|
@ -1,6 +1,5 @@
|
||||||
package com.baeldung.jackson.general.reference;
|
package com.baeldung.jackson.general.reference;
|
||||||
|
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -11,7 +10,9 @@ import java.util.List;
|
||||||
*/
|
*/
|
||||||
public class Course extends Item {
|
public class Course extends Item {
|
||||||
|
|
||||||
public enum Medium {CLASSROOM, ONLINE}
|
public enum Medium {
|
||||||
|
CLASSROOM, ONLINE
|
||||||
|
}
|
||||||
|
|
||||||
public enum Level {
|
public enum Level {
|
||||||
BEGINNER("Beginner", 1), INTERMEDIATE("Intermediate", 2), ADVANCED("Advanced", 3);
|
BEGINNER("Beginner", 1), INTERMEDIATE("Intermediate", 2), ADVANCED("Advanced", 3);
|
||||||
|
|
|
@ -21,7 +21,8 @@ public class Item {
|
||||||
private List<Person> authors = new ArrayList<>();
|
private List<Person> authors = new ArrayList<>();
|
||||||
private float price;
|
private float price;
|
||||||
|
|
||||||
public Item(){}
|
public Item() {
|
||||||
|
}
|
||||||
|
|
||||||
public Item(String title, Author author) {
|
public Item(String title, Author author) {
|
||||||
this.id = UUID.randomUUID();
|
this.id = UUID.randomUUID();
|
||||||
|
|
|
@ -14,7 +14,8 @@ public class Person {
|
||||||
private String firstName;
|
private String firstName;
|
||||||
private String lastName;
|
private String lastName;
|
||||||
|
|
||||||
public Person(){}
|
public Person() {
|
||||||
|
}
|
||||||
|
|
||||||
public Person(String firstName, String lastName) {
|
public Person(String firstName, String lastName) {
|
||||||
this.id = UUID.randomUUID();
|
this.id = UUID.randomUUID();
|
||||||
|
|
|
@ -28,7 +28,6 @@ public class JsonIncludeUnitTest {
|
||||||
assertThat(from(result).getString("firstName")).isEqualTo("Alex");
|
assertThat(from(result).getString("firstName")).isEqualTo("Alex");
|
||||||
assertThat(result).doesNotContain("lastName");
|
assertThat(result).doesNotContain("lastName");
|
||||||
|
|
||||||
|
|
||||||
/*
|
/*
|
||||||
{
|
{
|
||||||
"id": "e8bb4802-6e0c-4fa5-9f68-c233272399cd",
|
"id": "e8bb4802-6e0c-4fa5-9f68-c233272399cd",
|
||||||
|
|
|
@ -12,29 +12,29 @@ import static org.junit.Assert.assertTrue;
|
||||||
public class ItemIdRemovedFromUserUnitTest {
|
public class ItemIdRemovedFromUserUnitTest {
|
||||||
@Test
|
@Test
|
||||||
public void givenRemoveItemJson_whenDeserialize_shouldHaveProperClassType() throws IOException {
|
public void givenRemoveItemJson_whenDeserialize_shouldHaveProperClassType() throws IOException {
|
||||||
//given
|
// given
|
||||||
Event event = new ItemIdRemovedFromUser("1", 12345567L, "item_1", 2L);
|
Event event = new ItemIdRemovedFromUser("1", 12345567L, "item_1", 2L);
|
||||||
ObjectMapper objectMapper = new ObjectMapper();
|
ObjectMapper objectMapper = new ObjectMapper();
|
||||||
String eventJson = objectMapper.writeValueAsString(event);
|
String eventJson = objectMapper.writeValueAsString(event);
|
||||||
|
|
||||||
//when
|
// when
|
||||||
Event result = new ObjectMapper().readValue(eventJson, Event.class);
|
Event result = new ObjectMapper().readValue(eventJson, Event.class);
|
||||||
|
|
||||||
//then
|
// then
|
||||||
assertTrue(result instanceof ItemIdRemovedFromUser);
|
assertTrue(result instanceof ItemIdRemovedFromUser);
|
||||||
assertEquals("item_1", ((ItemIdRemovedFromUser) result).getItemId());
|
assertEquals("item_1", ((ItemIdRemovedFromUser) result).getItemId());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenAdddItemJson_whenSerialize_shouldIgnoreIdPropertyFromSuperclass() throws IOException {
|
public void givenAdddItemJson_whenSerialize_shouldIgnoreIdPropertyFromSuperclass() throws IOException {
|
||||||
//given
|
// given
|
||||||
Event event = new ItemIdAddedToUser("1", 12345567L, "item_1", 2L);
|
Event event = new ItemIdAddedToUser("1", 12345567L, "item_1", 2L);
|
||||||
ObjectMapper objectMapper = new ObjectMapper();
|
ObjectMapper objectMapper = new ObjectMapper();
|
||||||
|
|
||||||
//when
|
// when
|
||||||
String eventJson = objectMapper.writeValueAsString(event);
|
String eventJson = objectMapper.writeValueAsString(event);
|
||||||
|
|
||||||
//then
|
// then
|
||||||
assertFalse(eventJson.contains("id"));
|
assertFalse(eventJson.contains("id"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -23,7 +23,7 @@ public class SubTypeHandlingUnitTest {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenSubType_whenNotUsingNoArgsConstructors_thenSucceed() throws IOException{
|
public void givenSubType_whenNotUsingNoArgsConstructors_thenSucceed() throws IOException {
|
||||||
ObjectMapper mapper = new ObjectMapper();
|
ObjectMapper mapper = new ObjectMapper();
|
||||||
mapper.enableDefaultTyping();
|
mapper.enableDefaultTyping();
|
||||||
|
|
||||||
|
|
|
@ -30,8 +30,10 @@ public class TypeInfoInclusionUnitTest {
|
||||||
String jsonDataString = mapper.writeValueAsString(serializedFleet);
|
String jsonDataString = mapper.writeValueAsString(serializedFleet);
|
||||||
TypeInfoStructure.Fleet deserializedFleet = mapper.readValue(jsonDataString, TypeInfoStructure.Fleet.class);
|
TypeInfoStructure.Fleet deserializedFleet = mapper.readValue(jsonDataString, TypeInfoStructure.Fleet.class);
|
||||||
|
|
||||||
assertThat(deserializedFleet.getVehicles().get(0), instanceOf(TypeInfoStructure.Car.class));
|
assertThat(deserializedFleet.getVehicles()
|
||||||
assertThat(deserializedFleet.getVehicles().get(1), instanceOf(TypeInfoStructure.Truck.class));
|
.get(0), instanceOf(TypeInfoStructure.Car.class));
|
||||||
|
assertThat(deserializedFleet.getVehicles()
|
||||||
|
.get(1), instanceOf(TypeInfoStructure.Truck.class));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -51,7 +53,9 @@ public class TypeInfoInclusionUnitTest {
|
||||||
String jsonDataString = mapper.writeValueAsString(serializedFleet);
|
String jsonDataString = mapper.writeValueAsString(serializedFleet);
|
||||||
TypeInfoAnnotatedStructure.Fleet deserializedFleet = mapper.readValue(jsonDataString, TypeInfoAnnotatedStructure.Fleet.class);
|
TypeInfoAnnotatedStructure.Fleet deserializedFleet = mapper.readValue(jsonDataString, TypeInfoAnnotatedStructure.Fleet.class);
|
||||||
|
|
||||||
assertThat(deserializedFleet.getVehicles().get(0), instanceOf(TypeInfoAnnotatedStructure.Car.class));
|
assertThat(deserializedFleet.getVehicles()
|
||||||
assertThat(deserializedFleet.getVehicles().get(1), instanceOf(TypeInfoAnnotatedStructure.Truck.class));
|
.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();
|
private static ObjectMapper mapper = new ObjectMapper();
|
||||||
|
|
||||||
static JsonNode getExampleRoot() throws IOException {
|
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);
|
JsonNode rootNode = mapper.readTree(exampleInput);
|
||||||
return rootNode;
|
return rootNode;
|
||||||
}
|
}
|
||||||
|
|
|
@ -28,8 +28,10 @@ public class NodeOperationUnitTest {
|
||||||
|
|
||||||
final JsonNode node = mapper.valueToTree(fromValue);
|
final JsonNode node = mapper.valueToTree(fromValue);
|
||||||
|
|
||||||
assertEquals(2016, node.get("id").intValue());
|
assertEquals(2016, node.get("id")
|
||||||
assertEquals("baeldung.com", node.get("name").textValue());
|
.intValue());
|
||||||
|
assertEquals("baeldung.com", node.get("name")
|
||||||
|
.textValue());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -72,12 +74,21 @@ public class NodeOperationUnitTest {
|
||||||
public void givenANode_whenAddingIntoATree_thenCorrect() throws IOException {
|
public void givenANode_whenAddingIntoATree_thenCorrect() throws IOException {
|
||||||
final JsonNode rootNode = ExampleStructure.getExampleRoot();
|
final JsonNode rootNode = ExampleStructure.getExampleRoot();
|
||||||
final ObjectNode addedNode = ((ObjectNode) rootNode).putObject("address");
|
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());
|
assertFalse(rootNode.path("address")
|
||||||
assertEquals("Seattle", rootNode.path("address").path("city").textValue());
|
.isMissingNode());
|
||||||
assertEquals("Washington", rootNode.path("address").path("state").textValue());
|
assertEquals("Seattle", rootNode.path("address")
|
||||||
assertEquals("United States", rootNode.path("address").path("country").textValue());
|
.path("city")
|
||||||
|
.textValue());
|
||||||
|
assertEquals("Washington", rootNode.path("address")
|
||||||
|
.path("state")
|
||||||
|
.textValue());
|
||||||
|
assertEquals("United States", rootNode.path("address")
|
||||||
|
.path("country")
|
||||||
|
.textValue());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -88,8 +99,12 @@ public class NodeOperationUnitTest {
|
||||||
final JsonNode rootNode = ExampleStructure.getExampleRoot();
|
final JsonNode rootNode = ExampleStructure.getExampleRoot();
|
||||||
((ObjectNode) rootNode).set("name", newNode);
|
((ObjectNode) rootNode).set("name", newNode);
|
||||||
|
|
||||||
assertFalse(rootNode.path("name").path("nick").isMissingNode());
|
assertFalse(rootNode.path("name")
|
||||||
assertEquals("cowtowncoder", rootNode.path("name").path("nick").textValue());
|
.path("nick")
|
||||||
|
.isMissingNode());
|
||||||
|
assertEquals("cowtowncoder", rootNode.path("name")
|
||||||
|
.path("nick")
|
||||||
|
.textValue());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -97,7 +112,8 @@ public class NodeOperationUnitTest {
|
||||||
final JsonNode rootNode = ExampleStructure.getExampleRoot();
|
final JsonNode rootNode = ExampleStructure.getExampleRoot();
|
||||||
((ObjectNode) rootNode).remove("company");
|
((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);
|
super(vc);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Car deserialize(final JsonParser parser, final DeserializationContext deserializer) throws IOException {
|
public Car deserialize(final JsonParser parser, final DeserializationContext deserializer) throws IOException {
|
||||||
final Car car = new Car();
|
final Car car = new Car();
|
||||||
|
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue