diff --git a/core-java-9/src/test/java/com/baeldung/java9/language/stream/CollectorImprovementTest.java b/core-java-9/src/test/java/com/baeldung/java9/language/stream/CollectorImprovementTest.java new file mode 100644 index 0000000000..71ee6c6ae4 --- /dev/null +++ b/core-java-9/src/test/java/com/baeldung/java9/language/stream/CollectorImprovementTest.java @@ -0,0 +1,81 @@ +package com.baeldung.java9.language.stream; + +import org.junit.Test; + +import java.util.*; +import java.util.stream.Collectors; +import java.util.function.Function; + +import static org.junit.Assert.assertEquals; + +public class CollectorImprovementTest { + private static class Blog { + private String authorName; + private List comments; + + public Blog(String authorName) { + this.authorName = authorName; + this.comments = new LinkedList(); + } + + public String getAuthorName() { + return this.authorName; + } + + public List getComments() { + return new LinkedList(this.comments); + } + + public void addComment(String comment) { + this.comments.add(comment); + } + } + + @Test + public void testFiltering() { + List numbers = List.of(1, 2, 3, 5, 5); + + Map result = numbers.stream() + .filter(val -> val > 3).collect(Collectors.groupingBy( + Function.identity(), Collectors.counting())); + + assertEquals(1, result.size()); + + result = numbers.stream().collect(Collectors.groupingBy( + Function.identity(), Collectors.filtering(val -> val > 3, + Collectors.counting()))); + + assertEquals(4, result.size()); + } + + @Test + public void testFlatMapping() { + Blog blog1 = new CollectorImprovementTest.Blog("1"); + blog1.addComment("Nice"); + blog1.addComment("Very Nice"); + Blog blog2 = new CollectorImprovementTest.Blog("2"); + blog2.addComment("Disappointing"); + blog2.addComment("Ok"); + blog2.addComment("Could be better"); + List blogs = List.of(blog1, blog2); + + Map>> authorComments1 = + blogs.stream().collect(Collectors.groupingBy( + Blog::getAuthorName, Collectors.mapping( + Blog::getComments, Collectors.toList()))); + + assertEquals(2, authorComments1.size()); + assertEquals(2, authorComments1.get("1").get(0).size()); + assertEquals(3, authorComments1.get("2").get(0).size()); + + Map> authorComments2 = + blogs.stream().collect(Collectors.groupingBy( + Blog::getAuthorName, Collectors.flatMapping( + blog -> blog.getComments().stream(), + Collectors.toList()))); + + assertEquals(2, authorComments2.size()); + assertEquals(2, authorComments2.get("1").size()); + assertEquals(3, authorComments2.get("2").size()); + } +} diff --git a/core-java/README.md b/core-java/README.md index 015e18cec1..b653cfcfaf 100644 --- a/core-java/README.md +++ b/core-java/README.md @@ -52,4 +52,5 @@ - [URL Encoding and Decoding in Java](http://www.baeldung.com/java-url-encoding-decoding) - [Calculate the Size of a File in Java](http://www.baeldung.com/java-file-size) - [The Basics of Java Generics](http://www.baeldung.com/java-generics) -- [The Traveling Salesman Problem in Java](http://www.baeldung.com/java-simulated-annealing-for-traveling-salesman) \ No newline at end of file +- [The Traveling Salesman Problem in Java](http://www.baeldung.com/java-simulated-annealing-for-traveling-salesman) +- [How to Create an Executable JAR with Maven](http://www.baeldung.com/executable-jar-with-maven) diff --git a/core-java/pom.xml b/core-java/pom.xml index 3406bddda9..85afee2968 100644 --- a/core-java/pom.xml +++ b/core-java/pom.xml @@ -64,11 +64,6 @@ ${grep4j.version} - - com.lmax - disruptor - ${disruptor.version} - @@ -369,7 +364,6 @@ 0.4 1.8.7 1.16.12 - 3.3.6 1.3 diff --git a/core-java/src/main/java/com/baeldung/concurrent/countdownlatch/BrokenWorker.java b/core-java/src/main/java/com/baeldung/concurrent/countdownlatch/BrokenWorker.java new file mode 100644 index 0000000000..90cd01b69f --- /dev/null +++ b/core-java/src/main/java/com/baeldung/concurrent/countdownlatch/BrokenWorker.java @@ -0,0 +1,23 @@ +package com.baeldung.concurrent.countdownlatch; + +import java.util.List; +import java.util.concurrent.CountDownLatch; + +public class BrokenWorker implements Runnable { + private final List outputScraper; + private final CountDownLatch countDownLatch; + + public BrokenWorker(final List outputScraper, final CountDownLatch countDownLatch) { + this.outputScraper = outputScraper; + this.countDownLatch = countDownLatch; + } + + @Override + public void run() { + if (true) { + throw new RuntimeException("Oh dear"); + } + countDownLatch.countDown(); + outputScraper.add("Counted down"); + } +} diff --git a/core-java/src/main/java/com/baeldung/concurrent/countdownlatch/WaitingWorker.java b/core-java/src/main/java/com/baeldung/concurrent/countdownlatch/WaitingWorker.java new file mode 100644 index 0000000000..58a2a5f6b4 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/concurrent/countdownlatch/WaitingWorker.java @@ -0,0 +1,37 @@ +package com.baeldung.concurrent.countdownlatch; + +import java.util.List; +import java.util.concurrent.CountDownLatch; + +public class WaitingWorker implements Runnable { + + private final List outputScraper; + private final CountDownLatch readyThreadCounter; + private final CountDownLatch callingThreadBlocker; + private final CountDownLatch completedThreadCounter; + + public WaitingWorker(final List outputScraper, + final CountDownLatch readyThreadCounter, + final CountDownLatch callingThreadBlocker, + CountDownLatch completedThreadCounter) { + + this.outputScraper = outputScraper; + this.readyThreadCounter = readyThreadCounter; + this.callingThreadBlocker = callingThreadBlocker; + this.completedThreadCounter = completedThreadCounter; + } + + @Override + public void run() { + // Mark this thread as read / started + readyThreadCounter.countDown(); + try { + callingThreadBlocker.await(); + outputScraper.add("Counted down"); + } catch (InterruptedException e) { + e.printStackTrace(); + } finally { + completedThreadCounter.countDown(); + } + } +} diff --git a/core-java/src/main/java/com/baeldung/concurrent/countdownlatch/Worker.java b/core-java/src/main/java/com/baeldung/concurrent/countdownlatch/Worker.java new file mode 100644 index 0000000000..4701f26530 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/concurrent/countdownlatch/Worker.java @@ -0,0 +1,22 @@ +package com.baeldung.concurrent.countdownlatch; + +import java.util.List; +import java.util.concurrent.CountDownLatch; + +public class Worker implements Runnable { + private final List outputScraper; + private final CountDownLatch countDownLatch; + + public Worker(final List outputScraper, final CountDownLatch countDownLatch) { + this.outputScraper = outputScraper; + this.countDownLatch = countDownLatch; + } + + @Override + public void run() { + // Do some work + System.out.println("Doing some logic"); + countDownLatch.countDown(); + outputScraper.add("Counted down"); + } +} diff --git a/core-java/src/test/java/com/baeldung/concurrent/countdownlatch/CountdownLatchExampleTest.java b/core-java/src/test/java/com/baeldung/concurrent/countdownlatch/CountdownLatchExampleTest.java new file mode 100644 index 0000000000..2e77042f0b --- /dev/null +++ b/core-java/src/test/java/com/baeldung/concurrent/countdownlatch/CountdownLatchExampleTest.java @@ -0,0 +1,96 @@ +package com.baeldung.concurrent.countdownlatch; + +import org.junit.Test; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.stream.Stream; + +import static java.util.stream.Collectors.toList; +import static org.assertj.core.api.Assertions.assertThat; + +public class CountdownLatchExampleTest { + @Test + public void whenParallelProcessing_thenMainThreadWillBlockUntilCompletion() throws InterruptedException { + // Given + List outputScraper = Collections.synchronizedList(new ArrayList<>()); + CountDownLatch countDownLatch = new CountDownLatch(5); + List workers = Stream + .generate(() -> new Thread(new Worker(outputScraper, countDownLatch))) + .limit(5) + .collect(toList()); + + // When + workers.forEach(Thread::start); + countDownLatch.await(); // Block until workers finish + outputScraper.add("Latch released"); + + // Then + outputScraper.forEach(Object::toString); + assertThat(outputScraper) + .containsExactly( + "Counted down", + "Counted down", + "Counted down", + "Counted down", + "Counted down", + "Latch released" + ); + } + + @Test + public void whenFailingToParallelProcess_thenMainThreadShouldTimeout() throws InterruptedException { + // Given + List outputScraper = Collections.synchronizedList(new ArrayList<>()); + CountDownLatch countDownLatch = new CountDownLatch(5); + List workers = Stream + .generate(() -> new Thread(new BrokenWorker(outputScraper, countDownLatch))) + .limit(5) + .collect(toList()); + + // When + workers.forEach(Thread::start); + final boolean result = countDownLatch.await(3L, TimeUnit.SECONDS); + + // Then + assertThat(result).isFalse(); + } + + @Test + public void whenDoingLotsOfThreadsInParallel_thenStartThemAtTheSameTime() throws InterruptedException { + // Given + List outputScraper = Collections.synchronizedList(new ArrayList<>()); + CountDownLatch readyThreadCounter = new CountDownLatch(5); + CountDownLatch callingThreadBlocker = new CountDownLatch(1); + CountDownLatch completedThreadCounter = new CountDownLatch(5); + List workers = Stream + .generate(() -> new Thread(new WaitingWorker(outputScraper, readyThreadCounter, callingThreadBlocker, completedThreadCounter))) + .limit(5) + .collect(toList()); + + // When + workers.forEach(Thread::start); + readyThreadCounter.await(); // Block until workers start + outputScraper.add("Workers ready"); + callingThreadBlocker.countDown(); // Start workers + completedThreadCounter.await(); // Block until workers finish + outputScraper.add("Workers complete"); + + // Then + outputScraper.forEach(Object::toString); + assertThat(outputScraper) + .containsExactly( + "Workers ready", + "Counted down", + "Counted down", + "Counted down", + "Counted down", + "Counted down", + "Workers complete" + ); + } + +} \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/guava/GuavaBiMapTest.java b/core-java/src/test/java/com/baeldung/guava/GuavaBiMapTest.java index 1dab8b384b..0997c93a72 100644 --- a/core-java/src/test/java/com/baeldung/guava/GuavaBiMapTest.java +++ b/core-java/src/test/java/com/baeldung/guava/GuavaBiMapTest.java @@ -1,10 +1,8 @@ package com.baeldung.guava; import static org.junit.Assert.*; - import java.util.HashMap; import java.util.Map; - import org.junit.Test; import com.google.common.collect.BiMap; import com.google.common.collect.EnumHashBiMap; @@ -13,32 +11,32 @@ import com.google.common.collect.ImmutableBiMap; public class GuavaBiMapTest { @Test - public void whenQueryByValue_shouldReturnKey() { + public void whenQueryByValue_returnsKey() { final BiMap capitalCountryBiMap = HashBiMap.create(); capitalCountryBiMap.put("New Delhi", "India"); capitalCountryBiMap.put("Washingon, D.C.", "USA"); capitalCountryBiMap.put("Moscow", "Russia"); - final String countryHeadName = capitalCountryBiMap.inverse().get("India"); + final String countryCapitalName = capitalCountryBiMap.inverse().get("India"); - assertEquals("New Delhi", countryHeadName); + assertEquals("New Delhi", countryCapitalName); } @Test - public void whenCreateBiMapFromExistingMap_shouldReturnKey() { - final Map personCountryHeadMap = new HashMap<>(); - personCountryHeadMap.put("New Delhi", "India"); - personCountryHeadMap.put("Washingon, D.C.", "USA"); - personCountryHeadMap.put("Moscow", "Russia"); - final BiMap capitalCountryBiMap = HashBiMap.create(personCountryHeadMap); + public void whenCreateBiMapFromExistingMap_returnsKey() { + final Map capitalCountryMap = new HashMap<>(); + capitalCountryMap.put("New Delhi", "India"); + capitalCountryMap.put("Washingon, D.C.", "USA"); + capitalCountryMap.put("Moscow", "Russia"); + final BiMap capitalCountryBiMap = HashBiMap.create(capitalCountryMap); - final String countryHeadName = capitalCountryBiMap.inverse().get("India"); + final String countryCapitalName = capitalCountryBiMap.inverse().get("India"); - assertEquals("New Delhi", countryHeadName); + assertEquals("New Delhi", countryCapitalName); } @Test - public void whenQueryByKey_shouldReturnValue() { + public void whenQueryByKey_returnsValue() { final BiMap capitalCountryBiMap = HashBiMap.create(); capitalCountryBiMap.put("New Delhi", "India"); @@ -49,7 +47,7 @@ public class GuavaBiMapTest { } @Test(expected = IllegalArgumentException.class) - public void whenSameValueIsBeingPresent_shouldThrowException() { + public void whenSameValueIsPresent_throwsException() { final BiMap capitalCountryBiMap = HashBiMap.create(); capitalCountryBiMap.put("New Delhi", "India"); @@ -59,7 +57,7 @@ public class GuavaBiMapTest { } @Test - public void givenSameValueIsBeingPresent_whenForcePutIsUsed_shouldCompleteSuccessfully() { + public void givenSameValueIsPresent_whenForcePut_completesSuccessfully() { final BiMap capitalCountryBiMap = HashBiMap.create(); capitalCountryBiMap.put("New Delhi", "India"); @@ -72,7 +70,7 @@ public class GuavaBiMapTest { } @Test - public void whenSameKeyIsBeingPresent_shouldReplaceAlreadyPresent() { + public void whenSameKeyIsPresent_replacesAlreadyPresent() { final BiMap capitalCountryBiMap = HashBiMap.create(); capitalCountryBiMap.put("New Delhi", "India"); @@ -84,21 +82,21 @@ public class GuavaBiMapTest { } @Test - public void whenUsingImmutableBiMap_shouldAllowPutSuccessfully() { + public void whenUsingImmutableBiMap_allowsPutSuccessfully() { final BiMap capitalCountryBiMap = new ImmutableBiMap.Builder().put("New Delhi", "India").put("Washingon, D.C.", "USA").put("Moscow", "Russia").build(); assertEquals("USA", capitalCountryBiMap.get("Washingon, D.C.")); } @Test(expected = UnsupportedOperationException.class) - public void whenUsingImmutableBiMap_shouldNotAllowRemove() { + public void whenUsingImmutableBiMap_doesntAllowRemove() { final BiMap capitalCountryBiMap = new ImmutableBiMap.Builder().put("New Delhi", "India").put("Washingon, D.C.", "USA").put("Moscow", "Russia").build(); capitalCountryBiMap.remove("New Delhi"); } @Test(expected = UnsupportedOperationException.class) - public void whenUsingImmutableBiMap_shouldNotAllowPut() { + public void whenUsingImmutableBiMap_doesntAllowPut() { final BiMap capitalCountryBiMap = new ImmutableBiMap.Builder().put("New Delhi", "India").put("Washingon, D.C.", "USA").put("Moscow", "Russia").build(); capitalCountryBiMap.put("New York", "USA"); @@ -109,7 +107,7 @@ public class GuavaBiMapTest { } @Test - public void whenUsingEnumAsKeyInMap_shouldReplaceAlreadyPresent() { + public void whenUsingEnumAsKeyInMap_replacesAlreadyPresent() { final BiMap operationStringBiMap = EnumHashBiMap.create(Operation.class); operationStringBiMap.put(Operation.ADD, "Add"); @@ -119,4 +117,4 @@ public class GuavaBiMapTest { assertEquals("Divide", operationStringBiMap.get(Operation.DIVIDE)); } -} +} \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/java/map/MapTest.java b/core-java/src/test/java/com/baeldung/java/map/MapTest.java index a348869a5c..4642c4cc4d 100644 --- a/core-java/src/test/java/com/baeldung/java/map/MapTest.java +++ b/core-java/src/test/java/com/baeldung/java/map/MapTest.java @@ -311,13 +311,7 @@ public class MapTest { @Test public void givenTreeMap_whenOrdersEntriesByComparator_thenCorrect() { - TreeMap map = new TreeMap<>(new Comparator() { - - @Override - public int compare(Integer o1, Integer o2) { - return o2 - o1; - } - }); + TreeMap map = new TreeMap<>(Comparator.reverseOrder()); map.put(3, "val"); map.put(2, "val"); map.put(1, "val"); diff --git a/core-java/src/test/java/com/baeldung/java8/Java8FindAnyFindFirstTest.java b/core-java/src/test/java/com/baeldung/java8/Java8FindAnyFindFirstTest.java index c90b7d79c2..6a2b89963c 100644 --- a/core-java/src/test/java/com/baeldung/java8/Java8FindAnyFindFirstTest.java +++ b/core-java/src/test/java/com/baeldung/java8/Java8FindAnyFindFirstTest.java @@ -17,7 +17,7 @@ public class Java8FindAnyFindFirstTest { @Test public void createStream_whenFindAnyResultIsPresent_thenCorrect() { - List list = Arrays.asList("A","B","C","D"); + List list = Arrays.asList("A", "B", "C", "D"); Optional result = list.stream().findAny(); @@ -25,14 +25,27 @@ public class Java8FindAnyFindFirstTest { assertThat(result.get(), anyOf(is("A"), is("B"), is("C"), is("D"))); } + @Test + public void createParallelStream_whenFindAnyResultIsPresent_thenCorrect() throws Exception { + List list = Arrays.asList(1, 2, 3, 4, 5); + Optional result = list + .stream() + .parallel() + .filter(num -> num < 4) + .findAny(); + + assertTrue(result.isPresent()); + assertThat(result.get(), anyOf(is(1), is(2), is(3))); + } + @Test public void createStream_whenFindFirstResultIsPresent_thenCorrect() { - List list = Arrays.asList("A","B","C","D"); + List list = Arrays.asList("A", "B", "C", "D"); Optional result = list.stream().findFirst(); assertTrue(result.isPresent()); - assertThat(result.get(),is("A")); + assertThat(result.get(), is("A")); } } diff --git a/disruptor/README.md b/disruptor/README.md new file mode 100644 index 0000000000..e69de29bb2 diff --git a/disruptor/pom.xml b/disruptor/pom.xml new file mode 100644 index 0000000000..7f2c78c9b0 --- /dev/null +++ b/disruptor/pom.xml @@ -0,0 +1,251 @@ + + 4.0.0 + com.baeldung + disruptor + 0.1.0-SNAPSHOT + jar + + disruptor + + + + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + + com.lmax + disruptor + ${disruptor.version} + + + + + + org.slf4j + slf4j-api + ${org.slf4j.version} + + + ch.qos.logback + logback-classic + ${logback.version} + + + org.slf4j + jcl-over-slf4j + ${org.slf4j.version} + + + org.slf4j + log4j-over-slf4j + ${org.slf4j.version} + + + + + + org.hamcrest + hamcrest-all + 1.3 + test + + + + junit + junit + ${junit.version} + test + + + + org.hamcrest + hamcrest-core + ${org.hamcrest.version} + test + + + org.hamcrest + hamcrest-library + ${org.hamcrest.version} + test + + + + + + disruptor + + + src/main/resources + true + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + 1.8 + 1.8 + + + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + + org.apache.maven.plugins + maven-dependency-plugin + + + copy-dependencies + prepare-package + + copy-dependencies + + + ${project.build.directory}/libs + + + + + + + org.apache.maven.plugins + maven-jar-plugin + + + + true + libs/ + org.baeldung.executable.ExecutableMavenJar + + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + package + + single + + + + + org.baeldung.executable.ExecutableMavenJar + + + + jar-with-dependencies + + + + + + + + org.apache.maven.plugins + maven-shade-plugin + + + + shade + + + true + + + org.baeldung.executable.ExecutableMavenJar + + + + + + + + + com.jolira + onejar-maven-plugin + + + + org.baeldung.executable.ExecutableMavenJar + true + ${project.build.finalName}-onejar.${project.packaging} + + + one-jar + + + + + + + + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + + + json + + + + + + + + + + + 1.7.21 + 1.1.7 + + + 3.5 + 3.3.6 + + + 1.3 + 4.12 + 1.10.19 + 6.10 + 3.6.1 + + + 3.6.0 + 2.19.1 + + + + \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/disruptor/DelayedMultiEventProducer.java b/disruptor/src/main/java/com/baeldung/disruptor/DelayedMultiEventProducer.java similarity index 100% rename from core-java/src/main/java/com/baeldung/disruptor/DelayedMultiEventProducer.java rename to disruptor/src/main/java/com/baeldung/disruptor/DelayedMultiEventProducer.java diff --git a/core-java/src/main/java/com/baeldung/disruptor/EventConsumer.java b/disruptor/src/main/java/com/baeldung/disruptor/EventConsumer.java similarity index 100% rename from core-java/src/main/java/com/baeldung/disruptor/EventConsumer.java rename to disruptor/src/main/java/com/baeldung/disruptor/EventConsumer.java diff --git a/core-java/src/main/java/com/baeldung/disruptor/EventProducer.java b/disruptor/src/main/java/com/baeldung/disruptor/EventProducer.java similarity index 100% rename from core-java/src/main/java/com/baeldung/disruptor/EventProducer.java rename to disruptor/src/main/java/com/baeldung/disruptor/EventProducer.java diff --git a/core-java/src/main/java/com/baeldung/disruptor/MultiEventPrintConsumer.java b/disruptor/src/main/java/com/baeldung/disruptor/MultiEventPrintConsumer.java similarity index 100% rename from core-java/src/main/java/com/baeldung/disruptor/MultiEventPrintConsumer.java rename to disruptor/src/main/java/com/baeldung/disruptor/MultiEventPrintConsumer.java diff --git a/core-java/src/main/java/com/baeldung/disruptor/SingleEventPrintConsumer.java b/disruptor/src/main/java/com/baeldung/disruptor/SingleEventPrintConsumer.java similarity index 100% rename from core-java/src/main/java/com/baeldung/disruptor/SingleEventPrintConsumer.java rename to disruptor/src/main/java/com/baeldung/disruptor/SingleEventPrintConsumer.java diff --git a/core-java/src/main/java/com/baeldung/disruptor/SingleEventProducer.java b/disruptor/src/main/java/com/baeldung/disruptor/SingleEventProducer.java similarity index 100% rename from core-java/src/main/java/com/baeldung/disruptor/SingleEventProducer.java rename to disruptor/src/main/java/com/baeldung/disruptor/SingleEventProducer.java diff --git a/core-java/src/main/java/com/baeldung/disruptor/ValueEvent.java b/disruptor/src/main/java/com/baeldung/disruptor/ValueEvent.java similarity index 100% rename from core-java/src/main/java/com/baeldung/disruptor/ValueEvent.java rename to disruptor/src/main/java/com/baeldung/disruptor/ValueEvent.java diff --git a/core-java/src/test/java/com/baeldung/disruptor/DisruptorTest.java b/disruptor/src/test/java/com/baeldung/disruptor/DisruptorTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/disruptor/DisruptorTest.java rename to disruptor/src/test/java/com/baeldung/disruptor/DisruptorTest.java diff --git a/core-java/src/test/java/com/baeldung/disruptor/MultiEventConsumer.java b/disruptor/src/test/java/com/baeldung/disruptor/MultiEventConsumer.java similarity index 100% rename from core-java/src/test/java/com/baeldung/disruptor/MultiEventConsumer.java rename to disruptor/src/test/java/com/baeldung/disruptor/MultiEventConsumer.java diff --git a/core-java/src/test/java/com/baeldung/disruptor/SingleEventConsumer.java b/disruptor/src/test/java/com/baeldung/disruptor/SingleEventConsumer.java similarity index 100% rename from core-java/src/test/java/com/baeldung/disruptor/SingleEventConsumer.java rename to disruptor/src/test/java/com/baeldung/disruptor/SingleEventConsumer.java diff --git a/guava/src/test/java/org/baeldung/guava/GuavaRangeMapTest.java b/guava/src/test/java/org/baeldung/guava/GuavaRangeMapTest.java new file mode 100644 index 0000000000..b68dca97c6 --- /dev/null +++ b/guava/src/test/java/org/baeldung/guava/GuavaRangeMapTest.java @@ -0,0 +1,128 @@ +package org.baeldung.guava; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import java.util.Map; +import org.junit.Test; +import com.google.common.collect.ImmutableRangeMap; +import com.google.common.collect.Range; +import com.google.common.collect.RangeMap; +import com.google.common.collect.TreeRangeMap; + +public class GuavaRangeMapTest { + + @Test + public void givenRangeMap_whenQueryWithinRange_returnsSucessfully() { + final RangeMap experienceRangeDesignationMap = TreeRangeMap.create(); + + experienceRangeDesignationMap.put(Range.closed(0, 2), "Associate"); + experienceRangeDesignationMap.put(Range.closed(3, 5), "Senior Associate"); + experienceRangeDesignationMap.put(Range.closed(6, 8), "Vice President"); + experienceRangeDesignationMap.put(Range.closed(9, 15), "Executive Director"); + experienceRangeDesignationMap.put(Range.closed(16, 30), "Managing Director"); + + assertEquals("Vice President", experienceRangeDesignationMap.get(6)); + assertEquals("Executive Director", experienceRangeDesignationMap.get(15)); + } + + @Test + public void givenRangeMap_whenQueryOutsideRange_returnsNull() { + final RangeMap experienceRangeDesignationMap = TreeRangeMap.create(); + + experienceRangeDesignationMap.put(Range.closed(0, 2), "Associate"); + experienceRangeDesignationMap.put(Range.closed(3, 5), "Senior Associate"); + experienceRangeDesignationMap.put(Range.closed(6, 8), "Vice President"); + experienceRangeDesignationMap.put(Range.closed(9, 15), "Executive Director"); + experienceRangeDesignationMap.put(Range.closed(16, 30), "Managing Director"); + + assertNull(experienceRangeDesignationMap.get(31)); + } + + @Test + public void givenRangeMap_whenRemoveRangeIsCalled_removesSucessfully() { + final RangeMap experienceRangeDesignationMap = TreeRangeMap.create(); + + experienceRangeDesignationMap.put(Range.closed(0, 2), "Associate"); + experienceRangeDesignationMap.put(Range.closed(3, 5), "Senior Associate"); + experienceRangeDesignationMap.put(Range.closed(6, 8), "Vice President"); + experienceRangeDesignationMap.put(Range.closed(9, 15), "Executive Director"); + experienceRangeDesignationMap.put(Range.closed(16, 30), "Managing Director"); + experienceRangeDesignationMap.remove(Range.closed(8, 15)); + experienceRangeDesignationMap.remove(Range.closed(20, 26)); + + assertNull(experienceRangeDesignationMap.get(9)); + assertEquals("Managing Director", experienceRangeDesignationMap.get(16)); + assertEquals("Managing Director", experienceRangeDesignationMap.get(30)); + assertNull(experienceRangeDesignationMap.get(25)); + } + + @Test + public void givenRangeMap_whenSpanIsCalled_returnsSucessfully() { + final RangeMap experienceRangeDesignationMap = TreeRangeMap.create(); + + experienceRangeDesignationMap.put(Range.closed(0, 2), "Associate"); + experienceRangeDesignationMap.put(Range.closed(3, 5), "Senior Associate"); + experienceRangeDesignationMap.put(Range.closed(6, 8), "Vice President"); + experienceRangeDesignationMap.put(Range.closed(9, 15), "Executive Director"); + experienceRangeDesignationMap.put(Range.closed(16, 30), "Managing Director"); + final Range experienceSpan = experienceRangeDesignationMap.span(); + + assertEquals(0, experienceSpan.lowerEndpoint().intValue()); + assertEquals(30, experienceSpan.upperEndpoint().intValue()); + } + + @Test + public void givenRangeMap_whenGetEntryIsCalled_returnsEntrySucessfully() { + final RangeMap experienceRangeDesignationMap = TreeRangeMap.create(); + + experienceRangeDesignationMap.put(Range.closed(0, 2), "Associate"); + experienceRangeDesignationMap.put(Range.closed(3, 5), "Senior Associate"); + experienceRangeDesignationMap.put(Range.closed(6, 8), "Vice President"); + experienceRangeDesignationMap.put(Range.closed(9, 15), "Executive Director"); + experienceRangeDesignationMap.put(Range.closed(20, 30), "Managing Director"); + final Map.Entry, String> experiencEntry = experienceRangeDesignationMap.getEntry(10); + + assertEquals(Range.closed(9, 15), experiencEntry.getKey()); + assertEquals("Executive Director", experiencEntry.getValue()); + } + + @Test + public void givenRangeMap_whenSubRangeMapIsCalled_returnsSubRangeSucessfully() { + final RangeMap experienceRangeDesignationMap = TreeRangeMap.create(); + + experienceRangeDesignationMap.put(Range.closed(0, 2), "Associate"); + experienceRangeDesignationMap.put(Range.closed(3, 5), "Senior Associate"); + experienceRangeDesignationMap.put(Range.closed(6, 8), "Vice President"); + experienceRangeDesignationMap.put(Range.closed(8, 15), "Executive Director"); + experienceRangeDesignationMap.put(Range.closed(16, 30), "Managing Director"); + final RangeMap experiencedSubRangeDesignationMap = experienceRangeDesignationMap.subRangeMap(Range.closed(4, 14)); + + assertNull(experiencedSubRangeDesignationMap.get(3)); + assertEquals("Executive Director", experiencedSubRangeDesignationMap.get(14)); + assertEquals("Vice President", experiencedSubRangeDesignationMap.get(7)); + } + + @Test + public void givenImmutableRangeMap_whenQueryWithinRange_returnsSucessfully() { + final RangeMap experienceRangeDesignationMap = ImmutableRangeMap. builder() + .put(Range.closed(0, 2), "Associate") + .put(Range.closed(3, 5), "Senior Associate") + .put(Range.closed(6, 8), "Vice President") + .put(Range.closed(9, 15), "Executive Director") + .put(Range.closed(16, 30), "Managing Director").build(); + + assertEquals("Vice President", experienceRangeDesignationMap.get(6)); + assertEquals("Executive Director", experienceRangeDesignationMap.get(15)); + } + + @Test(expected = IllegalArgumentException.class) + public void givenImmutableRangeMap_whenRangeOverlaps_ThrowsException() { + ImmutableRangeMap. builder() + .put(Range.closed(0, 2), "Associate") + .put(Range.closed(3, 5), "Senior Associate") + .put(Range.closed(6, 8), "Vice President") + .put(Range.closed(8, 15), "Executive Director") + .put(Range.closed(16, 30), "Managing Director").build(); + + } +} diff --git a/guava/src/test/java/org/baeldung/guava/GuavaRangeSetTest.java b/guava/src/test/java/org/baeldung/guava/GuavaRangeSetTest.java new file mode 100644 index 0000000000..002e1a61e9 --- /dev/null +++ b/guava/src/test/java/org/baeldung/guava/GuavaRangeSetTest.java @@ -0,0 +1,127 @@ +package org.baeldung.guava; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.assertFalse; +import org.junit.Test; +import com.google.common.collect.ImmutableRangeSet; +import com.google.common.collect.Range; +import com.google.common.collect.RangeSet; +import com.google.common.collect.TreeRangeSet; + +public class GuavaRangeSetTest { + + @Test + public void givenRangeSet_whenQueryWithinRange_returnsSucessfully() { + final RangeSet numberRangeSet = TreeRangeSet.create(); + + numberRangeSet.add(Range.closed(0, 2)); + numberRangeSet.add(Range.closed(3, 5)); + numberRangeSet.add(Range.closed(6, 8)); + + assertTrue(numberRangeSet.contains(1)); + assertFalse(numberRangeSet.contains(9)); + } + + @Test + public void givenRangeSet_whenEnclosesWithinRange_returnsSucessfully() { + final RangeSet numberRangeSet = TreeRangeSet.create(); + + numberRangeSet.add(Range.closed(0, 2)); + numberRangeSet.add(Range.closed(3, 10)); + numberRangeSet.add(Range.closed(15, 18)); + + assertTrue(numberRangeSet.encloses(Range.closed(4, 5))); + assertFalse(numberRangeSet.encloses(Range.closed(4, 11))); + } + + @Test + public void givenRangeSet_whenComplementIsCalled_returnsSucessfully() { + final RangeSet numberRangeSet = TreeRangeSet.create(); + + numberRangeSet.add(Range.closed(0, 2)); + numberRangeSet.add(Range.closed(3, 5)); + numberRangeSet.add(Range.closed(6, 8)); + final RangeSet numberRangeComplementSet = numberRangeSet.complement(); + + assertTrue(numberRangeComplementSet.contains(-1000)); + assertFalse(numberRangeComplementSet.contains(2)); + assertFalse(numberRangeComplementSet.contains(3)); + assertTrue(numberRangeComplementSet.contains(1000)); + } + + @Test + public void givenRangeSet_whenIntersectsWithinRange_returnsSucessfully() { + final RangeSet numberRangeSet = TreeRangeSet.create(); + + numberRangeSet.add(Range.closed(0, 2)); + numberRangeSet.add(Range.closed(3, 10)); + numberRangeSet.add(Range.closed(15, 18)); + + assertTrue(numberRangeSet.intersects(Range.closed(4, 17))); + assertFalse(numberRangeSet.intersects(Range.closed(19, 200))); + } + + @Test + public void givenRangeSet_whenRemoveRangeIsCalled_removesSucessfully() { + final RangeSet numberRangeSet = TreeRangeSet.create(); + + numberRangeSet.add(Range.closed(0, 2)); + numberRangeSet.add(Range.closed(3, 5)); + numberRangeSet.add(Range.closed(6, 8)); + numberRangeSet.add(Range.closed(9, 15)); + numberRangeSet.remove(Range.closed(3, 5)); + numberRangeSet.remove(Range.closed(7, 10)); + + assertTrue(numberRangeSet.contains(1)); + assertFalse(numberRangeSet.contains(9)); + assertTrue(numberRangeSet.contains(12)); + } + + @Test + public void givenRangeSet_whenSpanIsCalled_returnsSucessfully() { + final RangeSet numberRangeSet = TreeRangeSet.create(); + + numberRangeSet.add(Range.closed(0, 2)); + numberRangeSet.add(Range.closed(3, 5)); + numberRangeSet.add(Range.closed(6, 8)); + final Range experienceSpan = numberRangeSet.span(); + + assertEquals(0, experienceSpan.lowerEndpoint().intValue()); + assertEquals(8, experienceSpan.upperEndpoint().intValue()); + } + + @Test + public void givenRangeSet_whenSubRangeSetIsCalled_returnsSubRangeSucessfully() { + final RangeSet numberRangeSet = TreeRangeSet.create(); + + numberRangeSet.add(Range.closed(0, 2)); + numberRangeSet.add(Range.closed(3, 5)); + numberRangeSet.add(Range.closed(6, 8)); + final RangeSet numberSubRangeSet = numberRangeSet.subRangeSet(Range.closed(4, 14)); + + assertFalse(numberSubRangeSet.contains(3)); + assertFalse(numberSubRangeSet.contains(14)); + assertTrue(numberSubRangeSet.contains(7)); + } + + @Test + public void givenImmutableRangeSet_whenQueryWithinRange_returnsSucessfully() { + final RangeSet numberRangeSet = ImmutableRangeSet. builder() + .add(Range.closed(0, 2)) + .add(Range.closed(3, 5)) + .add(Range.closed(6, 8)).build(); + + assertTrue(numberRangeSet.contains(6)); + assertFalse(numberRangeSet.contains(15)); + } + + @Test(expected = IllegalArgumentException.class) + public void givenImmutableRangeMap_whenRangeOverlaps_ThrowsException() { + ImmutableRangeSet. builder() + .add(Range.closed(0, 2)) + .add(Range.closed(3, 5)) + .add(Range.closed(5, 8)).build(); + + } +} diff --git a/java-mongodb/pom.xml b/java-mongodb/pom.xml index 66b4bbdc99..4e5b847a01 100644 --- a/java-mongodb/pom.xml +++ b/java-mongodb/pom.xml @@ -1,44 +1,98 @@ - - 4.0.0 + + 4.0.0 - com.baeldung - java-mongodb - 1.0-SNAPSHOT + com.baeldung + java-mongodb + 1.0-SNAPSHOT - - 1.8 - 1.8 - 4.12 - 3.4.1 - 1.11 - + - + + junit + junit + ${junit.version} + test + - - junit - junit - ${junit.version} - test - - - - de.flapdoodle.embedmongo - de.flapdoodle.embedmongo - ${flapdoodle.version} - test - + + de.flapdoodle.embedmongo + de.flapdoodle.embedmongo + ${flapdoodle.version} + test + - - org.mongodb - mongo-java-driver - ${mongo.version} - + + org.mongodb + mongo-java-driver + ${mongo.version} + - + + + + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + **/*IntegrationTest.java + **/*LongRunningUnitTest.java + **/*ManualTest.java + + true + + + + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*ManualTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + + + + 1.8 + 1.8 + 4.12 + 3.4.1 + 1.11 + + 2.19.1 + \ No newline at end of file diff --git a/java-mongodb/src/main/java/com/baeldung/MongoExample.java b/java-mongodb/src/main/java/com/baeldung/MongoExample.java index fbef17a15f..9af1e1f6a4 100644 --- a/java-mongodb/src/main/java/com/baeldung/MongoExample.java +++ b/java-mongodb/src/main/java/com/baeldung/MongoExample.java @@ -7,47 +7,47 @@ import com.mongodb.DBCursor; import com.mongodb.MongoClient; public class MongoExample { - public static void main( String[] args ) { - - MongoClient mongoClient = new MongoClient("localhost", 27017); - - DB database = mongoClient.getDB("myMongoDb"); - - // print existing databases - mongoClient.getDatabaseNames().forEach(System.out::println); - - database.createCollection("customers", null); - - // print all collections in customers database - database.getCollectionNames().forEach(System.out::println); - - // create data - DBCollection collection = database.getCollection("customers"); - BasicDBObject document = new BasicDBObject(); - document.put("name", "Shubham"); - document.put("company", "Baeldung"); - collection.insert(document); - - // update data - BasicDBObject query = new BasicDBObject(); - query.put("name", "Shubham"); - BasicDBObject newDocument = new BasicDBObject(); - newDocument.put("name", "John"); - BasicDBObject updateObject = new BasicDBObject(); - updateObject.put("$set", newDocument); - collection.update(query, updateObject); - - // read data - BasicDBObject searchQuery = new BasicDBObject(); - searchQuery.put("name", "John"); - DBCursor cursor = collection.find(searchQuery); - while (cursor.hasNext()) { - System.out.println(cursor.next()); - } - - // delete data - BasicDBObject deleteQuery = new BasicDBObject(); - deleteQuery.put("name", "John"); - collection.remove(deleteQuery); + public static void main(String[] args) { + + MongoClient mongoClient = new MongoClient("localhost", 27017); + + DB database = mongoClient.getDB("myMongoDb"); + + // print existing databases + mongoClient.getDatabaseNames().forEach(System.out::println); + + database.createCollection("customers", null); + + // print all collections in customers database + database.getCollectionNames().forEach(System.out::println); + + // create data + DBCollection collection = database.getCollection("customers"); + BasicDBObject document = new BasicDBObject(); + document.put("name", "Shubham"); + document.put("company", "Baeldung"); + collection.insert(document); + + // update data + BasicDBObject query = new BasicDBObject(); + query.put("name", "Shubham"); + BasicDBObject newDocument = new BasicDBObject(); + newDocument.put("name", "John"); + BasicDBObject updateObject = new BasicDBObject(); + updateObject.put("$set", newDocument); + collection.update(query, updateObject); + + // read data + BasicDBObject searchQuery = new BasicDBObject(); + searchQuery.put("name", "John"); + DBCursor cursor = collection.find(searchQuery); + while (cursor.hasNext()) { + System.out.println(cursor.next()); + } + + // delete data + BasicDBObject deleteQuery = new BasicDBObject(); + deleteQuery.put("name", "John"); + collection.remove(deleteQuery); } } diff --git a/java-mongodb/src/test/java/com/baeldung/AppIntegrationTest.java b/java-mongodb/src/test/java/com/baeldung/AppIntegrationTest.java new file mode 100644 index 0000000000..94d1a01492 --- /dev/null +++ b/java-mongodb/src/test/java/com/baeldung/AppIntegrationTest.java @@ -0,0 +1,72 @@ +package com.baeldung; + +import static org.junit.Assert.assertEquals; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import com.mongodb.BasicDBObject; +import com.mongodb.DB; +import com.mongodb.DBCollection; +import com.mongodb.DBCursor; +import com.mongodb.Mongo; + +import de.flapdoodle.embedmongo.MongoDBRuntime; +import de.flapdoodle.embedmongo.MongodExecutable; +import de.flapdoodle.embedmongo.MongodProcess; +import de.flapdoodle.embedmongo.config.MongodConfig; +import de.flapdoodle.embedmongo.distribution.Version; +import de.flapdoodle.embedmongo.runtime.Network; + +public class AppIntegrationTest { + + private static final String DB_NAME = "myMongoDb"; + private MongodExecutable mongodExe; + private MongodProcess mongod; + private Mongo mongo; + private DB db; + private DBCollection collection; + + @Before + public void setup() throws Exception { + // Creating Mongodbruntime instance + MongoDBRuntime runtime = MongoDBRuntime.getDefaultInstance(); + + // Creating MongodbExecutable + mongodExe = runtime.prepare(new MongodConfig(Version.V2_0_1, 12345, Network.localhostIsIPv6())); + + // Starting Mongodb + mongod = mongodExe.start(); + mongo = new Mongo("localhost", 12345); + + // Creating DB + db = mongo.getDB(DB_NAME); + + // Creating collection Object and adding values + collection = db.getCollection("customers"); + } + + @After + public void teardown() throws Exception { + mongod.stop(); + mongodExe.cleanup(); + } + + @Test + public void testAddressPersistance() { + BasicDBObject contact = new BasicDBObject(); + contact.put("name", "John"); + contact.put("company", "Baeldung"); + + // Inserting document + collection.insert(contact); + DBCursor cursorDoc = collection.find(); + BasicDBObject contact1 = new BasicDBObject(); + while (cursorDoc.hasNext()) { + contact1 = (BasicDBObject) cursorDoc.next(); + System.out.println(contact1); + } + assertEquals(contact1.get("name"), "John"); + } +} \ No newline at end of file diff --git a/java-mongodb/src/test/java/com/baeldung/AppTest.java b/java-mongodb/src/test/java/com/baeldung/AppTest.java deleted file mode 100644 index 5dd6bb66a9..0000000000 --- a/java-mongodb/src/test/java/com/baeldung/AppTest.java +++ /dev/null @@ -1,72 +0,0 @@ -package com.baeldung; - -import static org.junit.Assert.assertEquals; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import com.mongodb.BasicDBObject; -import com.mongodb.DB; -import com.mongodb.DBCollection; -import com.mongodb.DBCursor; -import com.mongodb.Mongo; -import de.flapdoodle.embedmongo.MongoDBRuntime; -import de.flapdoodle.embedmongo.MongodExecutable; -import de.flapdoodle.embedmongo.MongodProcess; -import de.flapdoodle.embedmongo.config.MongodConfig; -import de.flapdoodle.embedmongo.distribution.Version; -import de.flapdoodle.embedmongo.runtime.Network; - -public class AppTest { - - private static final String DB_NAME = "myMongoDb"; - private MongodExecutable mongodExe; - private MongodProcess mongod; - private Mongo mongo; - private DB db; - private DBCollection collection; - - @Before - public void setup() throws Exception { - - // Creating Mongodbruntime instance - MongoDBRuntime runtime = MongoDBRuntime.getDefaultInstance(); - - // Creating MongodbExecutable - mongodExe = runtime.prepare(new MongodConfig(Version.V2_0_1, 12345, - Network.localhostIsIPv6())); - - // Starting Mongodb - mongod = mongodExe.start(); - mongo = new Mongo("localhost", 12345); - - // Creating DB - db = mongo.getDB(DB_NAME); - - // Creating collection Object and adding values - collection = db.getCollection("customers"); - } - - @After - public void teardown() throws Exception { - mongod.stop(); - mongodExe.cleanup(); - } - - @Test - public void testAddressPersistance() { - - BasicDBObject contact = new BasicDBObject(); - contact.put("name", "John"); - contact.put("company", "Baeldung"); - - // Inserting document - collection.insert(contact); - DBCursor cursorDoc = collection.find(); - BasicDBObject contact1 = new BasicDBObject(); - while (cursorDoc.hasNext()) { - contact1 = (BasicDBObject) cursorDoc.next(); - System.out.println(contact1); - } - assertEquals(contact1.get("name"), "John"); - } -} \ No newline at end of file diff --git a/javaslang/pom.xml b/javaslang/pom.xml index 57a3c7596e..e111132aec 100644 --- a/javaslang/pom.xml +++ b/javaslang/pom.xml @@ -37,4 +37,4 @@ - + \ No newline at end of file diff --git a/metrics/src/test/java/com/baeldung/metrics/core/MetricsTest.java b/metrics/src/test/java/com/baeldung/metrics/core/MetricsTest.java index 882cc6785f..f670acfaef 100644 --- a/metrics/src/test/java/com/baeldung/metrics/core/MetricsTest.java +++ b/metrics/src/test/java/com/baeldung/metrics/core/MetricsTest.java @@ -1,16 +1,15 @@ package com.baeldung.metrics.core; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; +import com.codahale.metrics.*; +import org.junit.Test; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; -import org.junit.Test; - -import com.codahale.metrics.*; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; public class MetricsTest { @Test @@ -139,7 +138,7 @@ public class MetricsTest { long elapsed1 = context1.stop(); - assertEquals(5000000000L, elapsed1, 1000000); + assertEquals(5000000000L, elapsed1, 10000000); assertThat(timer.getCount(), equalTo(1L)); assertEquals(0.2, timer.getMeanRate(), 0.1); diff --git a/pom.xml b/pom.xml index 6d26517999..d2db787c64 100644 --- a/pom.xml +++ b/pom.xml @@ -18,8 +18,8 @@ algorithms annotations apache-cxf - apache-fop - apache-poi + apache-fop + apache-poi aspectj assertj autovalue @@ -44,6 +44,7 @@ guava guava18 guava19 + disruptor handling-spring-static-resources hazelcast @@ -94,6 +95,7 @@ resteasy selenium-junit-testng + spark-java spring-akka spring-amqp spring-all @@ -120,7 +122,7 @@ spring-hibernate3 spring-hibernate4 spring-integration - spring-jersey + spring-jersey spring-jms spring-jooq spring-jpa @@ -174,12 +176,15 @@ testing + video-tutorials + wicket xml xmlunit2 xstream - java-mongodb + + struts2 - \ No newline at end of file + diff --git a/redis/README.md b/redis/README.md new file mode 100644 index 0000000000..3ce9031b62 --- /dev/null +++ b/redis/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Intro to Jedis – the Java Redis Client Library](http://www.baeldung.com/jedis-java-redis-client-library) diff --git a/rest-with-spark-java/pom.xml b/rest-with-spark-java/pom.xml new file mode 100644 index 0000000000..2364154fdc --- /dev/null +++ b/rest-with-spark-java/pom.xml @@ -0,0 +1,38 @@ + + + 4.0.0 + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + com.baeldung + rest-with-spark-java + 1.0-SNAPSHOT + rest-with-spark-java + http://maven.apache.org + + + junit + junit + 3.8.1 + test + + + com.sparkjava + spark-core + 2.5.4 + + + com.fasterxml.jackson.core + jackson-core + 2.8.6 + + + com.fasterxml.jackson.core + jackson-databind + 2.8.6 + + + diff --git a/rest-with-spark-java/src/main/java/com/baeldung/Router.java b/rest-with-spark-java/src/main/java/com/baeldung/Router.java new file mode 100644 index 0000000000..3482184e1e --- /dev/null +++ b/rest-with-spark-java/src/main/java/com/baeldung/Router.java @@ -0,0 +1,50 @@ +package com.baeldung; + +import static spark.Spark.after; +import static spark.Spark.before; +import static spark.Spark.delete; +import static spark.Spark.get; +import static spark.Spark.post; +import static spark.Spark.port; + +import com.baeldung.domain.Book; +import com.baeldung.service.LibraryService; + +public class Router { + + public static void main( String[] args ){ + + port(8080); + + before((request, response) -> { + + //do some filtering stuff + + }); + + after((request, response) -> { + response.type("application/json"); + }); + + get("ListOfBooks", (request, response) -> { + return LibraryService.view(); + }); + + get("SearchBook/:title", (request, response) -> { + return LibraryService.view(request.params("title")); + }); + + post("AddBook/:title/:author/:publisher", (request, response) -> { + Book book = new Book(); + book.setTitle(request.params("title")); + book.setAuthor(request.params("author")); + book.setPublisher(request.params("publisher")); + return LibraryService.add(book); + }); + + delete("DeleteBook/:title", (request, response) -> { + return LibraryService.delete(request.params("title")); + }); + + } +} diff --git a/rest-with-spark-java/src/main/java/com/baeldung/domain/Book.java b/rest-with-spark-java/src/main/java/com/baeldung/domain/Book.java new file mode 100644 index 0000000000..977d5d9f89 --- /dev/null +++ b/rest-with-spark-java/src/main/java/com/baeldung/domain/Book.java @@ -0,0 +1,52 @@ +package com.baeldung.domain; + +public class Book { + + private String title; + private String author; + private String publisher; + + public Book() {} + + public Book(String title, String author, String publisher) { + super(); + this.title = title; + this.author = author; + this.publisher = publisher; + } + + public String getTitle() { + return title; + } + public void setTitle(String title) { + this.title = title; + } + public String getAuthor() { + return author; + } + + public void setAuthor(String author) { + this.author = author; + } + public String getPublisher() { + return publisher; + } + public void setPublisher(String publisher) { + this.publisher = publisher; + } + + protected boolean canEqual(Object other) { + return other instanceof Book; + } + + @Override + public boolean equals(Object o) { + if (o == this) return true; + if (!(o instanceof Book)) return false; + Book other = (Book) o; + if (!other.canEqual((Object)this)) return false; + if (this.getTitle() == null ? other.getTitle() != null : !this.getTitle().equals(other.getTitle())) return false; + return true; + } + +} diff --git a/rest-with-spark-java/src/main/java/com/baeldung/service/LibraryService.java b/rest-with-spark-java/src/main/java/com/baeldung/service/LibraryService.java new file mode 100644 index 0000000000..e4ca4c270c --- /dev/null +++ b/rest-with-spark-java/src/main/java/com/baeldung/service/LibraryService.java @@ -0,0 +1,40 @@ +package com.baeldung.service; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.baeldung.domain.Book; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.ObjectWriter; + +public class LibraryService { + + private static ObjectWriter mapper = new ObjectMapper().writer().withDefaultPrettyPrinter(); + private static Map library = new HashMap(); + + public static String view() throws JsonProcessingException { + List books = new ArrayList(); + library.forEach((key, value) -> { + books.add(value); + }); + return mapper.writeValueAsString(books); + } + + public static String view(String title) throws JsonProcessingException { + return mapper.writeValueAsString(library.get(title)); + } + + public static String add(Book book) throws JsonProcessingException { + library.put(book.getTitle(), book); + return mapper.writeValueAsString(book); + } + + public static String delete(String title) throws JsonProcessingException { + Book deletedBook = library.remove(title); + return mapper.writeValueAsString(deletedBook); + } + +} diff --git a/rest-with-spark-java/src/test/java/com/baeldung/AppTest.java b/rest-with-spark-java/src/test/java/com/baeldung/AppTest.java new file mode 100644 index 0000000000..c7b88dd6d1 --- /dev/null +++ b/rest-with-spark-java/src/test/java/com/baeldung/AppTest.java @@ -0,0 +1,148 @@ +package com.baeldung; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.ArrayList; +import java.util.List; + +import com.baeldung.domain.Book; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; + +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; + +public class AppTest extends TestCase { + + ObjectMapper mapper = new ObjectMapper(); + + public AppTest( String testName ) { + super( testName ); + } + + public static Test suite() { + return new TestSuite( AppTest.class ); + } + + public void testApp() throws IOException, ClassNotFoundException { + + URL url; + HttpURLConnection conn; + BufferedReader br; + String output; + StringBuffer resp; + Book book; + Book temp; + + url = new URL("http://localhost:8080/AddBook/Odessy/YannMartel/GreenLeaves"); + conn = (HttpURLConnection) url.openConnection(); + conn.setRequestMethod("POST"); + conn.getContent(); + br = new BufferedReader(new InputStreamReader( + (conn.getInputStream()))); + resp = new StringBuffer(); + + while ((output = br.readLine()) != null) { + resp.append(output); + } + + book = mapper.readValue(resp.toString(), Book.class); + temp = new Book("Odessy","YannMartel","GreenLeaves"); + + assertEquals(book, temp); + + url = new URL("http://localhost:8080/AddBook/Twilight/StephenieMeyer/LittleBrown"); + conn = (HttpURLConnection) url.openConnection(); + conn.setRequestMethod("POST"); + br = new BufferedReader(new InputStreamReader( + (conn.getInputStream()))); + resp = new StringBuffer(); + + while ((output = br.readLine()) != null) { + resp.append(output); + } + + book = mapper.readValue(resp.toString(), Book.class); + temp = new Book("Twilight","StephenieMeyer","LittleBrown"); + + assertEquals(book, temp); + + url = new URL("http://localhost:8080/ListOfBooks"); + conn = (HttpURLConnection) url.openConnection(); + conn.setRequestMethod("GET"); + br = new BufferedReader(new InputStreamReader( + (conn.getInputStream()))); + resp = new StringBuffer(); + + while ((output = br.readLine()) != null) { + resp.append(output); + } + + List books = new ArrayList(); + + books.add(new Book("Odessy","YannMartel","GreenLeaves")); + books.add(new Book("Twilight","StephenieMeyer","LittleBrown")); + + List listOfBooks = mapper.readValue(resp.toString(), new TypeReference>(){}); + + assertEquals(books, listOfBooks); + + url = new URL("http://localhost:8080/SearchBook/Twilight"); + conn = (HttpURLConnection) url.openConnection(); + conn.setRequestMethod("GET"); + br = new BufferedReader(new InputStreamReader( + (conn.getInputStream()))); + resp = new StringBuffer(); + + while ((output = br.readLine()) != null) { + resp.append(output); + } + + book = mapper.readValue(resp.toString(), Book.class); + temp = new Book("Twilight","StephenieMeyer","LittleBrown"); + + assertEquals(book, temp); + + url = new URL("http://localhost:8080/DeleteBook/Twilight"); + conn = (HttpURLConnection) url.openConnection(); + conn.setRequestMethod("DELETE"); + br = new BufferedReader(new InputStreamReader( + (conn.getInputStream()))); + resp = new StringBuffer(); + + while ((output = br.readLine()) != null) { + resp.append(output); + } + + book = mapper.readValue(resp.toString(), Book.class); + temp = new Book("Twilight","StephenieMeyer","LittleBrown"); + + assertEquals(book, temp); + + url = new URL("http://localhost:8080/ListOfBooks"); + conn = (HttpURLConnection) url.openConnection(); + conn.setRequestMethod("GET"); + br = new BufferedReader(new InputStreamReader( + (conn.getInputStream()))); + resp = new StringBuffer(); + + while ((output = br.readLine()) != null) { + resp.append(output); + } + + books = new ArrayList(); + + books.add(new Book("Odessy","YannMartel","GreenLeaves")); + listOfBooks = mapper.readValue(resp.toString(), new TypeReference>(){}); + + assertEquals(books, listOfBooks); + + conn.disconnect(); + + } + +} diff --git a/spark-java/pom.xml b/spark-java/pom.xml new file mode 100644 index 0000000000..5b8923322a --- /dev/null +++ b/spark-java/pom.xml @@ -0,0 +1,29 @@ + + + 4.0.0 + com.baeldung + spark-java + 0.1.0-SNAPSHOT + spark-java + http://maven.apache.org + + UTF-8 + 1.8 + 1.8 + + + + com.sparkjava + spark-core + 2.5.4 + + + + com.google.code.gson + gson + 2.8.0 + + + diff --git a/spark-java/src/main/java/com/baeldung/sparkjava/HelloWorldService.java b/spark-java/src/main/java/com/baeldung/sparkjava/HelloWorldService.java new file mode 100644 index 0000000000..55b3fbe3f2 --- /dev/null +++ b/spark-java/src/main/java/com/baeldung/sparkjava/HelloWorldService.java @@ -0,0 +1,12 @@ +package com.baeldung.sparkjava; +import static spark.Spark.*; + +public class HelloWorldService { + public static void main(String[] args) { + get("/hello", (req,res)->"Hello, Baeldung"); + + get("/hello/:name", (req,res)->{ + return "Hello: "+ req.params(":name"); + }); + } +} diff --git a/spark-java/src/main/java/com/baeldung/sparkjava/SparkRestExample.java b/spark-java/src/main/java/com/baeldung/sparkjava/SparkRestExample.java new file mode 100644 index 0000000000..bb610fd7f0 --- /dev/null +++ b/spark-java/src/main/java/com/baeldung/sparkjava/SparkRestExample.java @@ -0,0 +1,76 @@ +package com.baeldung.sparkjava; + +import static spark.Spark.delete; +import static spark.Spark.get; +import static spark.Spark.options; +import static spark.Spark.post; +import static spark.Spark.put; + +import com.google.gson.Gson; + +public class SparkRestExample { + public static void main(String[] args) { + final UserService userService = new UserServiceMapImpl(); + + post("/users", (request, response) -> { + response.type("application/json"); + + User user = new Gson().fromJson(request.body(), User.class); + userService.addUser(user); + + return new Gson().toJson(new StandardResponse(StatusResponse.SUCCESS)); + }); + + get("/users", (request, response) -> { + response.type("application/json"); + + return new Gson().toJson( + new StandardResponse(StatusResponse.SUCCESS,new Gson() + .toJsonTree(userService.getUsers()))); + }); + + get("/users/:id", (request, response) -> { + response.type("application/json"); + + return new Gson().toJson( + new StandardResponse(StatusResponse.SUCCESS,new Gson() + .toJsonTree(userService.getUser(request.params(":id"))))); + }); + + put("/users/:id", (request, response) -> { + response.type("application/json"); + + User toEdit = new Gson().fromJson(request.body(), User.class); + User editedUser = userService.editUser(toEdit); + + if (editedUser != null) { + return new Gson().toJson( + new StandardResponse(StatusResponse.SUCCESS,new Gson() + .toJsonTree(editedUser))); + }else { + return new Gson().toJson( + new StandardResponse(StatusResponse.ERROR,new Gson() + .toJson("User not found or error in edit"))); + } + }); + + delete("/users/:id", (request, response) -> { + response.type("application/json"); + + userService.deleteUser(request.params(":id")); + return new Gson().toJson( + new StandardResponse(StatusResponse.SUCCESS, "user deleted")); + }); + + options("/users/:id", (request, response) -> { + response.type("application/json"); + + return new Gson().toJson( + new StandardResponse(StatusResponse.SUCCESS, + (userService.userExist( + request.params(":id"))) ? "User exists" : "User does not exists" )); + }); + + } + +} diff --git a/spark-java/src/main/java/com/baeldung/sparkjava/StandardResponse.java b/spark-java/src/main/java/com/baeldung/sparkjava/StandardResponse.java new file mode 100644 index 0000000000..51f1954e57 --- /dev/null +++ b/spark-java/src/main/java/com/baeldung/sparkjava/StandardResponse.java @@ -0,0 +1,47 @@ +package com.baeldung.sparkjava; + +import com.google.gson.JsonElement; + +public class StandardResponse { + private StatusResponse status; + private String message; + private JsonElement data; + + public StandardResponse(StatusResponse status) { + this.status = status; + } + + public StandardResponse(StatusResponse status, String message) { + this.status = status; + this.message = message; + } + + public StandardResponse(StatusResponse status, JsonElement data) { + this.status = status; + this.data = data; + } + + public StatusResponse getStatus() { + return status; + } + + public void setStatus(StatusResponse status) { + this.status = status; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + public JsonElement getData() { + return data; + } + + public void setData(JsonElement data) { + this.data = data; + } +} diff --git a/spark-java/src/main/java/com/baeldung/sparkjava/StatusResponse.java b/spark-java/src/main/java/com/baeldung/sparkjava/StatusResponse.java new file mode 100644 index 0000000000..0e3137293a --- /dev/null +++ b/spark-java/src/main/java/com/baeldung/sparkjava/StatusResponse.java @@ -0,0 +1,17 @@ +package com.baeldung.sparkjava; + +public enum StatusResponse { + SUCCESS ("Success"), + ERROR ("Error"); + + final private String status; + + StatusResponse(String status) { + this.status = status; + } + + public String getStatus() { + return status; + } + +} diff --git a/spark-java/src/main/java/com/baeldung/sparkjava/User.java b/spark-java/src/main/java/com/baeldung/sparkjava/User.java new file mode 100644 index 0000000000..7447671470 --- /dev/null +++ b/spark-java/src/main/java/com/baeldung/sparkjava/User.java @@ -0,0 +1,59 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package com.baeldung.sparkjava; + +class User { + + private String id; + private String firstName; + private String lastName; + private String email; + + public User(String id, String firstName, String lastName, String email) { + super(); + this.id = id; + this.firstName = firstName; + this.lastName = lastName; + this.email = email; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + @Override + public String toString() { + return new StringBuffer().append(getEmail()).toString(); + } +} diff --git a/spark-java/src/main/java/com/baeldung/sparkjava/UserException.java b/spark-java/src/main/java/com/baeldung/sparkjava/UserException.java new file mode 100644 index 0000000000..929c0dfdb7 --- /dev/null +++ b/spark-java/src/main/java/com/baeldung/sparkjava/UserException.java @@ -0,0 +1,13 @@ +package com.baeldung.sparkjava; + +public class UserException extends Exception{ + + public UserException() { + super(); + } + + public UserException(String message) { + super(message); + } + +} diff --git a/spark-java/src/main/java/com/baeldung/sparkjava/UserService.java b/spark-java/src/main/java/com/baeldung/sparkjava/UserService.java new file mode 100644 index 0000000000..9b1fa7be3a --- /dev/null +++ b/spark-java/src/main/java/com/baeldung/sparkjava/UserService.java @@ -0,0 +1,12 @@ +package com.baeldung.sparkjava; + +import java.util.Collection; + +public interface UserService { + public void addUser (User user) ; + public Collection getUsers () ; + public User getUser (String id) ; + public User editUser (User user) throws UserException; + public void deleteUser (String id) ; + public boolean userExist (String id); +} diff --git a/spark-java/src/main/java/com/baeldung/sparkjava/UserServiceMapImpl.java b/spark-java/src/main/java/com/baeldung/sparkjava/UserServiceMapImpl.java new file mode 100644 index 0000000000..0b5072647f --- /dev/null +++ b/spark-java/src/main/java/com/baeldung/sparkjava/UserServiceMapImpl.java @@ -0,0 +1,68 @@ +package com.baeldung.sparkjava; + +import java.util.Collection; +import java.util.HashMap; + +public class UserServiceMapImpl implements UserService{ + private HashMap userMap; + + public UserServiceMapImpl() { + userMap = new HashMap<>(); + } + + @Override + public void addUser (User user) { + userMap.put(user.getId(), user); + } + + @Override + public Collection getUsers () { + return userMap.values(); + } + + @Override + public User getUser (String id) { + return userMap.get(id); + } + + @Override + public User editUser (User forEdit) throws UserException{ + try{ + if (forEdit.getId() == null) + throw new UserException("ID cannot be blank"); + + User toEdit = userMap.get(forEdit.getId()); + + if (toEdit == null ) + throw new UserException("User not found"); + + if (forEdit.getEmail()!=null) { + toEdit.setEmail(forEdit.getEmail()); + } + if (forEdit.getFirstName()!=null) { + toEdit.setFirstName(forEdit.getFirstName()); + } + if (forEdit.getLastName()!=null) { + toEdit.setLastName(forEdit.getLastName()); + } + if (forEdit.getId()!=null) { + toEdit.setId(forEdit.getId()); + } + + return toEdit; + }catch (Exception ex) { + throw new UserException(ex.getMessage()); + } + } + + @Override + public void deleteUser (String id) { + userMap.remove(id); + } + + @Override + public boolean userExist (String id) { + return userMap.containsKey(id); + } + +} diff --git a/spring-boot/MyFirstSpringBoot/pom.xml b/spring-boot/MyFirstSpringBoot/pom.xml deleted file mode 100644 index a5cbb37263..0000000000 --- a/spring-boot/MyFirstSpringBoot/pom.xml +++ /dev/null @@ -1,39 +0,0 @@ - - 4.0.0 - - com.baeldung - MyFirstSpringBoot - 0.0.1-SNAPSHOT - jar - - - org.springframework.boot - spring-boot-starter-parent - 1.4.3.RELEASE - - - MyFirstSpringBoot - http://maven.apache.org - - - UTF-8 - - - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-test - test - - - junit - junit - test - - - diff --git a/spring-boot/MyFirstSpringBoot/src/main/java/com/baeldung/App.java b/spring-boot/src/main/java/com/baeldung/intro/App.java similarity index 86% rename from spring-boot/MyFirstSpringBoot/src/main/java/com/baeldung/App.java rename to spring-boot/src/main/java/com/baeldung/intro/App.java index d7cc90fcb9..30e1c2b5ba 100644 --- a/spring-boot/MyFirstSpringBoot/src/main/java/com/baeldung/App.java +++ b/spring-boot/src/main/java/com/baeldung/intro/App.java @@ -1,4 +1,4 @@ -package com.baeldung; +package com.baeldung.intro; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/spring-boot/MyFirstSpringBoot/src/main/java/com/baeldung/controller/HomeController.java b/spring-boot/src/main/java/com/baeldung/intro/controller/HomeController.java similarity index 86% rename from spring-boot/MyFirstSpringBoot/src/main/java/com/baeldung/controller/HomeController.java rename to spring-boot/src/main/java/com/baeldung/intro/controller/HomeController.java index 757e0a06b1..9109b0a292 100644 --- a/spring-boot/MyFirstSpringBoot/src/main/java/com/baeldung/controller/HomeController.java +++ b/spring-boot/src/main/java/com/baeldung/intro/controller/HomeController.java @@ -1,4 +1,4 @@ -package com.baeldung.controller; +package com.baeldung.intro.controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; diff --git a/spring-boot/MyFirstSpringBoot/src/main/resources/public/error/404.html b/spring-boot/src/main/resources/public/error/404.html similarity index 100% rename from spring-boot/MyFirstSpringBoot/src/main/resources/public/error/404.html rename to spring-boot/src/main/resources/public/error/404.html diff --git a/spring-boot/MyFirstSpringBoot/src/test/java/com/baeldung/AppTest.java b/spring-boot/src/test/java/com/baeldung/intro/AppTest.java similarity index 95% rename from spring-boot/MyFirstSpringBoot/src/test/java/com/baeldung/AppTest.java rename to spring-boot/src/test/java/com/baeldung/intro/AppTest.java index 8450740863..749fe68838 100644 --- a/spring-boot/MyFirstSpringBoot/src/test/java/com/baeldung/AppTest.java +++ b/spring-boot/src/test/java/com/baeldung/intro/AppTest.java @@ -1,4 +1,4 @@ -package com.baeldung; +package com.baeldung.intro; import static org.hamcrest.Matchers.equalTo; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; diff --git a/spring-cloud/spring-cloud-rest/application-config/resource.properties b/spring-cloud/spring-cloud-rest/application-config/resource.properties new file mode 100644 index 0000000000..759bb87895 --- /dev/null +++ b/spring-cloud/spring-cloud-rest/application-config/resource.properties @@ -0,0 +1,20 @@ +spring.application.name=resource +#server.port=0 + +#### cloud +eureka.client.serviceUrl.defaultZone=${EUREKA_URI:http://system:systemPass@localhost:8761/eureka} +eureka.instance.preferIpAddress=true + +#### persistence +spring.datasource.driver-class-name=org.h2.Driver +spring.datasource.url=jdbc:h2:mem:cloud_rest;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE +spring.datasource.username=sa +spring.datasource.password= + +#### security +security.basic.enabled=true +security.basic.path=/** +security.user.name=user +security.user.password=userPass +security.user.role=USER +security.sessions=always \ No newline at end of file diff --git a/spring-cloud/spring-cloud-rest/application-config/spring-cloud-rest-server.properties b/spring-cloud/spring-cloud-rest/application-config/spring-cloud-rest-server.properties new file mode 100644 index 0000000000..96cacdb5fb --- /dev/null +++ b/spring-cloud/spring-cloud-rest/application-config/spring-cloud-rest-server.properties @@ -0,0 +1,16 @@ +spring.application.name=spring-cloud-rest-server +server.port=8761 + +#### cloud +eureka.instance.hostname=localhost +eureka.client.serviceUrl.defaultZone=${EUREKA_URI:http://system:systemPass@localhost:8761/eureka} +eureka.client.registerWithEureka=false +eureka.client.fetchRegistry=false + +#### security +security.basic.enabled=true +security.basic.path=/** +security.user.name=system +security.user.password=systemPass +security.user.role=ADMIN +security.sessions=always \ No newline at end of file diff --git a/spring-cloud/spring-cloud-rest/pom.xml b/spring-cloud/spring-cloud-rest/pom.xml index fef6d93cfc..376ce96b95 100644 --- a/spring-cloud/spring-cloud-rest/pom.xml +++ b/spring-cloud/spring-cloud-rest/pom.xml @@ -7,8 +7,10 @@ spring-cloud-rest 1.0.0-SNAPSHOT + spring-cloud-rest-config spring-cloud-rest-server - spring-cloud-rest-client + spring-cloud-rest-client-1 + spring-cloud-rest-client-2 pom diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-client-1/pom.xml b/spring-cloud/spring-cloud-rest/spring-cloud-rest-client-1/pom.xml new file mode 100644 index 0000000000..ac878d1652 --- /dev/null +++ b/spring-cloud/spring-cloud-rest/spring-cloud-rest-client-1/pom.xml @@ -0,0 +1,111 @@ + + + 4.0.0 + + org.baeldung + spring-cloud-rest-client-1 + 0.0.1-SNAPSHOT + jar + + spring-cloud-rest-client-1 + Client Service for books + + + org.springframework.boot + spring-boot-starter-parent + 1.4.3.RELEASE + + + + + UTF-8 + UTF-8 + 1.8 + 3.0.1 + + + + + org.springframework.cloud + spring-cloud-starter-config + + + org.springframework.cloud + spring-cloud-starter-eureka + + + org.springframework.boot + spring-boot-starter-data-jpa + + + com.h2database + h2 + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-data-rest + + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.session + spring-session + + + org.springframework.boot + spring-boot-starter-data-redis + + + + org.springframework.boot + spring-boot-starter-test + test + + + io.rest-assured + rest-assured + ${rest-assured.version} + + + + + + + + org.springframework.cloud + spring-cloud-dependencies + Camden.SR4 + pom + import + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + org.apache.maven.plugins + maven-surefire-plugin + + + **/*IntegrationTest.java + **/*LiveTest.java + + + + + + + + diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-client-1/src/main/java/org/baeldung/SessionConfig.java b/spring-cloud/spring-cloud-rest/spring-cloud-rest-client-1/src/main/java/org/baeldung/SessionConfig.java new file mode 100644 index 0000000000..bd1c0013ca --- /dev/null +++ b/spring-cloud/spring-cloud-rest/spring-cloud-rest-client-1/src/main/java/org/baeldung/SessionConfig.java @@ -0,0 +1,8 @@ +package org.baeldung; + +import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession; +import org.springframework.session.web.context.AbstractHttpSessionApplicationInitializer; + +@EnableRedisHttpSession +public class SessionConfig extends AbstractHttpSessionApplicationInitializer { +} diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-client/src/main/java/org/baeldung/SpringCloudRestClientApplication.java b/spring-cloud/spring-cloud-rest/spring-cloud-rest-client-1/src/main/java/org/baeldung/SpringCloudRestClientApplication.java similarity index 100% rename from spring-cloud/spring-cloud-rest/spring-cloud-rest-client/src/main/java/org/baeldung/SpringCloudRestClientApplication.java rename to spring-cloud/spring-cloud-rest/spring-cloud-rest-client-1/src/main/java/org/baeldung/SpringCloudRestClientApplication.java diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-client-1/src/main/java/org/baeldung/persistence/dao/BookRepository.java b/spring-cloud/spring-cloud-rest/spring-cloud-rest-client-1/src/main/java/org/baeldung/persistence/dao/BookRepository.java new file mode 100644 index 0000000000..1b0c32218f --- /dev/null +++ b/spring-cloud/spring-cloud-rest/spring-cloud-rest-client-1/src/main/java/org/baeldung/persistence/dao/BookRepository.java @@ -0,0 +1,13 @@ +package org.baeldung.persistence.dao; + +import org.baeldung.persistence.model.Book; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.repository.CrudRepository; +import org.springframework.data.repository.query.Param; +import org.springframework.data.rest.core.annotation.RepositoryRestResource; + +@RepositoryRestResource(collectionResourceRel = "books", path = "books") +public interface BookRepository extends CrudRepository { + Page findByTitle(@Param("title") String title, Pageable pageable); +} diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-client/src/main/java/org/baeldung/persistence/model/Book.java b/spring-cloud/spring-cloud-rest/spring-cloud-rest-client-1/src/main/java/org/baeldung/persistence/model/Book.java similarity index 79% rename from spring-cloud/spring-cloud-rest/spring-cloud-rest-client/src/main/java/org/baeldung/persistence/model/Book.java rename to spring-cloud/spring-cloud-rest/spring-cloud-rest-client-1/src/main/java/org/baeldung/persistence/model/Book.java index 69d217b096..80336d9da9 100644 --- a/spring-cloud/spring-cloud-rest/spring-cloud-rest-client/src/main/java/org/baeldung/persistence/model/Book.java +++ b/spring-cloud/spring-cloud-rest/spring-cloud-rest-client-1/src/main/java/org/baeldung/persistence/model/Book.java @@ -12,12 +12,9 @@ public class Book { @GeneratedValue(strategy = GenerationType.AUTO) private long id; - @Column(nullable = false) + @Column(nullable = false, unique = true) private String title; - @Column(nullable = false) - private String isbn; - @Column(nullable = false) private String author; @@ -27,10 +24,9 @@ public class Book { super(); } - public Book(String title, String isbn, String author) { + public Book(String title, String author) { super(); this.title = title; - this.isbn = isbn; this.author = author; } @@ -52,14 +48,6 @@ public class Book { this.title = title; } - public String getIsbn() { - return isbn; - } - - public void setIsbn(String isbn) { - this.isbn = isbn; - } - public String getAuthor() { return author; } @@ -76,7 +64,6 @@ public class Book { int result = 1; result = (prime * result) + ((author == null) ? 0 : author.hashCode()); result = (prime * result) + (int) (id ^ (id >>> 32)); - result = (prime * result) + ((isbn == null) ? 0 : isbn.hashCode()); result = (prime * result) + ((title == null) ? 0 : title.hashCode()); return result; } @@ -103,13 +90,7 @@ public class Book { if (id != other.id) { return false; } - if (isbn == null) { - if (other.isbn != null) { - return false; - } - } else if (!isbn.equals(other.isbn)) { - return false; - } + if (title == null) { if (other.title != null) { return false; @@ -127,8 +108,6 @@ public class Book { .append(id) .append(", title=") .append(title) - .append(", isbn=") - .append(isbn) .append(", author=") .append(author) .append("]"); diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-client-1/src/main/resources/bootstrap.properties b/spring-cloud/spring-cloud-rest/spring-cloud-rest-client-1/src/main/resources/bootstrap.properties new file mode 100644 index 0000000000..2cb3b71ca7 --- /dev/null +++ b/spring-cloud/spring-cloud-rest/spring-cloud-rest-client-1/src/main/resources/bootstrap.properties @@ -0,0 +1,9 @@ +spring.cloud.config.name=resource +spring.cloud.config.discovery.service-id=config +spring.cloud.config.discovery.enabled=true +spring.cloud.config.username=configUser +spring.cloud.config.password=configPassword + +eureka.client.serviceUrl.defaultZone=http://system:systemPass@localhost:8761/eureka + +server.port=8084 \ No newline at end of file diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-client-1/src/test/java/org/baeldung/RestApiLiveTest.java b/spring-cloud/spring-cloud-rest/spring-cloud-rest-client-1/src/test/java/org/baeldung/RestApiLiveTest.java new file mode 100644 index 0000000000..4ff54e44d2 --- /dev/null +++ b/spring-cloud/spring-cloud-rest/spring-cloud-rest-client-1/src/test/java/org/baeldung/RestApiLiveTest.java @@ -0,0 +1,174 @@ +package org.baeldung; + +import static io.restassured.RestAssured.preemptive; +import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.randomNumeric; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import io.restassured.RestAssured; +import io.restassured.response.Response; + +import org.baeldung.persistence.model.Book; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = { SpringCloudRestClientApplication.class }, webEnvironment = WebEnvironment.DEFINED_PORT) +public class RestApiLiveTest { + + private static final String API_URI = "http://localhost:8084/books"; + + @Before + public void setUp() { + RestAssured.authentication = preemptive().basic("user", "userPass"); + } + + // GET + + @Test + public void whenGetAllBooks_thenOK() { + final Response response = RestAssured.get(API_URI); + assertEquals(HttpStatus.OK.value(), response.getStatusCode()); + } + + @Test + public void whenGetCreatedBookById_thenOK() { + final Book book = createRandomBook(); + final String location = createBookAsUri(book); + + final Response response = RestAssured.get(location); + assertEquals(HttpStatus.OK.value(), response.getStatusCode()); + assertEquals(book.getTitle(), response.jsonPath() + .get("title")); + } + + @Test + public void whenGetCreatedBookByName_thenOK() { + final Book book = createRandomBook(); + createBookAsUri(book); + + final Response response = RestAssured.get(API_URI + "/search/findByTitle?title=" + book.getTitle()); + assertEquals(HttpStatus.OK.value(), response.getStatusCode()); + assertTrue(response.jsonPath() + .getLong("page.totalElements") > 0); + } + + @Test + public void whenGetNotExistBookById_thenNotFound() { + final Response response = RestAssured.get(API_URI + "/" + randomNumeric(4)); + assertEquals(HttpStatus.NOT_FOUND.value(), response.getStatusCode()); + } + + @Test + public void whenGetNotExistBookByName_thenNotFound() { + final Response response = RestAssured.get(API_URI + "/search/findByTitle?title=" + randomAlphabetic(20)); + assertEquals(HttpStatus.OK.value(), response.getStatusCode()); + assertTrue(response.jsonPath() + .getLong("page.totalElements") == 0); + } + + // POST + @Test + public void whenCreateNewBook_thenCreated() { + final Book book = createRandomBook(); + + final Response response = RestAssured.given() + .contentType(MediaType.APPLICATION_JSON_VALUE) + .body(book) + .post(API_URI); + assertEquals(HttpStatus.CREATED.value(), response.getStatusCode()); + } + + @Test + public void whenCreateDuplicateBook_thenError() { + final Book book = createRandomBook(); + createBookAsUri(book); + + // duplicate + final Response response = RestAssured.given() + .contentType(MediaType.APPLICATION_JSON_VALUE) + .body(book) + .post(API_URI); + assertEquals(HttpStatus.CONFLICT.value(), response.getStatusCode()); + } + + @Test + public void whenInvalidBook_thenError() { + final Book book = createRandomBook(); + book.setAuthor(null); + + final Response response = RestAssured.given() + .contentType(MediaType.APPLICATION_JSON_VALUE) + .body(book) + .post(API_URI); + assertEquals(HttpStatus.CONFLICT.value(), response.getStatusCode()); + } + + @Test + public void whenUpdateCreatedBook_thenUpdated() { + // create + final Book book = createRandomBook(); + final String location = createBookAsUri(book); + + // update + book.setAuthor("newAuthor"); + Response response = RestAssured.given() + .contentType(MediaType.APPLICATION_JSON_VALUE) + .body(book) + .put(location); + assertEquals(HttpStatus.OK.value(), response.getStatusCode()); + + // check if changes saved + response = RestAssured.get(location); + assertEquals(HttpStatus.OK.value(), response.getStatusCode()); + assertEquals("newAuthor", response.jsonPath() + .get("author")); + + } + + @Test + public void whenDeleteCreatedBook_thenOk() { + // create + final Book book = createRandomBook(); + final String location = createBookAsUri(book); + + // delete + Response response = RestAssured.delete(location); + assertEquals(HttpStatus.NO_CONTENT.value(), response.getStatusCode()); + + // confirm it was deleted + response = RestAssured.get(location); + assertEquals(HttpStatus.NOT_FOUND.value(), response.getStatusCode()); + } + + @Test + public void whenDeleteNotExistBook_thenError() { + final Response response = RestAssured.delete(API_URI + "/" + randomNumeric(4)); + assertEquals(HttpStatus.NOT_FOUND.value(), response.getStatusCode()); + } + + // =============================== Util + + private Book createRandomBook() { + final Book book = new Book(); + book.setTitle(randomAlphabetic(10)); + book.setAuthor(randomAlphabetic(15)); + return book; + } + + private String createBookAsUri(Book book) { + final Response response = RestAssured.given() + .contentType(MediaType.APPLICATION_JSON_VALUE) + .body(book) + .post(API_URI); + return response.jsonPath() + .get("_links.self.href"); + } + +} diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-client-1/src/test/java/org/baeldung/SessionLiveTest.java b/spring-cloud/spring-cloud-rest/spring-cloud-rest-client-1/src/test/java/org/baeldung/SessionLiveTest.java new file mode 100644 index 0000000000..a3ca722107 --- /dev/null +++ b/spring-cloud/spring-cloud-rest/spring-cloud-rest-client-1/src/test/java/org/baeldung/SessionLiveTest.java @@ -0,0 +1,75 @@ +package org.baeldung; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import io.restassured.RestAssured; +import io.restassured.response.Response; + +import java.util.Set; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.http.HttpStatus; +import org.springframework.test.context.junit4.SpringRunner; + +import redis.clients.jedis.Jedis; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = { SpringCloudRestClientApplication.class, SessionConfig.class }, webEnvironment = WebEnvironment.DEFINED_PORT) +public class SessionLiveTest { + + private Jedis jedis; + private static final String API_URI = "http://localhost:8084/books"; + + @Before + public void setUp() { + jedis = new Jedis("localhost", 6379); + jedis.flushAll(); + } + + @Test + public void whenStart_thenNoSessionsExist() { + final Set result = jedis.keys("*"); + assertEquals(0, result.size()); + } + + @Test + public void givenUnauthorizeUser_whenAccessResources_then_unAuthorized() { + final Response response = RestAssured.get(API_URI); + assertEquals(HttpStatus.UNAUTHORIZED.value(), response.getStatusCode()); + } + + @Test + public void givenAuthorizedUser_whenDeleteSession_thenUnauthorized() { + // authorize User + Response response = RestAssured.given() + .auth() + .preemptive() + .basic("user", "userPass") + .get(API_URI); + assertEquals(HttpStatus.OK.value(), response.getStatusCode()); + final String sessionCookie = response.getCookie("SESSION"); + + // check redis + final Set redisResult = jedis.keys("*"); + assertTrue(redisResult.size() > 0); + + // login with cookie + response = RestAssured.given() + .cookie("SESSION", sessionCookie) + .get(API_URI); + assertEquals(HttpStatus.OK.value(), response.getStatusCode()); + + // empty redis + jedis.flushAll(); + + // login with cookie again + response = RestAssured.given() + .cookie("SESSION", sessionCookie) + .get(API_URI); + assertEquals(HttpStatus.UNAUTHORIZED.value(), response.getStatusCode()); + } +} diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-client/src/test/java/org/baeldung/SpringCloudRestClientApplicationTests.java b/spring-cloud/spring-cloud-rest/spring-cloud-rest-client-1/src/test/java/org/baeldung/SpringCloudRestClientApplicationTests.java similarity index 100% rename from spring-cloud/spring-cloud-rest/spring-cloud-rest-client/src/test/java/org/baeldung/SpringCloudRestClientApplicationTests.java rename to spring-cloud/spring-cloud-rest/spring-cloud-rest-client-1/src/test/java/org/baeldung/SpringCloudRestClientApplicationTests.java diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-client-1/src/test/resources/application.properties b/spring-cloud/spring-cloud-rest/spring-cloud-rest-client-1/src/test/resources/application.properties new file mode 100644 index 0000000000..ece9ca1d94 --- /dev/null +++ b/spring-cloud/spring-cloud-rest/spring-cloud-rest-client-1/src/test/resources/application.properties @@ -0,0 +1,19 @@ +#### cloud +spring.application.name=spring-cloud-eureka-client +server.port=8084 +eureka.client.serviceUrl.defaultZone=${EUREKA_URI:http://system:systemPass@localhost:8761/eureka} +eureka.instance.preferIpAddress=true + +#### persistence +spring.datasource.driver-class-name=org.h2.Driver +spring.datasource.url=jdbc:h2:mem:cloud_rest;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE +spring.datasource.username=sa +spring.datasource.password= + +#### security +security.basic.enabled=true +security.basic.path=/** +security.user.name=user +security.user.password=userPass +security.user.role=USER +security.sessions=always \ No newline at end of file diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-client-2/pom.xml b/spring-cloud/spring-cloud-rest/spring-cloud-rest-client-2/pom.xml new file mode 100644 index 0000000000..6645e1382c --- /dev/null +++ b/spring-cloud/spring-cloud-rest/spring-cloud-rest-client-2/pom.xml @@ -0,0 +1,111 @@ + + + 4.0.0 + + org.baeldung + spring-cloud-rest-client-2 + 0.0.1-SNAPSHOT + jar + + spring-cloud-rest-client-2 + Client Service for book reviews + + + org.springframework.boot + spring-boot-starter-parent + 1.4.3.RELEASE + + + + + UTF-8 + UTF-8 + 1.8 + 3.0.1 + + + + + org.springframework.cloud + spring-cloud-starter-config + + + org.springframework.cloud + spring-cloud-starter-eureka + + + org.springframework.boot + spring-boot-starter-data-jpa + + + com.h2database + h2 + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-data-rest + + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.session + spring-session + + + org.springframework.boot + spring-boot-starter-data-redis + + + + org.springframework.boot + spring-boot-starter-test + test + + + io.rest-assured + rest-assured + ${rest-assured.version} + + + + + + + + org.springframework.cloud + spring-cloud-dependencies + Camden.SR4 + pom + import + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + org.apache.maven.plugins + maven-surefire-plugin + + + **/*IntegrationTest.java + **/*LiveTest.java + + + + + + + + diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-client-2/src/main/java/org/baeldung/SessionConfig.java b/spring-cloud/spring-cloud-rest/spring-cloud-rest-client-2/src/main/java/org/baeldung/SessionConfig.java new file mode 100644 index 0000000000..bd1c0013ca --- /dev/null +++ b/spring-cloud/spring-cloud-rest/spring-cloud-rest-client-2/src/main/java/org/baeldung/SessionConfig.java @@ -0,0 +1,8 @@ +package org.baeldung; + +import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession; +import org.springframework.session.web.context.AbstractHttpSessionApplicationInitializer; + +@EnableRedisHttpSession +public class SessionConfig extends AbstractHttpSessionApplicationInitializer { +} diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-client-2/src/main/java/org/baeldung/SpringCloudRestClientApplication.java b/spring-cloud/spring-cloud-rest/spring-cloud-rest-client-2/src/main/java/org/baeldung/SpringCloudRestClientApplication.java new file mode 100644 index 0000000000..a13aaa54bc --- /dev/null +++ b/spring-cloud/spring-cloud-rest/spring-cloud-rest-client-2/src/main/java/org/baeldung/SpringCloudRestClientApplication.java @@ -0,0 +1,14 @@ +package org.baeldung; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.netflix.eureka.EnableEurekaClient; + +@SpringBootApplication +@EnableEurekaClient +public class SpringCloudRestClientApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringCloudRestClientApplication.class, args); + } +} diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-client-2/src/main/java/org/baeldung/persistence/dao/BookReviewRepository.java b/spring-cloud/spring-cloud-rest/spring-cloud-rest-client-2/src/main/java/org/baeldung/persistence/dao/BookReviewRepository.java new file mode 100644 index 0000000000..2107786d62 --- /dev/null +++ b/spring-cloud/spring-cloud-rest/spring-cloud-rest-client-2/src/main/java/org/baeldung/persistence/dao/BookReviewRepository.java @@ -0,0 +1,13 @@ +package org.baeldung.persistence.dao; + +import org.baeldung.persistence.model.BookReview; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.repository.CrudRepository; +import org.springframework.data.repository.query.Param; +import org.springframework.data.rest.core.annotation.RepositoryRestResource; + +@RepositoryRestResource(collectionResourceRel = "reviews", path = "reviews") +public interface BookReviewRepository extends CrudRepository { + Page findByBookId(@Param("bookId") long bookId, Pageable pageable); +} diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-client-2/src/main/java/org/baeldung/persistence/model/BookReview.java b/spring-cloud/spring-cloud-rest/spring-cloud-rest-client-2/src/main/java/org/baeldung/persistence/model/BookReview.java new file mode 100644 index 0000000000..5341df7cb6 --- /dev/null +++ b/spring-cloud/spring-cloud-rest/spring-cloud-rest-client-2/src/main/java/org/baeldung/persistence/model/BookReview.java @@ -0,0 +1,128 @@ +package org.baeldung.persistence.model; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class BookReview { + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private long id; + + private String content; + + private int rating; + + @Column(nullable = false) + private Long bookId; + + // + + public BookReview() { + super(); + } + + public BookReview(String content, int rating, long bookId) { + super(); + this.content = content; + this.rating = rating; + this.bookId = bookId; + } + + // + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getContent() { + return content; + } + + public void setContent(String content) { + this.content = content; + } + + public int getRating() { + return rating; + } + + public void setRating(int rating) { + this.rating = rating; + } + + public Long getBookId() { + return bookId; + } + + public void setBookId(Long bookId) { + this.bookId = bookId; + } + + // + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = (prime * result) + (int) (bookId ^ (bookId >>> 32)); + result = (prime * result) + ((content == null) ? 0 : content.hashCode()); + result = (prime * result) + (int) (id ^ (id >>> 32)); + result = (prime * result) + rating; + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final BookReview other = (BookReview) obj; + if (bookId != other.bookId) { + return false; + } + if (content == null) { + if (other.content != null) { + return false; + } + } else if (!content.equals(other.content)) { + return false; + } + if (id != other.id) { + return false; + } + if (rating != other.rating) { + return false; + } + return true; + } + + // + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("BookReview [id=") + .append(id) + .append(", content=") + .append(content) + .append(", rating=") + .append(rating) + .append(", bookId=") + .append(bookId) + .append("]"); + return builder.toString(); + } + +} diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-client-2/src/main/resources/bootstrap.properties b/spring-cloud/spring-cloud-rest/spring-cloud-rest-client-2/src/main/resources/bootstrap.properties new file mode 100644 index 0000000000..d6e642afcb --- /dev/null +++ b/spring-cloud/spring-cloud-rest/spring-cloud-rest-client-2/src/main/resources/bootstrap.properties @@ -0,0 +1,9 @@ +spring.cloud.config.name=resource +spring.cloud.config.discovery.service-id=config +spring.cloud.config.discovery.enabled=true +spring.cloud.config.username=configUser +spring.cloud.config.password=configPassword + +eureka.client.serviceUrl.defaultZone=http://system:systemPass@localhost:8761/eureka + +server.port=8085 \ No newline at end of file diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-client-2/src/test/java/org/baeldung/RestApiLiveTest.java b/spring-cloud/spring-cloud-rest/spring-cloud-rest-client-2/src/test/java/org/baeldung/RestApiLiveTest.java new file mode 100644 index 0000000000..1899385e2a --- /dev/null +++ b/spring-cloud/spring-cloud-rest/spring-cloud-rest-client-2/src/test/java/org/baeldung/RestApiLiveTest.java @@ -0,0 +1,162 @@ +package org.baeldung; + +import static io.restassured.RestAssured.preemptive; +import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.randomNumeric; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import io.restassured.RestAssured; +import io.restassured.response.Response; + +import org.baeldung.persistence.model.BookReview; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = { SpringCloudRestClientApplication.class }, webEnvironment = WebEnvironment.DEFINED_PORT) +public class RestApiLiveTest { + + private static final String API_URI = "http://localhost:8085/reviews"; + + @Before + public void setUp() { + RestAssured.authentication = preemptive().basic("user", "userPass"); + } + + // GET + + @Test + public void whenGetAllReviews_thenOK() { + final Response response = RestAssured.get(API_URI); + assertEquals(HttpStatus.OK.value(), response.getStatusCode()); + } + + @Test + public void whenGetCreatedReviewById_thenOK() { + final BookReview review = createRandomReview(); + final String location = createReviewAsUri(review); + + final Response response = RestAssured.get(location); + assertEquals(HttpStatus.OK.value(), response.getStatusCode()); + assertEquals(review.getContent(), response.jsonPath() + .get("content")); + } + + @Test + public void whenGetCreatedReviewByName_thenOK() { + final BookReview review = createRandomReview(); + createReviewAsUri(review); + + final Response response = RestAssured.get(API_URI + "/search/findByBookId?bookId=" + review.getBookId()); + assertEquals(HttpStatus.OK.value(), response.getStatusCode()); + assertTrue(response.jsonPath() + .getLong("page.totalElements") > 0); + } + + @Test + public void whenGetNotExistReviewById_thenNotFound() { + final Response response = RestAssured.get(API_URI + "/" + randomNumeric(4)); + assertEquals(HttpStatus.NOT_FOUND.value(), response.getStatusCode()); + } + + @Test + public void whenGetNotExistReviewByName_thenNotFound() { + final Response response = RestAssured.get(API_URI + "/search/findByBookId?bookId=" + randomNumeric(4)); + assertEquals(HttpStatus.OK.value(), response.getStatusCode()); + assertTrue(response.jsonPath() + .getLong("page.totalElements") == 0); + } + + // POST + @Test + public void whenCreateNewReview_thenCreated() { + final BookReview review = createRandomReview(); + + final Response response = RestAssured.given() + .contentType(MediaType.APPLICATION_JSON_VALUE) + .body(review) + .post(API_URI); + assertEquals(HttpStatus.CREATED.value(), response.getStatusCode()); + } + + @Test + public void whenInvalidReview_thenError() { + final BookReview review = createRandomReview(); + review.setBookId(null); + + final Response response = RestAssured.given() + .contentType(MediaType.APPLICATION_JSON_VALUE) + .body(review) + .post(API_URI); + assertEquals(HttpStatus.CONFLICT.value(), response.getStatusCode()); + } + + @Test + public void whenUpdateCreatedReview_thenUpdated() { + // create + final BookReview review = createRandomReview(); + final String location = createReviewAsUri(review); + + // update + review.setRating(4); + Response response = RestAssured.given() + .contentType(MediaType.APPLICATION_JSON_VALUE) + .body(review) + .put(location); + assertEquals(HttpStatus.OK.value(), response.getStatusCode()); + + // check if changes saved + response = RestAssured.get(location); + assertEquals(HttpStatus.OK.value(), response.getStatusCode()); + assertEquals(4, response.jsonPath() + .getInt("rating")); + + } + + @Test + public void whenDeleteCreatedReview_thenOk() { + // create + final BookReview review = createRandomReview(); + final String location = createReviewAsUri(review); + + // delete + Response response = RestAssured.delete(location); + assertEquals(HttpStatus.NO_CONTENT.value(), response.getStatusCode()); + + // confirm it was deleted + response = RestAssured.get(location); + assertEquals(HttpStatus.NOT_FOUND.value(), response.getStatusCode()); + } + + @Test + public void whenDeleteNotExistReview_thenError() { + final Response response = RestAssured.delete(API_URI + "/" + randomNumeric(4)); + assertEquals(HttpStatus.NOT_FOUND.value(), response.getStatusCode()); + } + + // =============================== Util + + private BookReview createRandomReview() { + final BookReview review = new BookReview(); + review.setContent(randomAlphabetic(10)); + review.setRating(3); + review.setBookId(1L); + return review; + } + + private String createReviewAsUri(BookReview review) { + final Response response = RestAssured.given() + .contentType(MediaType.APPLICATION_JSON_VALUE) + .body(review) + .post(API_URI); + return response.jsonPath() + .get("_links.self.href"); + } + +} diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-client-2/src/test/java/org/baeldung/SpringCloudRestClientApplicationTests.java b/spring-cloud/spring-cloud-rest/spring-cloud-rest-client-2/src/test/java/org/baeldung/SpringCloudRestClientApplicationTests.java new file mode 100644 index 0000000000..c16adfbb34 --- /dev/null +++ b/spring-cloud/spring-cloud-rest/spring-cloud-rest-client-2/src/test/java/org/baeldung/SpringCloudRestClientApplicationTests.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class SpringCloudRestClientApplicationTests { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-client-2/src/test/resources/application.properties b/spring-cloud/spring-cloud-rest/spring-cloud-rest-client-2/src/test/resources/application.properties new file mode 100644 index 0000000000..e69cb2f555 --- /dev/null +++ b/spring-cloud/spring-cloud-rest/spring-cloud-rest-client-2/src/test/resources/application.properties @@ -0,0 +1,19 @@ +#### cloud +spring.application.name=spring-cloud-eureka-client +server.port=8085 +eureka.client.serviceUrl.defaultZone=${EUREKA_URI:http://system:systemPass@localhost:8761/eureka} +eureka.instance.preferIpAddress=true + +#### persistence +spring.datasource.driver-class-name=org.h2.Driver +spring.datasource.url=jdbc:h2:mem:cloud_rest;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE +spring.datasource.username=sa +spring.datasource.password= + +#### security +security.basic.enabled=true +security.basic.path=/** +security.user.name=user +security.user.password=userPass +security.user.role=USER +security.sessions=always \ No newline at end of file diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-client/src/main/java/org/baeldung/persistence/dao/BookRepository.java b/spring-cloud/spring-cloud-rest/spring-cloud-rest-client/src/main/java/org/baeldung/persistence/dao/BookRepository.java deleted file mode 100644 index 419c735d63..0000000000 --- a/spring-cloud/spring-cloud-rest/spring-cloud-rest-client/src/main/java/org/baeldung/persistence/dao/BookRepository.java +++ /dev/null @@ -1,10 +0,0 @@ -package org.baeldung.persistence.dao; - -import org.baeldung.persistence.model.Book; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.rest.core.annotation.RepositoryRestResource; - -@RepositoryRestResource(collectionResourceRel = "books", path = "books") -public interface BookRepository extends JpaRepository { - -} diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-client/src/main/resources/application.properties b/spring-cloud/spring-cloud-rest/spring-cloud-rest-client/src/main/resources/application.properties deleted file mode 100644 index 45100d4788..0000000000 --- a/spring-cloud/spring-cloud-rest/spring-cloud-rest-client/src/main/resources/application.properties +++ /dev/null @@ -1,9 +0,0 @@ -spring.application.name=spring-cloud-eureka-client -server.port=0 -eureka.client.serviceUrl.defaultZone=${EUREKA_URI:http://localhost:8761/eureka} -eureka.instance.preferIpAddress=true - -spring.datasource.driver-class-name=org.h2.Driver -spring.datasource.url=jdbc:h2:mem:cloud_rest;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE -spring.datasource.username=sa -spring.datasource.password= \ No newline at end of file diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-config/.gitignore b/spring-cloud/spring-cloud-rest/spring-cloud-rest-config/.gitignore new file mode 100644 index 0000000000..2af7cefb0a --- /dev/null +++ b/spring-cloud/spring-cloud-rest/spring-cloud-rest-config/.gitignore @@ -0,0 +1,24 @@ +target/ +!.mvn/wrapper/maven-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +nbproject/private/ +build/ +nbbuild/ +dist/ +nbdist/ +.nb-gradle/ \ No newline at end of file diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-client/pom.xml b/spring-cloud/spring-cloud-rest/spring-cloud-rest-config/pom.xml similarity index 63% rename from spring-cloud/spring-cloud-rest/spring-cloud-rest-client/pom.xml rename to spring-cloud/spring-cloud-rest/spring-cloud-rest-config/pom.xml index 824e17e59c..a6f045899c 100644 --- a/spring-cloud/spring-cloud-rest/spring-cloud-rest-client/pom.xml +++ b/spring-cloud/spring-cloud-rest/spring-cloud-rest-config/pom.xml @@ -4,48 +4,41 @@ 4.0.0 org.baeldung - spring-cloud-rest-client + spring-cloud-rest-config 0.0.1-SNAPSHOT jar - spring-cloud-rest - Demo project for Spring Boot + spring-cloud-rest-config + Spring Cloud REST configuration server org.springframework.boot spring-boot-starter-parent 1.4.3.RELEASE - + UTF-8 UTF-8 1.8 + Camden.SR4 org.springframework.cloud - spring-cloud-starter-eureka + spring-cloud-config-server - org.springframework.boot - spring-boot-starter-data-jpa - - - com.h2database - h2 - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-data-rest + org.springframework.cloud + spring-cloud-starter-eureka - + + org.springframework.boot + spring-boot-starter-security + + org.springframework.boot spring-boot-starter-test @@ -58,7 +51,7 @@ org.springframework.cloud spring-cloud-dependencies - Camden.SR4 + ${spring-cloud.version} pom import @@ -71,6 +64,16 @@ org.springframework.boot spring-boot-maven-plugin + + org.apache.maven.plugins + maven-surefire-plugin + + + **/*IntegrationTest.java + **/*LiveTest.java + + + diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-config/src/main/java/org/baeldung/SpringCloudRestConfigApplication.java b/spring-cloud/spring-cloud-rest/spring-cloud-rest-config/src/main/java/org/baeldung/SpringCloudRestConfigApplication.java new file mode 100644 index 0000000000..90c6fe3ec9 --- /dev/null +++ b/spring-cloud/spring-cloud-rest/spring-cloud-rest-config/src/main/java/org/baeldung/SpringCloudRestConfigApplication.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.config.server.EnableConfigServer; +import org.springframework.cloud.netflix.eureka.EnableEurekaClient; + +@SpringBootApplication +@EnableConfigServer +@EnableEurekaClient +public class SpringCloudRestConfigApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringCloudRestConfigApplication.class, args); + } + +} diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-config/src/main/resources/application.properties b/spring-cloud/spring-cloud-rest/spring-cloud-rest-config/src/main/resources/application.properties new file mode 100644 index 0000000000..4071dc81ea --- /dev/null +++ b/spring-cloud/spring-cloud-rest/spring-cloud-rest-config/src/main/resources/application.properties @@ -0,0 +1,11 @@ +server.port=8081 +spring.application.name=config + +spring.cloud.config.server.git.uri=${HOME}/application-config + +eureka.client.region = default +eureka.client.registryFetchIntervalSeconds = 5 +eureka.client.serviceUrl.defaultZone=${EUREKA_URI:http://system:systemPass@localhost:8761/eureka} + +security.user.name=configUser +security.user.password=configPassword \ No newline at end of file diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-config/src/test/java/org/baeldung/SpringCloudRestConfigApplicationTests.java b/spring-cloud/spring-cloud-rest/spring-cloud-rest-config/src/test/java/org/baeldung/SpringCloudRestConfigApplicationTests.java new file mode 100644 index 0000000000..072a3e6ffc --- /dev/null +++ b/spring-cloud/spring-cloud-rest/spring-cloud-rest-config/src/test/java/org/baeldung/SpringCloudRestConfigApplicationTests.java @@ -0,0 +1,15 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class SpringCloudRestConfigApplicationTests { + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-server/.mvn/wrapper/maven-wrapper.properties b/spring-cloud/spring-cloud-rest/spring-cloud-rest-server/.mvn/wrapper/maven-wrapper.properties deleted file mode 100644 index c954cec91c..0000000000 --- a/spring-cloud/spring-cloud-rest/spring-cloud-rest-server/.mvn/wrapper/maven-wrapper.properties +++ /dev/null @@ -1 +0,0 @@ -distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.3.9/apache-maven-3.3.9-bin.zip diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-server/pom.xml b/spring-cloud/spring-cloud-rest/spring-cloud-rest-server/pom.xml index e513b2d0c4..98325e8ae9 100644 --- a/spring-cloud/spring-cloud-rest/spring-cloud-rest-server/pom.xml +++ b/spring-cloud/spring-cloud-rest/spring-cloud-rest-server/pom.xml @@ -26,11 +26,27 @@ + + org.springframework.cloud + spring-cloud-starter-config + org.springframework.cloud spring-cloud-starter-eureka-server - + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.session + spring-session + + + org.springframework.boot + spring-boot-starter-data-redis + + org.springframework.boot spring-boot-starter-test @@ -56,6 +72,16 @@ org.springframework.boot spring-boot-maven-plugin + + org.apache.maven.plugins + maven-surefire-plugin + + + **/*IntegrationTest.java + **/*LiveTest.java + + + diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-server/src/main/java/org/baeldung/SessionConfig.java b/spring-cloud/spring-cloud-rest/spring-cloud-rest-server/src/main/java/org/baeldung/SessionConfig.java new file mode 100644 index 0000000000..bd1c0013ca --- /dev/null +++ b/spring-cloud/spring-cloud-rest/spring-cloud-rest-server/src/main/java/org/baeldung/SessionConfig.java @@ -0,0 +1,8 @@ +package org.baeldung; + +import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession; +import org.springframework.session.web.context.AbstractHttpSessionApplicationInitializer; + +@EnableRedisHttpSession +public class SessionConfig extends AbstractHttpSessionApplicationInitializer { +} diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-server/src/main/resources/application.properties b/spring-cloud/spring-cloud-rest/spring-cloud-rest-server/src/main/resources/application.properties deleted file mode 100644 index 2c7dfa193e..0000000000 --- a/spring-cloud/spring-cloud-rest/spring-cloud-rest-server/src/main/resources/application.properties +++ /dev/null @@ -1,3 +0,0 @@ -server.port=8761 -eureka.client.registerWithEureka=false -eureka.client.fetchRegistry=false \ No newline at end of file diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-server/src/main/resources/bootstrap.properties b/spring-cloud/spring-cloud-rest/spring-cloud-rest-server/src/main/resources/bootstrap.properties new file mode 100644 index 0000000000..528cb4cfd3 --- /dev/null +++ b/spring-cloud/spring-cloud-rest/spring-cloud-rest-server/src/main/resources/bootstrap.properties @@ -0,0 +1,4 @@ +spring.cloud.config.name=spring-cloud-rest-server +spring.cloud.config.uri=http://localhost:8081 +spring.cloud.config.username=configUser +spring.cloud.config.password=configPassword \ No newline at end of file diff --git a/spring-mvc-forms/pom.xml b/spring-mvc-forms/pom.xml index c0cac4d349..31a0c38791 100644 --- a/spring-mvc-forms/pom.xml +++ b/spring-mvc-forms/pom.xml @@ -41,7 +41,11 @@ ${hibernate-validator.version} - + + commons-fileupload + commons-fileupload + ${fileupload.version} + @@ -93,6 +97,7 @@ 1.8 5.3.3.Final enter-location-of-server + 1.3.2 diff --git a/spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/configuration/ApplicationConfiguration.java b/spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/configuration/ApplicationConfiguration.java index 998f070c02..3f7889422f 100644 --- a/spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/configuration/ApplicationConfiguration.java +++ b/spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/configuration/ApplicationConfiguration.java @@ -3,6 +3,8 @@ package com.baeldung.springmvcforms.configuration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; +import org.springframework.web.multipart.MultipartResolver; +import org.springframework.web.multipart.commons.CommonsMultipartResolver; import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @@ -26,4 +28,10 @@ class ApplicationConfiguration extends WebMvcConfigurerAdapter { return bean; } + @Bean + public MultipartResolver multipartResolver() { + CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(); + multipartResolver.setMaxUploadSize(5242880); + return multipartResolver; + } } diff --git a/spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/controller/FileUploadController.java b/spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/controller/FileUploadController.java new file mode 100644 index 0000000000..07f235d317 --- /dev/null +++ b/spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/controller/FileUploadController.java @@ -0,0 +1,52 @@ +package com.baeldung.springmvcforms.controller; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.multipart.MaxUploadSizeExceededException; +import org.springframework.web.multipart.MultipartFile; +import org.springframework.web.servlet.HandlerExceptionResolver; +import org.springframework.web.servlet.ModelAndView; + +@Controller +public class FileUploadController implements HandlerExceptionResolver { + + @RequestMapping(value = "/uploadFile", method = RequestMethod.GET) + public String getImageView() { + return "file"; + } + + @RequestMapping(value = "/uploadFile", method = RequestMethod.POST) + public ModelAndView uploadFile(MultipartFile file) throws IOException{ + ModelAndView modelAndView = new ModelAndView("file"); + + InputStream in = file.getInputStream(); + File currDir = new File("."); + String path = currDir.getAbsolutePath(); + FileOutputStream f = new FileOutputStream(path.substring(0, path.length()-1)+ file.getOriginalFilename()); + int ch = 0; + while ((ch = in.read()) != -1) { + f.write(ch); + } + f.flush(); + f.close(); + + modelAndView.getModel().put("message", "File uploaded successfully!"); + return modelAndView; + } + + @Override + public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object object, Exception exc) { + ModelAndView modelAndView = new ModelAndView("file"); + if (exc instanceof MaxUploadSizeExceededException) { + modelAndView.getModel().put("message", "File size exceeds limit!"); + } + return modelAndView; + } +} diff --git a/spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/interceptor/FileUploadExceptionAdvice.java b/spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/interceptor/FileUploadExceptionAdvice.java new file mode 100644 index 0000000000..3f1c09eeef --- /dev/null +++ b/spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/interceptor/FileUploadExceptionAdvice.java @@ -0,0 +1,19 @@ +package com.baeldung.springmvcforms.interceptor; + +import org.springframework.web.servlet.ModelAndView; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import org.springframework.web.multipart.MaxUploadSizeExceededException; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; + +@ControllerAdvice +public class FileUploadExceptionAdvice { + + @ExceptionHandler(MaxUploadSizeExceededException.class) + public ModelAndView handleMaxSizeException(MaxUploadSizeExceededException exc, HttpServletRequest request, HttpServletResponse response){ + ModelAndView modelAndView = new ModelAndView("file"); + modelAndView.getModel().put("message", "File too large!"); + return modelAndView; + } +} \ No newline at end of file diff --git a/spring-mvc-forms/src/main/webapp/WEB-INF/views/file.jsp b/spring-mvc-forms/src/main/webapp/WEB-INF/views/file.jsp new file mode 100644 index 0000000000..0ed8dae5ed --- /dev/null +++ b/spring-mvc-forms/src/main/webapp/WEB-INF/views/file.jsp @@ -0,0 +1,23 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> +<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> + + + + +Upload file + + + +
+ + +
+
+${message } +

+
+ +
+ + \ No newline at end of file diff --git a/spring-mvc-xml/README.md b/spring-mvc-xml/README.md index b699c37d00..7a5e8c75e9 100644 --- a/spring-mvc-xml/README.md +++ b/spring-mvc-xml/README.md @@ -14,3 +14,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Returning Image/Media Data with Spring MVC](http://www.baeldung.com/spring-mvc-image-media-data) - [Geolocation by IP in Java](http://www.baeldung.com/geolocation-by-ip-with-maxmind) - [Guide to JavaServer Pages (JSP)](http://www.baeldung.com/jsp) +- [Exploring SpringMVC’s Form Tag Library](http://www.baeldung.com/spring-mvc-form-tags) diff --git a/spring-reactor/pom.xml b/spring-reactor/pom.xml index 7b6b1318cf..a04955eada 100644 --- a/spring-reactor/pom.xml +++ b/spring-reactor/pom.xml @@ -39,6 +39,17 @@ org.springframework.boot spring-boot-maven-plugin + + + org.apache.maven.plugins + maven-surefire-plugin + + + **/*IntegrationTest.java + **/*LiveTest.java + + + diff --git a/spring-remoting/README.md b/spring-remoting/README.md new file mode 100644 index 0000000000..1aafdaf6f5 --- /dev/null +++ b/spring-remoting/README.md @@ -0,0 +1,13 @@ +## Spring Remoting Tutorials Project + +### Relevant Articles +- [Intro to Spring Remoting with HTTP Invokers](http://www.baeldung.com/spring-remoting-http-invoker) + +### Overview +This Maven project contains the Java source code for various modules used in the Spring Remoting series of articles. + +### Building the Project +You can build the project using Maven inside your IDE or from the command line: +``` +mvn clean install +``` diff --git a/spring-remoting/pom.xml b/spring-remoting/pom.xml index 2e3b7e76f8..a43dd52a3e 100644 --- a/spring-remoting/pom.xml +++ b/spring-remoting/pom.xml @@ -3,65 +3,24 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 1.4.3.RELEASE + com.baeldung spring-remoting 1.0-SNAPSHOT + Parent for all projects related to Spring Remoting. pom - 3.6.0 - 3.0.0 - - 3.1.0 - 1.1.8 - 4.3.5.RELEASE + 1.8 - - - org.springframework - spring-core - ${spring.version} - - - org.springframework - spring-context - ${spring.version} - - - org.springframework - spring-web - ${spring.version} - - - org.springframework - spring-webmvc - ${spring.version} - - - - - ch.qos.logback - logback-core - ${logback.version} - - - ch.qos.logback - logback-classic - ${logback.version} - - - - - javax.servlet - javax.servlet-api - ${servlet.version} - provided - - ${project.groupId} @@ -73,35 +32,6 @@ - - - - - - maven-compiler-plugin - ${maven-compiler-plugin.version} - - true - true - 1.8 - 1.8 - UTF-8 - true - true - - - - - maven-war-plugin - 3.0.0 - - false - - - - - - remoting-http diff --git a/spring-remoting/remoting-http/api/src/main/java/com/baeldung/api/Address.java b/spring-remoting/remoting-http/api/src/main/java/com/baeldung/api/Address.java deleted file mode 100644 index f2382fabd9..0000000000 --- a/spring-remoting/remoting-http/api/src/main/java/com/baeldung/api/Address.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.baeldung.api; - -import java.io.Serializable; - -public class Address implements Serializable{ - - private String address; - private String countryCode; - - public Address(String address, String countryCode) { - this.address = address; - this.countryCode = countryCode; - } - - public String getAddress() { - return address; - } - - public String getCountryCode() { - return countryCode; - } - - @Override public String toString() { - return address + " (" + countryCode + ")"; - } -} diff --git a/spring-remoting/remoting-http/api/src/main/java/com/baeldung/api/Booking.java b/spring-remoting/remoting-http/api/src/main/java/com/baeldung/api/Booking.java index 7bec4e162d..5d2d3683a1 100644 --- a/spring-remoting/remoting-http/api/src/main/java/com/baeldung/api/Booking.java +++ b/spring-remoting/remoting-http/api/src/main/java/com/baeldung/api/Booking.java @@ -1,52 +1,17 @@ package com.baeldung.api; import java.io.Serializable; -import java.time.LocalDateTime; + +import static java.lang.String.format; public class Booking implements Serializable { - - private int costInCent; - private int etaInSeconds; private String bookingCode; - private LocalDateTime pickUptime; - private Address pickUpAddress; - private Address dropOffAddress; - - public Booking(Address pickUpAddress, LocalDateTime pickUptime, Address dropOffAddress, int costInCent, int etaInSeconds, String bookingCode) { - this.costInCent = costInCent; - this.etaInSeconds = etaInSeconds; - this.bookingCode = bookingCode; - this.pickUptime = pickUptime; - this.pickUpAddress = pickUpAddress; - this.dropOffAddress = dropOffAddress; - } - - public int getCostInCent() { - return costInCent; - } - - public int getEtaInSeconds() { - return etaInSeconds; - } - - public String getBookingCode() { - return bookingCode; - } - - public LocalDateTime getPickUptime() { - return pickUptime; - } - - public Address getDropOffAddress() { - return dropOffAddress; - } @Override public String toString() { - return String.format("Booking: pick up @ %tr in %s, drop down in %s after %d minutes, %.2f $.", pickUptime, pickUpAddress, dropOffAddress, etaInSeconds / 60, costInCent / 100.0); + return format("Ride confirmed: code '%s'.", bookingCode); } - public static void main(String[] args) throws InterruptedException { - System.out.println(new Booking(new Address("a", "b"), - LocalDateTime.now(), new Address("c", "d"), 123_00, 600, "abc")); + public Booking(String bookingCode) { + this.bookingCode = bookingCode; } } diff --git a/spring-remoting/remoting-http/api/src/main/java/com/baeldung/api/CabBookingService.java b/spring-remoting/remoting-http/api/src/main/java/com/baeldung/api/CabBookingService.java index 25b27264e8..b554415e07 100644 --- a/spring-remoting/remoting-http/api/src/main/java/com/baeldung/api/CabBookingService.java +++ b/spring-remoting/remoting-http/api/src/main/java/com/baeldung/api/CabBookingService.java @@ -1,5 +1,5 @@ package com.baeldung.api; public interface CabBookingService { - Booking bookPickUp(Address pickUpLocation, Address dropOffLocation, int pax) throws BookingException; + Booking bookRide(String pickUpLocation) throws BookingException; } diff --git a/spring-remoting/remoting-http/client/pom.xml b/spring-remoting/remoting-http/client/pom.xml index 77891c106a..94a536fc18 100644 --- a/spring-remoting/remoting-http/client/pom.xml +++ b/spring-remoting/remoting-http/client/pom.xml @@ -9,22 +9,22 @@ spring-remoting-http 1.0-SNAPSHOT - spring-remoting-http-client - Shows how to invoke a remote service using Spring Remoting. - + Shows how to invoke a remote service using Spring Remoting HTTP. - - org.springframework - spring-web + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-tomcat + + - - ${project.groupId} api - \ No newline at end of file diff --git a/spring-remoting/remoting-http/client/src/main/java/com/baeldug/client/CabBookingClient.java b/spring-remoting/remoting-http/client/src/main/java/com/baeldug/client/CabBookingClient.java deleted file mode 100644 index 9669970403..0000000000 --- a/spring-remoting/remoting-http/client/src/main/java/com/baeldug/client/CabBookingClient.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.baeldug.client; - -import com.baeldung.api.*; - -public class CabBookingClient { - - private CabBookingService cabService; - - public CabBookingClient(CabBookingService cabService) { - this.cabService = cabService; - } - - public void run() throws BookingException { - - Address pickUp = new Address("13 Seagate Blvd, Key Largo, FL 33037", "US"); - Address dropDown = new Address("91831 Overseas Hwy, Tavernier, FL 33070", "US"); - System.out.println( cabService.bookPickUp(pickUp, dropDown, 3) ); - - } - -} diff --git a/spring-remoting/remoting-http/client/src/main/java/com/baeldug/client/Client.java b/spring-remoting/remoting-http/client/src/main/java/com/baeldug/client/Client.java new file mode 100644 index 0000000000..90f6736a43 --- /dev/null +++ b/spring-remoting/remoting-http/client/src/main/java/com/baeldug/client/Client.java @@ -0,0 +1,28 @@ +package com.baeldug.client; + +import com.baeldung.api.BookingException; +import com.baeldung.api.CabBookingService; +import org.springframework.boot.SpringApplication; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.remoting.httpinvoker.HttpInvokerProxyFactoryBean; + +import static java.lang.System.out; + +@Configuration +public class Client { + + @Bean + public HttpInvokerProxyFactoryBean invoker() { + HttpInvokerProxyFactoryBean invoker = new HttpInvokerProxyFactoryBean(); + invoker.setServiceUrl("http://localhost:8080/booking"); + invoker.setServiceInterface(CabBookingService.class); + return invoker; + } + + public static void main(String[] args) throws BookingException { + CabBookingService service = SpringApplication.run(Client.class, args).getBean(CabBookingService.class); + out.println(service.bookRide("13 Seagate Blvd, Key Largo, FL 33037")); + } + +} diff --git a/spring-remoting/remoting-http/client/src/main/java/com/baeldug/client/Main.java b/spring-remoting/remoting-http/client/src/main/java/com/baeldug/client/Main.java deleted file mode 100644 index a5e3ccd912..0000000000 --- a/spring-remoting/remoting-http/client/src/main/java/com/baeldug/client/Main.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.baeldug.client; - -import com.baeldung.api.CabBookingService; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.remoting.httpinvoker.HttpInvokerProxyFactoryBean; - -@Configuration -public class Main { - - @Bean - public HttpInvokerProxyFactoryBean invoker() { - HttpInvokerProxyFactoryBean invoker = new HttpInvokerProxyFactoryBean(); - invoker.setServiceUrl("http://localhost:9090/spring-remoting-http-server/booking"); - invoker.setServiceInterface(CabBookingService.class); - return invoker; - } - - @Bean - public CabBookingClient client(CabBookingService service){ - return new CabBookingClient(service); - } - - public static void main(String[] args) throws Exception { - AnnotationConfigApplicationContext rootContext = - new AnnotationConfigApplicationContext(); - rootContext.scan(Main.class.getPackage().getName()); - rootContext.refresh(); - CabBookingClient bean = rootContext.getBean(CabBookingClient.class); - bean.run(); - } - -} diff --git a/spring-remoting/remoting-http/pom.xml b/spring-remoting/remoting-http/pom.xml index 0d08779bd7..117d4ec295 100644 --- a/spring-remoting/remoting-http/pom.xml +++ b/spring-remoting/remoting-http/pom.xml @@ -9,9 +9,8 @@ 1.0-SNAPSHOT spring-remoting-http - Parent for all modules related to HTTP Spring Remoting + Parent for all modules related to HTTP Spring Remoting. pom - server client diff --git a/spring-remoting/remoting-http/server/pom.xml b/spring-remoting/remoting-http/server/pom.xml index 32a99716a5..517f4451f7 100644 --- a/spring-remoting/remoting-http/server/pom.xml +++ b/spring-remoting/remoting-http/server/pom.xml @@ -8,58 +8,16 @@ spring-remoting-http 1.0-SNAPSHOT - war - spring-remoting-http-server - Shows how to expose a service using Spring Remoting - - - 2.2 - - + Shows how to expose a service using Spring Remoting HTTP. - - - - - org.springframework - spring-webmvc + org.springframework.boot + spring-boot-starter-web - - - - javax.servlet - javax.servlet-api - - - ${project.groupId} api - - - - - - maven-compiler-plugin - - - - maven-war-plugin - - - - org.apache.tomcat.maven - tomcat7-maven-plugin - ${tomcat7-maven-plugin.version} - - 9090 - - - - - \ No newline at end of file diff --git a/spring-remoting/remoting-http/server/src/main/java/com/baeldung/server/CabBookingConfig.java b/spring-remoting/remoting-http/server/src/main/java/com/baeldung/server/CabBookingConfig.java deleted file mode 100644 index 146d2ecadb..0000000000 --- a/spring-remoting/remoting-http/server/src/main/java/com/baeldung/server/CabBookingConfig.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.baeldung.server; - -import org.springframework.context.annotation.Configuration; - -@Configuration -public class CabBookingConfig { - - - -} diff --git a/spring-remoting/remoting-http/server/src/main/java/com/baeldung/server/CabBookingInitializer.java b/spring-remoting/remoting-http/server/src/main/java/com/baeldung/server/CabBookingInitializer.java deleted file mode 100644 index 53b3fd5faf..0000000000 --- a/spring-remoting/remoting-http/server/src/main/java/com/baeldung/server/CabBookingInitializer.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.baeldung.server; - -import org.springframework.web.WebApplicationInitializer; -import org.springframework.web.context.ContextLoaderListener; -import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; -import org.springframework.web.servlet.DispatcherServlet; - -import javax.servlet.ServletContext; -import javax.servlet.ServletRegistration; - -public class CabBookingInitializer implements WebApplicationInitializer { - - @Override - public void onStartup(ServletContext container) { - AnnotationConfigWebApplicationContext rootContext = - new AnnotationConfigWebApplicationContext(); - rootContext.register(CabBookingConfig.class); - - // Manage the lifecycle of the root application context - container.addListener(new ContextLoaderListener(rootContext)); - - // Create the dispatcher servlet's Spring application context - AnnotationConfigWebApplicationContext dispatcherContext = - new AnnotationConfigWebApplicationContext(); - dispatcherContext.register(DispatcherConfig.class); - - // Register and map the dispatcher servlet - ServletRegistration.Dynamic dispatcher = - container.addServlet("dispatcher", new DispatcherServlet(dispatcherContext)); - dispatcher.setLoadOnStartup(1); - dispatcher.addMapping("/*"); - } - -} diff --git a/spring-remoting/remoting-http/server/src/main/java/com/baeldung/server/CabBookingServiceImpl.java b/spring-remoting/remoting-http/server/src/main/java/com/baeldung/server/CabBookingServiceImpl.java index 8f3c099fe0..55ec9c5733 100644 --- a/spring-remoting/remoting-http/server/src/main/java/com/baeldung/server/CabBookingServiceImpl.java +++ b/spring-remoting/remoting-http/server/src/main/java/com/baeldung/server/CabBookingServiceImpl.java @@ -1,27 +1,16 @@ package com.baeldung.server; -import com.baeldung.api.Address; import com.baeldung.api.Booking; import com.baeldung.api.BookingException; import com.baeldung.api.CabBookingService; -import java.time.LocalDateTime; - import static java.lang.Math.random; -import static java.time.LocalDateTime.now; -import static java.time.temporal.ChronoUnit.MINUTES; import static java.util.UUID.randomUUID; public class CabBookingServiceImpl implements CabBookingService { - @Override public Booking bookPickUp(Address pickUpLocation, Address dropOffLocation, int pax) throws BookingException { - if (random() < 0.3) { - throw new BookingException("Cab unavailable"); - } - int tripTimeInMinutes = (int) (5 + random() * 15); - int costInCent = 15_00 + tripTimeInMinutes * 5 * pax; - LocalDateTime pickUpDate = now().plus(15L * (long) (random() * 10), MINUTES); - - return new Booking(pickUpLocation, pickUpDate, dropOffLocation, costInCent, tripTimeInMinutes * 60, randomUUID().toString()); + @Override public Booking bookRide(String pickUpLocation) throws BookingException { + if (random() < 0.3) throw new BookingException("Cab unavailable"); + return new Booking(randomUUID().toString()); } } diff --git a/spring-remoting/remoting-http/server/src/main/java/com/baeldung/server/DispatcherConfig.java b/spring-remoting/remoting-http/server/src/main/java/com/baeldung/server/Server.java similarity index 62% rename from spring-remoting/remoting-http/server/src/main/java/com/baeldung/server/DispatcherConfig.java rename to spring-remoting/remoting-http/server/src/main/java/com/baeldung/server/Server.java index 8f9391f8ac..c6b198507f 100644 --- a/spring-remoting/remoting-http/server/src/main/java/com/baeldung/server/DispatcherConfig.java +++ b/spring-remoting/remoting-http/server/src/main/java/com/baeldung/server/Server.java @@ -1,12 +1,17 @@ package com.baeldung.server; import com.baeldung.api.CabBookingService; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter; @Configuration -public class DispatcherConfig { +@ComponentScan +@EnableAutoConfiguration +public class Server { @Bean(name = "/booking") HttpInvokerServiceExporter accountService() { HttpInvokerServiceExporter exporter = new HttpInvokerServiceExporter(); @@ -15,4 +20,8 @@ public class DispatcherConfig { return exporter; } -} + public static void main(String[] args) { + SpringApplication.run(Server.class, args); + } + +} \ No newline at end of file diff --git a/spring-remoting/remoting-http/server/src/main/resources/logback.xml b/spring-remoting/remoting-http/server/src/main/resources/logback.xml deleted file mode 100644 index 566c44b448..0000000000 --- a/spring-remoting/remoting-http/server/src/main/resources/logback.xml +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - ${logPattern} - - - - - - - \ No newline at end of file diff --git a/spring-thymeleaf/README.md b/spring-thymeleaf/README.md index 67bdddaf64..3f8f0ab244 100644 --- a/spring-thymeleaf/README.md +++ b/spring-thymeleaf/README.md @@ -9,6 +9,7 @@ - [Spring and Thymeleaf 3: Expressions](http://www.baeldung.com/spring-thymeleaf-3-expressions) - [Spring MVC + Thymeleaf 3.0: New Features](http://www.baeldung.com/spring-thymeleaf-3) - [How to Work with Dates in Thymeleaef](http://www.baeldung.com/dates-in-thymeleaf) +- [How to Create an Executable JAR with Maven](http://www.baeldung.com/executable-jar-with-maven) ### Build the Project diff --git a/struts2/WebContent/WEB-INF/web.xml b/struts2/WebContent/WEB-INF/web.xml new file mode 100644 index 0000000000..3aa1d1d173 --- /dev/null +++ b/struts2/WebContent/WEB-INF/web.xml @@ -0,0 +1,16 @@ + + + MyStrutsApp + + struts2 + org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter + + + + struts2 + /* + + \ No newline at end of file diff --git a/struts2/WebContent/input.jsp b/struts2/WebContent/input.jsp new file mode 100644 index 0000000000..6d80aa3ffd --- /dev/null +++ b/struts2/WebContent/input.jsp @@ -0,0 +1,21 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> + + + + +Baledung Struts + + +
+

Welcome to Baeldung Struts 2 app

+

Which car do you like !!

+

Please choose ferrari or bmw

+ + +
+ + \ No newline at end of file diff --git a/struts2/WebContent/result.jsp b/struts2/WebContent/result.jsp new file mode 100644 index 0000000000..0fe9ea2d1d --- /dev/null +++ b/struts2/WebContent/result.jsp @@ -0,0 +1,11 @@ +<%@ page contentType="text/html; charset=UTF-8" %> +<%@ taglib prefix="s" uri="/struts-tags" %> + + +Hello World + + +

Hello Baeldung User

+

You are a

+ + diff --git a/struts2/pom.xml b/struts2/pom.xml new file mode 100644 index 0000000000..b6ddce6c5b --- /dev/null +++ b/struts2/pom.xml @@ -0,0 +1,44 @@ + + 4.0.0 + com.baeldung + MyStrutsApp + 0.0.1-SNAPSHOT + war + MyStrutsApp + + src + + + src + + **/*.java + + + + + + maven-compiler-plugin + 3.5.1 + + 1.8 + 1.8 + + + + maven-war-plugin + 3.0.0 + + WebContent + + + + + + + + org.apache.struts + struts2-core + 2.5.5 + + + \ No newline at end of file diff --git a/struts2/src/com/baeldung/struts/CarAction.java b/struts2/src/com/baeldung/struts/CarAction.java new file mode 100644 index 0000000000..a96aa440b6 --- /dev/null +++ b/struts2/src/com/baeldung/struts/CarAction.java @@ -0,0 +1,31 @@ +package com.baeldung.struts; + +public class CarAction { + + private String carName; + private String carMessage; + private CarMessageService carMessageService = new CarMessageService(); + + public String execute() { + System.out.println("inside execute(): carName is" + carName); + this.setCarMessage(this.carMessageService.getMessage(carName)); + return "success"; + } + + public String getCarName() { + return carName; + } + + public void setCarName(String carName) { + this.carName = carName; + } + + public String getCarMessage() { + return carMessage; + } + + public void setCarMessage(String carMessage) { + this.carMessage = carMessage; + } + +} diff --git a/struts2/src/com/baeldung/struts/CarMessageService.java b/struts2/src/com/baeldung/struts/CarMessageService.java new file mode 100644 index 0000000000..fef9c1719d --- /dev/null +++ b/struts2/src/com/baeldung/struts/CarMessageService.java @@ -0,0 +1,15 @@ +package com.baeldung.struts; + +public class CarMessageService { + + public String getMessage(String carName) { + System.out.println("inside getMessage()" + carName); + if (carName.equalsIgnoreCase("ferrari")) + return "Ferrari Fan!"; + else if (carName.equalsIgnoreCase("bmw")) + return "BMW Fan!"; + else + return "please choose ferrari Or bmw"; + } + +} diff --git a/struts2/src/struts.xml b/struts2/src/struts.xml new file mode 100644 index 0000000000..1c117ac900 --- /dev/null +++ b/struts2/src/struts.xml @@ -0,0 +1,12 @@ + + + + + + /result.jsp + + + \ No newline at end of file diff --git a/video-tutorials/jackson-annotations/pom.xml b/video-tutorials/jackson-annotations/pom.xml new file mode 100644 index 0000000000..e321544d4e --- /dev/null +++ b/video-tutorials/jackson-annotations/pom.xml @@ -0,0 +1,244 @@ + + 4.0.0 + com.baeldung + jackson-annotations + 1.0.0-SNAPSHOT + + jacksonannotation + + + com.baeldung + video-tutorials + 1.0.0-SNAPSHOT + + + + + + + com.google.guava + guava + ${guava.version} + + + + commons-io + commons-io + ${commons-io.version} + + + + + com.fasterxml.jackson.dataformat + jackson-dataformat-xml + ${jackson.version} + + + + org.apache.commons + commons-collections4 + ${commons-collections4.version} + + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + + + + + + com.fasterxml.jackson.core + jackson-databind + ${jackson.version} + + + + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 + ${jackson.version} + + + + com.fasterxml.jackson.datatype + jackson-datatype-joda + ${jackson.version} + + + + com.fasterxml.jackson.module + jackson-module-jsonSchema + ${jackson.version} + + + + joda-time + joda-time + ${joda-time.version} + + + + com.google.code.gson + gson + ${gson.version} + + + + + io.rest-assured + rest-assured + 3.0.1 + test + + + + + io.rest-assured + json-schema-validator + 3.0.0 + test + + + + io.rest-assured + json-path + ${json-path.version} + test + + + + com.github.fge + json-schema-validator + ${json-schema-validator.version} + test + + + + junit + junit + ${junit.version} + test + + + + org.assertj + assertj-core + ${assertj-core.version} + test + + + + + ch.qos.logback + logback-classic + ${logback.version} + + + + + org.slf4j + slf4j-api + ${org.slf4j.version} + + + + org.slf4j + jcl-over-slf4j + ${org.slf4j.version} + + + + org.slf4j + log4j-over-slf4j + ${org.slf4j.version} + + + + + + jackson-annotations + + + src/main/resources + true + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${maven-compiler-plugin.source} + ${maven-compiler-plugin.source} + + + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + + + + + + + + 4.3.11.Final + 5.1.38 + + + 2.8.5 + + + 1.7.21 + 1.1.7 + + + 5.1.3.Final + 2.9.6 + 2.8.0 + 4.1 + + + 20.0 + 3.5 + 2.5 + + + 1.3 + 4.12 + 2.2.26 + + 4.4.1 + 4.5 + + 2.9.0 + + 3.6.1 + 2.2.6 + 3.0.1 + + + 3.5.1 + 2.6 + 2.19.1 + 2.7 + 1.4.18 + + UTF-8 + 1.8 + + + + + + diff --git a/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/deserialization/jacksoninject/Author.java b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/deserialization/jacksoninject/Author.java new file mode 100644 index 0000000000..42d014de8a --- /dev/null +++ b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/deserialization/jacksoninject/Author.java @@ -0,0 +1,32 @@ +package com.baeldung.jacksonannotation.deserialization.jacksoninject; + +import com.baeldung.jacksonannotation.domain.Item; + +import java.util.ArrayList; +import java.util.List; + +/** + * Source code github.com/eugenp/tutorials + * + * @author Alex Theedom www.baeldung.com + * @version 1.0 + */ +public class Author extends Person { + + List items = new ArrayList<>(); + + public Author(){ + super(); + } + public Author(String firstName, String lastName) { + super(firstName, lastName); + } + + public List getItems() { + return items; + } + + public void setItems(List items) { + this.items = items; + } +} diff --git a/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/deserialization/jacksoninject/Person.java b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/deserialization/jacksoninject/Person.java new file mode 100644 index 0000000000..e185893c00 --- /dev/null +++ b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/deserialization/jacksoninject/Person.java @@ -0,0 +1,49 @@ +package com.baeldung.jacksonannotation.deserialization.jacksoninject; + +import com.fasterxml.jackson.annotation.JacksonInject; + +import java.util.UUID; + +/** + * Source code github.com/eugenp/tutorials + * + * @author Alex Theedom www.baeldung.com + * @version 1.0 + */ +public class Person { + + @JacksonInject + private UUID id; + private String firstName; + private String lastName; + + public Person(){ + + } + + public Person(String firstName, String lastName) { + this.id = UUID.randomUUID(); + this.firstName = firstName; + this.lastName = lastName; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public UUID getId() { + return id; + } +} diff --git a/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/deserialization/jsonanysetter/Inventory.java b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/deserialization/jsonanysetter/Inventory.java new file mode 100644 index 0000000000..0016f749ea --- /dev/null +++ b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/deserialization/jsonanysetter/Inventory.java @@ -0,0 +1,38 @@ +package com.baeldung.jacksonannotation.deserialization.jsonanysetter; + +import com.baeldung.jacksonannotation.domain.Author; +import com.baeldung.jacksonannotation.domain.Item; +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import java.util.HashMap; +import java.util.Map; + +/** + * Source code github.com/eugenp/tutorials + * + * @author Alex Theedom www.baeldung.com + * @version 1.0 + * @see JsonAnyGetter + */ +public class Inventory { + + private Map stock = new HashMap<>(); + + private Map countryDeliveryCost = new HashMap<>(); + + @JsonIgnore + public Map getStock() { + return stock; + } + + public Map getCountryDeliveryCost() { + return countryDeliveryCost; + } + + @JsonAnySetter + public void addCountryDeliveryCost(String country, Float cost) { + countryDeliveryCost.put(country, cost); + } +} diff --git a/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/deserialization/jsoncreator/Author.java b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/deserialization/jsoncreator/Author.java new file mode 100644 index 0000000000..91afd16eb0 --- /dev/null +++ b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/deserialization/jsoncreator/Author.java @@ -0,0 +1,38 @@ +package com.baeldung.jacksonannotation.deserialization.jsoncreator; + + +import com.baeldung.jacksonannotation.domain.Item; +import com.baeldung.jacksonannotation.domain.Person; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonGetter; +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.util.ArrayList; +import java.util.List; + +/** + * Source code github.com/eugenp/tutorials + * + * @author Alex Theedom www.baeldung.com + * @version 1.0 + * @see JsonGetter + */ +public class Author extends Person { + + List items = new ArrayList<>(); + + @JsonCreator + public Author( + @JsonProperty("christianName") String firstName, + @JsonProperty("surname") String lastName) { + super(firstName, lastName); + } + + public List getItems() { + return items; + } + + public void setItems(List items) { + this.items = items; + } +} diff --git a/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/deserialization/jsondeserialize/Author.java b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/deserialization/jsondeserialize/Author.java new file mode 100644 index 0000000000..6999e53411 --- /dev/null +++ b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/deserialization/jsondeserialize/Author.java @@ -0,0 +1,30 @@ +package com.baeldung.jacksonannotation.deserialization.jsondeserialize; + +import com.baeldung.jacksonannotation.domain.Item; +import com.baeldung.jacksonannotation.domain.Person; + +import java.util.ArrayList; +import java.util.List; + +/** + * Source code github.com/eugenp/tutorials + * + * @author Alex Theedom www.baeldung.com + * @version 1.0 + */ +public class Author extends Person { + + List items = new ArrayList<>(); + + public Author(String firstName, String lastName) { + super(firstName, lastName); + } + + public List getItems() { + return items; + } + + public void setItems(List items) { + this.items = items; + } +} diff --git a/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/deserialization/jsondeserialize/Book.java b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/deserialization/jsondeserialize/Book.java new file mode 100644 index 0000000000..1ab53e7f9f --- /dev/null +++ b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/deserialization/jsondeserialize/Book.java @@ -0,0 +1,53 @@ +package com.baeldung.jacksonannotation.deserialization.jsondeserialize; + +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; + +import java.math.BigDecimal; +import java.util.Date; + +/** + * Source code github.com/eugenp/tutorials + * + * @author Alex Theedom www.baeldung.com + * @version 1.0 + */ +public class Book extends Item { + + private String ISBN; + + @JsonDeserialize(using = CustomDateDeserializer.class) + private Date published; + private BigDecimal pages; + + public Book() { + super(); + } + + public Book(String title, Author author) { + super(title, author); + } + + public String getISBN() { + return ISBN; + } + + public void setISBN(String ISBN) { + this.ISBN = ISBN; + } + + public Date getPublished() { + return published; + } + + public void setPublished(Date published) { + this.published = published; + } + + public BigDecimal getPages() { + return pages; + } + + public void setPages(BigDecimal pages) { + this.pages = pages; + } +} diff --git a/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/deserialization/jsondeserialize/CustomDateDeserializer.java b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/deserialization/jsondeserialize/CustomDateDeserializer.java new file mode 100644 index 0000000000..3d048ed347 --- /dev/null +++ b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/deserialization/jsondeserialize/CustomDateDeserializer.java @@ -0,0 +1,42 @@ +package com.baeldung.jacksonannotation.deserialization.jsondeserialize; + +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.deser.std.StdDeserializer; + +import java.io.IOException; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; + +/** + * Source code github.com/eugenp/tutorials + * + * @author Alex Theedom www.baeldung.com + * @version 1.0 + */ +public class CustomDateDeserializer extends StdDeserializer { + + private static SimpleDateFormat formatter = + new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); + + public CustomDateDeserializer() { + this(null); + } + + public CustomDateDeserializer(Class vc) { + super(vc); + } + + @Override + public Date deserialize(JsonParser jsonparser, DeserializationContext context) + throws IOException, JsonProcessingException { + String date = jsonparser.getText(); + try { + return formatter.parse(date); + } catch (ParseException e) { + throw new RuntimeException(e); + } + } +} diff --git a/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/deserialization/jsondeserialize/Item.java b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/deserialization/jsondeserialize/Item.java new file mode 100644 index 0000000000..9b6652c8dd --- /dev/null +++ b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/deserialization/jsondeserialize/Item.java @@ -0,0 +1,61 @@ +package com.baeldung.jacksonannotation.deserialization.jsondeserialize; + +import com.baeldung.jacksonannotation.domain.Person; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +/** + * Source code github.com/eugenp/tutorials + * + * @author Alex Theedom www.baeldung.com + * @version 1.0 + */ +public class Item { + + private UUID id; + private String title; + private List authors = new ArrayList<>(); + private float price; + + public Item(){} + + public Item(String title, Author author) { + this.id = UUID.randomUUID(); + this.title = title; + this.authors.add(author); + } + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public List getAuthors() { + return authors; + } + + public void setAuthors(List authors) { + this.authors = authors; + } + + public float getPrice() { + return price; + } + + public void setPrice(float price) { + this.price = price; + } +} diff --git a/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/deserialization/jsonsetter/Author.java b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/deserialization/jsonsetter/Author.java new file mode 100644 index 0000000000..1adf31bb3b --- /dev/null +++ b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/deserialization/jsonsetter/Author.java @@ -0,0 +1,38 @@ +package com.baeldung.jacksonannotation.deserialization.jsonsetter; + +import com.baeldung.jacksonannotation.domain.Item; +import com.baeldung.jacksonannotation.domain.Person; +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonSetter; + +import java.util.ArrayList; +import java.util.List; + +/** + * Source code github.com/eugenp/tutorials + * + * @author Alex Theedom www.baeldung.com + * @version 1.0 + */ +public class Author extends Person { + + private List items = new ArrayList<>(); + + public Author(){ + super(); + } + + public Author(String firstName, String lastName) { + super(firstName, lastName); + } + + @JsonIgnore + public List getItems() { + return items; + } + + @JsonSetter("publications") + public void setItems(List items) { + this.items = items; + } +} diff --git a/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/domain/Author.java b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/domain/Author.java new file mode 100644 index 0000000000..7bf0031a18 --- /dev/null +++ b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/domain/Author.java @@ -0,0 +1,27 @@ +package com.baeldung.jacksonannotation.domain; + +import java.util.ArrayList; +import java.util.List; + +/** + * Source code github.com/eugenp/tutorials + * + * @author Alex Theedom www.baeldung.com + * @version 1.0 + */ +public class Author extends Person { + + private List items = new ArrayList<>(); + + public Author(String firstName, String lastName) { + super(firstName, lastName); + } + + public List getItems() { + return items; + } + + public void setItems(List items) { + this.items = items; + } +} diff --git a/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/domain/Book.java b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/domain/Book.java new file mode 100644 index 0000000000..e242406446 --- /dev/null +++ b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/domain/Book.java @@ -0,0 +1,48 @@ +package com.baeldung.jacksonannotation.domain; + +import java.math.BigDecimal; +import java.util.Date; + +/** + * Source code github.com/eugenp/tutorials + * + * @author Alex Theedom www.baeldung.com + * @version 1.0 + */ +public class Book extends Item { + + private String ISBN; + private Date published; + private BigDecimal pages; + + public Book(){ + } + + public Book(String title, Author author) { + super(title, author); + } + + public String getISBN() { + return ISBN; + } + + public void setISBN(String ISBN) { + this.ISBN = ISBN; + } + + public Date getPublished() { + return published; + } + + public void setPublished(Date published) { + this.published = published; + } + + public BigDecimal getPages() { + return pages; + } + + public void setPages(BigDecimal pages) { + this.pages = pages; + } +} diff --git a/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/domain/Course.java b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/domain/Course.java new file mode 100644 index 0000000000..f0c37cc0bd --- /dev/null +++ b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/domain/Course.java @@ -0,0 +1,71 @@ +package com.baeldung.jacksonannotation.domain; + +import java.util.List; + +/** + * Source code github.com/eugenp/tutorials + * + * @author Alex Theedom www.baeldung.com + * @version 1.0 + */ +public class Course extends Item { + + public enum Medium {CLASSROOM, ONLINE} + + public enum Level { + BEGINNER("Beginner", 1), INTERMEDIATE("Intermediate", 2), ADVANCED("Advanced", 3); + + private String name; + private int number; + + Level(String name, int number) { + this.name = name; + this.number = number; + } + + public String getName() { + return name; + } + } + + private float duration; + private Medium medium; + private Level level; + private List prerequisite; + + public Course(String title, Author author) { + super(title, author); + } + + public float getDuration() { + return duration; + } + + public void setDuration(float duration) { + this.duration = duration; + } + + public Medium getMedium() { + return medium; + } + + public void setMedium(Medium medium) { + this.medium = medium; + } + + public Level getLevel() { + return level; + } + + public void setLevel(Level level) { + this.level = level; + } + + public List getPrerequisite() { + return prerequisite; + } + + public void setPrerequisite(List prerequisite) { + this.prerequisite = prerequisite; + } +} diff --git a/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/domain/Customer.java b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/domain/Customer.java new file mode 100644 index 0000000000..add568b9d4 --- /dev/null +++ b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/domain/Customer.java @@ -0,0 +1,24 @@ +package com.baeldung.jacksonannotation.domain; + +/** + * Source code github.com/eugenp/tutorials + * + * @author Alex Theedom www.baeldung.com + * @version 1.0 + */ +public class Customer extends Person { + + private String configuration; + + public Customer(String firstName, String lastName) { + super(firstName, lastName); + } + + public String getConfiguration() { + return configuration; + } + + public void setConfiguration(String configuration) { + this.configuration = configuration; + } +} diff --git a/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/domain/Inventory.java b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/domain/Inventory.java new file mode 100644 index 0000000000..f5320e6f4b --- /dev/null +++ b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/domain/Inventory.java @@ -0,0 +1,29 @@ +package com.baeldung.jacksonannotation.domain; + +import java.util.HashMap; +import java.util.Map; + +/** + * Source code github.com/eugenp/tutorials + * + * @author Alex Theedom www.baeldung.com + * @version 1.0 + */ +public class Inventory { + + private Map stock; + + private Map countryDeliveryCost = new HashMap<>(); + + public Map getStock() { + return stock; + } + + public void setStock(Map stock) { + this.stock = stock; + } + + public Map getCountryDeliveryCost() { + return countryDeliveryCost; + } +} diff --git a/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/domain/Item.java b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/domain/Item.java new file mode 100644 index 0000000000..315e411f9d --- /dev/null +++ b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/domain/Item.java @@ -0,0 +1,59 @@ +package com.baeldung.jacksonannotation.domain; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +/** + * Source code github.com/eugenp/tutorials + * + * @author Alex Theedom www.baeldung.com + * @version 1.0 + */ +public class Item { + + private UUID id; + private String title; + private List authors = new ArrayList<>(); + private float price; + + public Item(){} + + public Item(String title, Author author) { + this.id = UUID.randomUUID(); + this.title = title; + this.authors.add(author); + } + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public List getAuthors() { + return authors; + } + + public void setAuthors(List authors) { + this.authors = authors; + } + + public float getPrice() { + return price; + } + + public void setPrice(float price) { + this.price = price; + } +} diff --git a/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/domain/Order.java b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/domain/Order.java new file mode 100644 index 0000000000..85cf74d020 --- /dev/null +++ b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/domain/Order.java @@ -0,0 +1,50 @@ +package com.baeldung.jacksonannotation.domain; + +import java.util.UUID; + +/** + * Source code github.com/eugenp/tutorials + * + * @author Alex Theedom www.baeldung.com + * @version 1.0 + */ +public class Order { + + private UUID id; + private Type type; + private int internalAudit; + + public static class Type { + public long id; + public String name; + } + + public Order() { + this.id = UUID.randomUUID(); + } + + public Order(Type type) { + this(); + this.type = type; + } + + public Order(int internalAudit) { + this(); + this.type = new Type(); + this.type.id = 20; + this.type.name = "Order"; + this.internalAudit = internalAudit; + } + + public UUID getId() { + return id; + } + + public Type getType() { + return type; + } + + public void setType(Type type) { + this.type = type; + } +} diff --git a/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/domain/Person.java b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/domain/Person.java new file mode 100644 index 0000000000..f4c332b008 --- /dev/null +++ b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/domain/Person.java @@ -0,0 +1,44 @@ +package com.baeldung.jacksonannotation.domain; + +import java.util.UUID; + +/** + * Source code github.com/eugenp/tutorials + * + * @author Alex Theedom www.baeldung.com + * @version 1.0 + */ +public class Person { + + private UUID id; + private String firstName; + private String lastName; + + public Person(){} + + public Person(String firstName, String lastName) { + this.id = UUID.randomUUID(); + this.firstName = firstName; + this.lastName = lastName; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public UUID getId() { + return id; + } +} diff --git a/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/general/jsonfilter/Author.java b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/general/jsonfilter/Author.java new file mode 100644 index 0000000000..71dcf3bcfa --- /dev/null +++ b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/general/jsonfilter/Author.java @@ -0,0 +1,32 @@ +package com.baeldung.jacksonannotation.general.jsonfilter; + +import com.baeldung.jacksonannotation.domain.Item; +import com.baeldung.jacksonannotation.domain.Person; +import com.fasterxml.jackson.annotation.JsonFilter; + +import java.util.ArrayList; +import java.util.List; + +/** + * Source code github.com/eugenp/tutorials + * + * @author Alex Theedom www.baeldung.com + * @version 1.0 + */ +@JsonFilter("authorFilter") +public class Author extends Person { + + private List items = new ArrayList<>(); + + public Author(String firstName, String lastName) { + super(firstName, lastName); + } + + public List getItems() { + return items; + } + + public void setItems(List items) { + this.items = items; + } +} diff --git a/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/general/jsonformat/Book.java b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/general/jsonformat/Book.java new file mode 100644 index 0000000000..95fb962118 --- /dev/null +++ b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/general/jsonformat/Book.java @@ -0,0 +1,56 @@ +package com.baeldung.jacksonannotation.general.jsonformat; + +import com.baeldung.jacksonannotation.domain.Author; +import com.baeldung.jacksonannotation.domain.Item; +import com.fasterxml.jackson.annotation.JsonFormat; + +import java.math.BigDecimal; +import java.util.Date; + +/** + * Source code github.com/eugenp/tutorials + * + * @author Alex Theedom www.baeldung.com + * @version 1.0 + */ +public class Book extends Item { + + private String ISBN; + + @JsonFormat( + shape = JsonFormat.Shape.STRING, + pattern = "dd-MM-yyyy HH:mm:ss") + private Date published; + private BigDecimal pages; + + public Book() { + } + + public Book(String title, Author author) { + super(title, author); + } + + public String getISBN() { + return ISBN; + } + + public void setISBN(String ISBN) { + this.ISBN = ISBN; + } + + public Date getPublished() { + return published; + } + + public void setPublished(Date published) { + this.published = published; + } + + public BigDecimal getPages() { + return pages; + } + + public void setPages(BigDecimal pages) { + this.pages = pages; + } +} diff --git a/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/general/jsonidentityinfo/Author.java b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/general/jsonidentityinfo/Author.java new file mode 100644 index 0000000000..f25a0f3a82 --- /dev/null +++ b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/general/jsonidentityinfo/Author.java @@ -0,0 +1,33 @@ +package com.baeldung.jacksonannotation.general.jsonidentityinfo; + +import com.fasterxml.jackson.annotation.JsonIdentityInfo; +import com.fasterxml.jackson.annotation.ObjectIdGenerators; + +import java.util.ArrayList; +import java.util.List; + +/** + * Source code github.com/eugenp/tutorials + * + * @author Alex Theedom www.baeldung.com + * @version 1.0 + */ +@JsonIdentityInfo( + generator = ObjectIdGenerators.PropertyGenerator.class, + property = "id") +public class Author extends Person { + + private List items = new ArrayList<>(); + + public Author(String firstName, String lastName) { + super(firstName, lastName); + } + + public List getItems() { + return items; + } + + public void setItems(List items) { + this.items = items; + } +} diff --git a/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/general/jsonidentityinfo/Course.java b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/general/jsonidentityinfo/Course.java new file mode 100644 index 0000000000..02557d21fc --- /dev/null +++ b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/general/jsonidentityinfo/Course.java @@ -0,0 +1,72 @@ +package com.baeldung.jacksonannotation.general.jsonidentityinfo; + + +import java.util.List; + +/** + * Source code github.com/eugenp/tutorials + * + * @author Alex Theedom www.baeldung.com + * @version 1.0 + */ +public class Course extends Item { + + public enum Medium {CLASSROOM, ONLINE} + + public enum Level { + BEGINNER("Beginner", 1), INTERMEDIATE("Intermediate", 2), ADVANCED("Advanced", 3); + + private String name; + private int number; + + Level(String name, int number) { + this.name = name; + this.number = number; + } + + public String getName() { + return name; + } + } + + private float duration; + private Medium medium; + private Level level; + private List prerequisite; + + public Course(String title, Author author) { + super(title, author); + } + + public float getDuration() { + return duration; + } + + public void setDuration(float duration) { + this.duration = duration; + } + + public Medium getMedium() { + return medium; + } + + public void setMedium(Medium medium) { + this.medium = medium; + } + + public Level getLevel() { + return level; + } + + public void setLevel(Level level) { + this.level = level; + } + + public List getPrerequisite() { + return prerequisite; + } + + public void setPrerequisite(List prerequisite) { + this.prerequisite = prerequisite; + } +} diff --git a/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/general/jsonidentityinfo/Item.java b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/general/jsonidentityinfo/Item.java new file mode 100644 index 0000000000..6d28e313f7 --- /dev/null +++ b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/general/jsonidentityinfo/Item.java @@ -0,0 +1,65 @@ +package com.baeldung.jacksonannotation.general.jsonidentityinfo; + +import com.fasterxml.jackson.annotation.JsonIdentityInfo; +import com.fasterxml.jackson.annotation.ObjectIdGenerators; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +/** + * Source code github.com/eugenp/tutorials + * + * @author Alex Theedom www.baeldung.com + * @version 1.0 + */ +@JsonIdentityInfo( + generator = ObjectIdGenerators.PropertyGenerator.class, + property = "id") +public class Item { + + private UUID id; + private String title; + private List authors = new ArrayList<>(); + private float price; + + public Item(){} + + public Item(String title, Author author) { + this.id = UUID.randomUUID(); + this.title = title; + this.authors.add(author); + } + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public List getAuthors() { + return authors; + } + + public void setAuthors(List authors) { + this.authors = authors; + } + + public float getPrice() { + return price; + } + + public void setPrice(float price) { + this.price = price; + } +} diff --git a/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/general/jsonidentityinfo/Person.java b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/general/jsonidentityinfo/Person.java new file mode 100644 index 0000000000..38a23ebffd --- /dev/null +++ b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/general/jsonidentityinfo/Person.java @@ -0,0 +1,44 @@ +package com.baeldung.jacksonannotation.general.jsonidentityinfo; + +import java.util.UUID; + +/** + * Source code github.com/eugenp/tutorials + * + * @author Alex Theedom www.baeldung.com + * @version 1.0 + */ +public class Person { + + private UUID id; + private String firstName; + private String lastName; + + public Person(){} + + public Person(String firstName, String lastName) { + this.id = UUID.randomUUID(); + this.firstName = firstName; + this.lastName = lastName; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public UUID getId() { + return id; + } +} diff --git a/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/general/jsonproperty/Author.java b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/general/jsonproperty/Author.java new file mode 100644 index 0000000000..c1507f43d3 --- /dev/null +++ b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/general/jsonproperty/Author.java @@ -0,0 +1,29 @@ +package com.baeldung.jacksonannotation.general.jsonproperty; + +import com.baeldung.jacksonannotation.domain.Person; + +import java.util.ArrayList; +import java.util.List; + +/** + * Source code github.com/eugenp/tutorials + * + * @author Alex Theedom www.baeldung.com + * @version 1.0 + */ +public class Author extends Person { + + private List items = new ArrayList<>(); + + public Author(String firstName, String lastName) { + super(firstName, lastName); + } + + public List getItems() { + return items; + } + + public void setItems(List items) { + this.items = items; + } +} diff --git a/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/general/jsonproperty/Book.java b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/general/jsonproperty/Book.java new file mode 100644 index 0000000000..d17fef2e46 --- /dev/null +++ b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/general/jsonproperty/Book.java @@ -0,0 +1,61 @@ +package com.baeldung.jacksonannotation.general.jsonproperty; + +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.math.BigDecimal; +import java.util.Date; + +/** + * Source code github.com/eugenp/tutorials + * + * @author Alex Theedom www.baeldung.com + * @version 1.0 + */ +public class Book extends Item { + + private String ISBN; + private Date published; + private BigDecimal pages; + private String binding; + + public Book() { + } + + public Book(String title, Author author) { + super(title, author); + } + + public String getISBN() { + return ISBN; + } + + public void setISBN(String ISBN) { + this.ISBN = ISBN; + } + + public Date getPublished() { + return published; + } + + public void setPublished(Date published) { + this.published = published; + } + + public BigDecimal getPages() { + return pages; + } + + public void setPages(BigDecimal pages) { + this.pages = pages; + } + + @JsonProperty("binding") + public String coverBinding() { + return binding; + } + + @JsonProperty("binding") + public void configureBinding(String binding) { + this.binding = binding; + } +} diff --git a/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/general/jsonproperty/Item.java b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/general/jsonproperty/Item.java new file mode 100644 index 0000000000..5e189f9f9d --- /dev/null +++ b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/general/jsonproperty/Item.java @@ -0,0 +1,61 @@ +package com.baeldung.jacksonannotation.general.jsonproperty; + +import com.baeldung.jacksonannotation.domain.Person; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +/** + * Source code github.com/eugenp/tutorials + * + * @author Alex Theedom www.baeldung.com + * @version 1.0 + */ +public class Item { + + private UUID id; + private String title; + private List authors = new ArrayList<>(); + private float price; + + public Item(){} + + public Item(String title, Author author) { + this.id = UUID.randomUUID(); + this.title = title; + this.authors.add(author); + } + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public List getAuthors() { + return authors; + } + + public void setAuthors(List authors) { + this.authors = authors; + } + + public float getPrice() { + return price; + } + + public void setPrice(float price) { + this.price = price; + } +} diff --git a/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/general/jsonunwrapped/Order.java b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/general/jsonunwrapped/Order.java new file mode 100644 index 0000000000..971f0a13c9 --- /dev/null +++ b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/general/jsonunwrapped/Order.java @@ -0,0 +1,54 @@ +package com.baeldung.jacksonannotation.general.jsonunwrapped; + +import com.fasterxml.jackson.annotation.JsonUnwrapped; + +import java.util.UUID; + +/** + * Source code github.com/eugenp/tutorials + * + * @author Alex Theedom www.baeldung.com + * @version 1.0 + */ +public class Order { + + private UUID id; + + @JsonUnwrapped + private Type type; + private int internalAudit; + + public static class Type { + public long id; + public String name; + } + + public Order() { + this.id = UUID.randomUUID(); + } + + public Order(Type type) { + this(); + this.type = type; + } + + public Order(int internalAudit) { + this(); + this.type = new Type(); + this.type.id = 20; + this.type.name = "Order"; + this.internalAudit = internalAudit; + } + + public UUID getId() { + return id; + } + + public Type getType() { + return type; + } + + public void setType(Type type) { + this.type = type; + } +} diff --git a/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/general/jsonview/Order.java b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/general/jsonview/Order.java new file mode 100644 index 0000000000..7a9c6f3930 --- /dev/null +++ b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/general/jsonview/Order.java @@ -0,0 +1,57 @@ +package com.baeldung.jacksonannotation.general.jsonview; + +import com.fasterxml.jackson.annotation.JsonView; + +import java.util.UUID; + +/** + * Source code github.com/eugenp/tutorials + * + * @author Alex Theedom www.baeldung.com + * @version 1.0 + */ +public class Order { + + @JsonView(Views.Public.class) + private UUID id; + + @JsonView(Views.Public.class) + private Type type; + + @JsonView(Views.Internal.class) + private int internalAudit; + + public static class Type { + public long id; + public String name; + } + + public Order() { + this.id = UUID.randomUUID(); + } + + public Order(Type type) { + this(); + this.type = type; + } + + public Order(int internalAudit) { + this(); + this.type = new Type(); + this.type.id = 20; + this.type.name = "Order"; + this.internalAudit = internalAudit; + } + + public UUID getId() { + return id; + } + + public Type getType() { + return type; + } + + public void setType(Type type) { + this.type = type; + } +} diff --git a/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/general/jsonview/Views.java b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/general/jsonview/Views.java new file mode 100644 index 0000000000..87cb3db9ea --- /dev/null +++ b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/general/jsonview/Views.java @@ -0,0 +1,15 @@ +package com.baeldung.jacksonannotation.general.jsonview; + +/** + * Source code github.com/eugenp/tutorials + * + * @author Alex Theedom www.baeldung.com + * @version 1.0 + */ +public class Views { + public static class Public { + } + + public static class Internal extends Public { + } +} diff --git a/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/general/reference/Author.java b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/general/reference/Author.java new file mode 100644 index 0000000000..8f99d35af0 --- /dev/null +++ b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/general/reference/Author.java @@ -0,0 +1,30 @@ +package com.baeldung.jacksonannotation.general.reference; + +import com.fasterxml.jackson.annotation.JsonManagedReference; + +import java.util.ArrayList; +import java.util.List; + +/** + * Source code github.com/eugenp/tutorials + * + * @author Alex Theedom www.baeldung.com + * @version 1.0 + */ +public class Author extends Person { + + private List items = new ArrayList<>(); + + public Author(String firstName, String lastName) { + super(firstName, lastName); + } + + @JsonManagedReference + public List getItems() { + return items; + } + + public void setItems(List items) { + this.items = items; + } +} diff --git a/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/general/reference/Course.java b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/general/reference/Course.java new file mode 100644 index 0000000000..12c317d5c3 --- /dev/null +++ b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/general/reference/Course.java @@ -0,0 +1,72 @@ +package com.baeldung.jacksonannotation.general.reference; + + +import java.util.List; + +/** + * Source code github.com/eugenp/tutorials + * + * @author Alex Theedom www.baeldung.com + * @version 1.0 + */ +public class Course extends Item { + + public enum Medium {CLASSROOM, ONLINE} + + public enum Level { + BEGINNER("Beginner", 1), INTERMEDIATE("Intermediate", 2), ADVANCED("Advanced", 3); + + private String name; + private int number; + + Level(String name, int number) { + this.name = name; + this.number = number; + } + + public String getName() { + return name; + } + } + + private float duration; + private Medium medium; + private Level level; + private List prerequisite; + + public Course(String title, Author author) { + super(title, author); + } + + public float getDuration() { + return duration; + } + + public void setDuration(float duration) { + this.duration = duration; + } + + public Medium getMedium() { + return medium; + } + + public void setMedium(Medium medium) { + this.medium = medium; + } + + public Level getLevel() { + return level; + } + + public void setLevel(Level level) { + this.level = level; + } + + public List getPrerequisite() { + return prerequisite; + } + + public void setPrerequisite(List prerequisite) { + this.prerequisite = prerequisite; + } +} diff --git a/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/general/reference/Item.java b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/general/reference/Item.java new file mode 100644 index 0000000000..b596cf0017 --- /dev/null +++ b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/general/reference/Item.java @@ -0,0 +1,63 @@ +package com.baeldung.jacksonannotation.general.reference; + +import com.fasterxml.jackson.annotation.JsonBackReference; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +/** + * Source code github.com/eugenp/tutorials + * + * @author Alex Theedom www.baeldung.com + * @version 1.0 + */ +public class Item { + + private UUID id; + private String title; + + @JsonBackReference + private List authors = new ArrayList<>(); + private float price; + + public Item(){} + + public Item(String title, Author author) { + this.id = UUID.randomUUID(); + this.title = title; + this.authors.add(author); + } + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public List getAuthors() { + return authors; + } + + public void setAuthors(List authors) { + this.authors = authors; + } + + public float getPrice() { + return price; + } + + public void setPrice(float price) { + this.price = price; + } +} diff --git a/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/general/reference/Person.java b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/general/reference/Person.java new file mode 100644 index 0000000000..f5303c6a17 --- /dev/null +++ b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/general/reference/Person.java @@ -0,0 +1,44 @@ +package com.baeldung.jacksonannotation.general.reference; + +import java.util.UUID; + +/** + * Source code github.com/eugenp/tutorials + * + * @author Alex Theedom www.baeldung.com + * @version 1.0 + */ +public class Person { + + private UUID id; + private String firstName; + private String lastName; + + public Person(){} + + public Person(String firstName, String lastName) { + this.id = UUID.randomUUID(); + this.firstName = firstName; + this.lastName = lastName; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public UUID getId() { + return id; + } +} diff --git a/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/inclusion/jsonautodetect/Order.java b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/inclusion/jsonautodetect/Order.java new file mode 100644 index 0000000000..4ebbbde984 --- /dev/null +++ b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/inclusion/jsonautodetect/Order.java @@ -0,0 +1,54 @@ +package com.baeldung.jacksonannotation.inclusion.jsonautodetect; + +import com.fasterxml.jackson.annotation.JsonAutoDetect; +import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; + +import java.util.UUID; + +/** + * Source code github.com/eugenp/tutorials + * + * @author Alex Theedom www.baeldung.com + * @version 1.0 + */ +@JsonAutoDetect(fieldVisibility = Visibility.ANY) +public class Order { + + private UUID id; + private Type type; + private int internalAudit; + + public static class Type { + public long id; + public String name; + } + + public Order() { + this.id = UUID.randomUUID(); + } + + public Order(Type type) { + this(); + this.type = type; + } + + public Order(int internalAudit) { + this(); + this.type = new Type(); + this.type.id = 20; + this.type.name = "Order"; + this.internalAudit = internalAudit; + } + + public UUID getId() { + return id; + } + + public Type getType() { + return type; + } + + public void setType(Type type) { + this.type = type; + } +} diff --git a/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/inclusion/jsonignore/Author.java b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/inclusion/jsonignore/Author.java new file mode 100644 index 0000000000..2d8676deaf --- /dev/null +++ b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/inclusion/jsonignore/Author.java @@ -0,0 +1,29 @@ +package com.baeldung.jacksonannotation.inclusion.jsonignore; + +import com.baeldung.jacksonannotation.domain.Item; + +import java.util.ArrayList; +import java.util.List; + +/** + * Source code github.com/eugenp/tutorials + * + * @author Alex Theedom www.baeldung.com + * @version 1.0 + */ +public class Author extends Person { + + private List items = new ArrayList<>(); + + public Author(String firstName, String lastName) { + super(firstName, lastName); + } + + public List getItems() { + return items; + } + + public void setItems(List items) { + this.items = items; + } +} diff --git a/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/inclusion/jsonignore/Person.java b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/inclusion/jsonignore/Person.java new file mode 100644 index 0000000000..eb4ff77f42 --- /dev/null +++ b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/inclusion/jsonignore/Person.java @@ -0,0 +1,47 @@ +package com.baeldung.jacksonannotation.inclusion.jsonignore; + +import com.fasterxml.jackson.annotation.JsonIgnore; + +import java.util.UUID; + +/** + * Source code github.com/eugenp/tutorials + * + * @author Alex Theedom www.baeldung.com + * @version 1.0 + */ +public class Person { + + @JsonIgnore + private UUID id; + private String firstName; + private String lastName; + + public Person(){} + + public Person(String firstName, String lastName) { + this.id = UUID.randomUUID(); + this.firstName = firstName; + this.lastName = lastName; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public UUID getId() { + return id; + } +} diff --git a/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/inclusion/jsonignoreproperties/Course.java b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/inclusion/jsonignoreproperties/Course.java new file mode 100644 index 0000000000..8b61f5a215 --- /dev/null +++ b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/inclusion/jsonignoreproperties/Course.java @@ -0,0 +1,76 @@ +package com.baeldung.jacksonannotation.inclusion.jsonignoreproperties; + +import com.baeldung.jacksonannotation.domain.Author; +import com.baeldung.jacksonannotation.domain.Item; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +import java.util.List; + +/** + * Source code github.com/eugenp/tutorials + * + * @author Alex Theedom www.baeldung.com + * @version 1.0 + */ +@JsonIgnoreProperties({"medium"}) +public class Course extends Item { + + public enum Medium {CLASSROOM, ONLINE} + + public enum Level { + BEGINNER("Beginner", 1), INTERMEDIATE("Intermediate", 2), ADVANCED("Advanced", 3); + + private String name; + private int number; + + Level(String name, int number) { + this.name = name; + this.number = number; + } + + public String getName() { + return name; + } + } + + private float duration; + private Medium medium; + private Level level; + private List prerequisite; + + public Course(String title, Author author) { + super(title, author); + } + + public float getDuration() { + return duration; + } + + public void setDuration(float duration) { + this.duration = duration; + } + + public Medium getMedium() { + return medium; + } + + public void setMedium(Medium medium) { + this.medium = medium; + } + + public Level getLevel() { + return level; + } + + public void setLevel(Level level) { + this.level = level; + } + + public List getPrerequisite() { + return prerequisite; + } + + public void setPrerequisite(List prerequisite) { + this.prerequisite = prerequisite; + } +} diff --git a/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/inclusion/jsonignoretype/Order.java b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/inclusion/jsonignoretype/Order.java new file mode 100644 index 0000000000..df4e167163 --- /dev/null +++ b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/inclusion/jsonignoretype/Order.java @@ -0,0 +1,44 @@ +package com.baeldung.jacksonannotation.inclusion.jsonignoretype; + +import com.fasterxml.jackson.annotation.JsonIgnoreType; + +import java.util.UUID; + +/** + * Source code github.com/eugenp/tutorials + * + * @author Alex Theedom www.baeldung.com + * @version 1.0 + */ +public class Order { + + private UUID id; + private Type type; + + @JsonIgnoreType + public static class Type { + public long id; + public String name; + } + + public Order() { + this.id = UUID.randomUUID(); + } + + public Order(Type type) { + this(); + this.type = type; + } + + public UUID getId() { + return id; + } + + public Type getType() { + return type; + } + + public void setType(Type type) { + this.type = type; + } +} diff --git a/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/inclusion/jsoninclude/Author.java b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/inclusion/jsoninclude/Author.java new file mode 100644 index 0000000000..d5c20de2f5 --- /dev/null +++ b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/inclusion/jsoninclude/Author.java @@ -0,0 +1,34 @@ +package com.baeldung.jacksonannotation.inclusion.jsoninclude; + +import com.baeldung.jacksonannotation.domain.Item; +import com.baeldung.jacksonannotation.domain.Person; +import com.fasterxml.jackson.annotation.JsonInclude; + +import java.util.ArrayList; +import java.util.List; + +import static com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL; + +/** + * Source code github.com/eugenp/tutorials + * + * @author Alex Theedom www.baeldung.com + * @version 1.0 + */ +@JsonInclude(NON_NULL) +public class Author extends Person { + + private List items = new ArrayList<>(); + + public Author(String firstName, String lastName) { + super(firstName, lastName); + } + + public List getItems() { + return items; + } + + public void setItems(List items) { + this.items = items; + } +} diff --git a/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/miscellaneous/custom/Course.java b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/miscellaneous/custom/Course.java new file mode 100644 index 0000000000..6a0c3edec0 --- /dev/null +++ b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/miscellaneous/custom/Course.java @@ -0,0 +1,74 @@ +package com.baeldung.jacksonannotation.miscellaneous.custom; + +import com.baeldung.jacksonannotation.domain.Author; + +import java.util.List; + +/** + * Source code github.com/eugenp/tutorials + * + * @author Alex Theedom www.baeldung.com + * @version 1.0 + */ +@CustomCourseAnnotation +public class Course extends Item { + + public enum Medium {CLASSROOM, ONLINE} + + public enum Level { + BEGINNER("Beginner", 1), INTERMEDIATE("Intermediate", 2), ADVANCED("Advanced", 3); + + private String name; + private int number; + + Level(String name, int number) { + this.name = name; + this.number = number; + } + + public String getName() { + return name; + } + } + + private float duration; + private Medium medium; + private Level level; + private List prerequisite; + + public Course(String title, Author author) { + super(title, author); + } + + public float getDuration() { + return duration; + } + + public void setDuration(float duration) { + this.duration = duration; + } + + public Medium getMedium() { + return medium; + } + + public void setMedium(Medium medium) { + this.medium = medium; + } + + public Level getLevel() { + return level; + } + + public void setLevel(Level level) { + this.level = level; + } + + public List getPrerequisite() { + return prerequisite; + } + + public void setPrerequisite(List prerequisite) { + this.prerequisite = prerequisite; + } +} diff --git a/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/miscellaneous/custom/CustomCourseAnnotation.java b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/miscellaneous/custom/CustomCourseAnnotation.java new file mode 100644 index 0000000000..d2185ae4bf --- /dev/null +++ b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/miscellaneous/custom/CustomCourseAnnotation.java @@ -0,0 +1,20 @@ +package com.baeldung.jacksonannotation.miscellaneous.custom; + +import com.fasterxml.jackson.annotation.*; + +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; + +/** + * Source code github.com/eugenp/tutorials + * + * @author Alex Theedom www.baeldung.com + * @version 1.0 + */ +@Retention(RetentionPolicy.RUNTIME) +@JacksonAnnotationsInside +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({"title", "price", "id", "duration", "authors", "level"}) +@JsonIgnoreProperties({"prerequisite"}) +public @interface CustomCourseAnnotation { +} diff --git a/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/miscellaneous/custom/Item.java b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/miscellaneous/custom/Item.java new file mode 100644 index 0000000000..327798d277 --- /dev/null +++ b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/miscellaneous/custom/Item.java @@ -0,0 +1,62 @@ +package com.baeldung.jacksonannotation.miscellaneous.custom; + +import com.baeldung.jacksonannotation.domain.Author; +import com.baeldung.jacksonannotation.domain.Person; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +/** + * Source code github.com/eugenp/tutorials + * + * @author Alex Theedom www.baeldung.com + * @version 1.0 + */ +public class Item { + + private UUID id; + private String title; + private List authors = new ArrayList<>(); + private float price; + + public Item(){} + + public Item(String title, Author author) { + this.id = UUID.randomUUID(); + this.title = title; + this.authors.add(author); + } + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public List getAuthors() { + return authors; + } + + public void setAuthors(List authors) { + this.authors = authors; + } + + public float getPrice() { + return price; + } + + public void setPrice(float price) { + this.price = price; + } +} diff --git a/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/miscellaneous/disable/Author.java b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/miscellaneous/disable/Author.java new file mode 100644 index 0000000000..851ba5f40f --- /dev/null +++ b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/miscellaneous/disable/Author.java @@ -0,0 +1,36 @@ +package com.baeldung.jacksonannotation.miscellaneous.disable; + +import com.baeldung.jacksonannotation.domain.Item; +import com.baeldung.jacksonannotation.domain.Person; +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + +import java.util.ArrayList; +import java.util.List; + +/** + * Source code github.com/eugenp/tutorials + * + * @author Alex Theedom www.baeldung.com + * @version 1.0 + */ +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({"lastName", "items", "firstName", "id"}) +public class Author extends Person { + + @JsonIgnore + private List items = new ArrayList<>(); + + public Author(String firstName, String lastName) { + super(firstName, lastName); + } + + public List getItems() { + return items; + } + + public void setItems(List items) { + this.items = items; + } +} diff --git a/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/miscellaneous/mixin/Author.java b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/miscellaneous/mixin/Author.java new file mode 100644 index 0000000000..4ee9351afb --- /dev/null +++ b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/miscellaneous/mixin/Author.java @@ -0,0 +1,30 @@ +package com.baeldung.jacksonannotation.miscellaneous.mixin; + +import com.baeldung.jacksonannotation.domain.Item; +import com.baeldung.jacksonannotation.domain.Person; + +import java.util.ArrayList; +import java.util.List; + +/** + * Source code github.com/eugenp/tutorials + * + * @author Alex Theedom www.baeldung.com + * @version 1.0 + */ +public class Author extends Person { + + private List items = new ArrayList<>(); + + public Author(String firstName, String lastName) { + super(firstName, lastName); + } + + public List getItems() { + return items; + } + + public void setItems(List items) { + this.items = items; + } +} diff --git a/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/miscellaneous/mixin/IgnoreListMixIn.java b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/miscellaneous/mixin/IgnoreListMixIn.java new file mode 100644 index 0000000000..c7ead90137 --- /dev/null +++ b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/miscellaneous/mixin/IgnoreListMixIn.java @@ -0,0 +1,13 @@ +package com.baeldung.jacksonannotation.miscellaneous.mixin; + +import com.fasterxml.jackson.annotation.JsonIgnoreType; + +/** + * Source code github.com/eugenp/tutorials + * + * @author Alex Theedom www.baeldung.com + * @version 1.0 + */ +@JsonIgnoreType +public class IgnoreListMixIn { +} diff --git a/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/polymorphism/Order.java b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/polymorphism/Order.java new file mode 100644 index 0000000000..6f1494988f --- /dev/null +++ b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/polymorphism/Order.java @@ -0,0 +1,66 @@ +package com.baeldung.jacksonannotation.polymorphism; + +import com.fasterxml.jackson.annotation.JsonSubTypes; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +import java.util.UUID; + +/** + * Source code github.com/eugenp/tutorials + * + * @author Alex Theedom www.baeldung.com + * @version 1.0 + */ +public class Order { + + private UUID id; + private Type type; + private int internalAudit; + + @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, + include = JsonTypeInfo.As.PROPERTY, + property = "ordertype") + @JsonSubTypes({ + @JsonSubTypes.Type(value = InternalType.class, name = "internal") + }) + public static class Type { + public long id; + public String name; + } + + @JsonTypeName("internal") + public static class InternalType extends Type { + public long id; + public String name; + } + + public Order() { + this.id = UUID.randomUUID(); + } + + public Order(Type type) { + this(); + this.type = type; + } + + public Order(int internalAudit) { + this(); + this.type = new Type(); + this.type.id = 20; + this.type.name = "Order"; + this.internalAudit = internalAudit; + } + + public UUID getId() { + return id; + } + + public Type getType() { + return type; + } + + public void setType(Type type) { + this.type = type; + } +} diff --git a/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/serialization/jsonanygetter/Inventory.java b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/serialization/jsonanygetter/Inventory.java new file mode 100644 index 0000000000..a6938de496 --- /dev/null +++ b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/serialization/jsonanygetter/Inventory.java @@ -0,0 +1,43 @@ +package com.baeldung.jacksonannotation.serialization.jsonanygetter; + +import com.baeldung.jacksonannotation.domain.Author; +import com.baeldung.jacksonannotation.domain.Item; +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import java.util.HashMap; +import java.util.Map; + +/** + * Source code github.com/eugenp/tutorials + * + * @author Alex Theedom www.baeldung.com + * @version 1.0 + */ +public class Inventory { + + private String location; + + private Map stock = new HashMap<>(); + + private Map countryDeliveryCost = new HashMap<>(); + + public String getLocation() { + return location; + } + + public void setLocation(String location) { + this.location = location; + } + + @JsonIgnore + public Map getStock() { + return stock; + } + + @JsonAnyGetter + public Map getCountryDeliveryCost() { + return countryDeliveryCost; + } + +} diff --git a/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/serialization/jsongetter/Author.java b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/serialization/jsongetter/Author.java new file mode 100644 index 0000000000..eccc306b45 --- /dev/null +++ b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/serialization/jsongetter/Author.java @@ -0,0 +1,33 @@ +package com.baeldung.jacksonannotation.serialization.jsongetter; + + +import com.baeldung.jacksonannotation.domain.Item; +import com.baeldung.jacksonannotation.domain.Person; +import com.fasterxml.jackson.annotation.JsonGetter; + +import java.util.ArrayList; +import java.util.List; + +/** + * Source code github.com/eugenp/tutorials + * + * @author Alex Theedom www.baeldung.com + * @version 1.0 + */ +public class Author extends Person { + + List items = new ArrayList<>(); + + public Author(String firstName, String lastName) { + super(firstName, lastName); + } + + @JsonGetter("publications") + public List getItems() { + return items; + } + + public void setItems(List items) { + this.items = items; + } +} diff --git a/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/serialization/jsonpropertyorder/Author.java b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/serialization/jsonpropertyorder/Author.java new file mode 100644 index 0000000000..fae2d52dcb --- /dev/null +++ b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/serialization/jsonpropertyorder/Author.java @@ -0,0 +1,52 @@ +package com.baeldung.jacksonannotation.serialization.jsonpropertyorder; + + +import com.baeldung.jacksonannotation.domain.Item; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + +import java.util.ArrayList; +import java.util.List; + +/** + * Source code github.com/eugenp/tutorials + * + * @author Alex Theedom www.baeldung.com + * @version 1.0 + */ +@JsonPropertyOrder(value = {"items", "firstName", "lastName", "id"}, alphabetic = true) +public class Author extends Person { + + private String zIndex; + + private String alphaIndex; + + List items = new ArrayList<>(); + + public Author(String firstName, String lastName) { + super(firstName, lastName); + } + + public List getItems() { + return items; + } + + public void setItems(List items) { + this.items = items; + } + + public String getzIndex() { + return zIndex; + } + + public void setzIndex(String zIndex) { + this.zIndex = zIndex; + } + + public String getAlphaIndex() { + return alphaIndex; + } + + public void setAlphaIndex(String alphaIndex) { + this.alphaIndex = alphaIndex; + } +} diff --git a/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/serialization/jsonpropertyorder/Person.java b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/serialization/jsonpropertyorder/Person.java new file mode 100644 index 0000000000..c976015001 --- /dev/null +++ b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/serialization/jsonpropertyorder/Person.java @@ -0,0 +1,42 @@ +package com.baeldung.jacksonannotation.serialization.jsonpropertyorder; + +import java.util.UUID; + +/** + * Source code github.com/eugenp/tutorials + * + * @author Alex Theedom www.baeldung.com + * @version 1.0 + */ +public class Person { + + private UUID id; + private String firstName; + private String lastName; + + public Person(String firstName, String lastName) { + this.id = UUID.randomUUID(); + this.firstName = firstName; + this.lastName = lastName; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public UUID getId() { + return id; + } +} diff --git a/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/serialization/jsonrawvalue/Customer.java b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/serialization/jsonrawvalue/Customer.java new file mode 100644 index 0000000000..f4235e4afc --- /dev/null +++ b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/serialization/jsonrawvalue/Customer.java @@ -0,0 +1,28 @@ +package com.baeldung.jacksonannotation.serialization.jsonrawvalue; + +import com.baeldung.jacksonannotation.domain.Person; +import com.fasterxml.jackson.annotation.JsonRawValue; + +/** + * Source code github.com/eugenp/tutorials + * + * @author Alex Theedom www.baeldung.com + * @version 1.0 + */ +public class Customer extends Person { + + @JsonRawValue + private String configuration; + + public Customer(String firstName, String lastName) { + super(firstName, lastName); + } + + public String getConfiguration() { + return configuration; + } + + public void setConfiguration(String configuration) { + this.configuration = configuration; + } +} diff --git a/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/serialization/jsonrootname/Author.java b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/serialization/jsonrootname/Author.java new file mode 100644 index 0000000000..b7c527c06f --- /dev/null +++ b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/serialization/jsonrootname/Author.java @@ -0,0 +1,32 @@ +package com.baeldung.jacksonannotation.serialization.jsonrootname; + +import com.baeldung.jacksonannotation.domain.Item; +import com.baeldung.jacksonannotation.domain.Person; +import com.fasterxml.jackson.annotation.JsonRootName; + +import java.util.ArrayList; +import java.util.List; + +/** + * Source code github.com/eugenp/tutorials + * + * @author Alex Theedom www.baeldung.com + * @version 1.0 + */ +@JsonRootName("writer") +public class Author extends Person { + + List items = new ArrayList<>(); + + public Author(String firstName, String lastName) { + super(firstName, lastName); + } + + public List getItems() { + return items; + } + + public void setItems(List items) { + this.items = items; + } +} diff --git a/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/serialization/jsonserialize/Author.java b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/serialization/jsonserialize/Author.java new file mode 100644 index 0000000000..4c14f6375f --- /dev/null +++ b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/serialization/jsonserialize/Author.java @@ -0,0 +1,30 @@ +package com.baeldung.jacksonannotation.serialization.jsonserialize; + +import com.baeldung.jacksonannotation.domain.Item; +import com.baeldung.jacksonannotation.domain.Person; + +import java.util.ArrayList; +import java.util.List; + +/** + * Source code github.com/eugenp/tutorials + * + * @author Alex Theedom www.baeldung.com + * @version 1.0 + */ +public class Author extends Person { + + List items = new ArrayList<>(); + + public Author(String firstName, String lastName) { + super(firstName, lastName); + } + + public List getItems() { + return items; + } + + public void setItems(List items) { + this.items = items; + } +} diff --git a/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/serialization/jsonserialize/Book.java b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/serialization/jsonserialize/Book.java new file mode 100644 index 0000000000..8e059c9fe5 --- /dev/null +++ b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/serialization/jsonserialize/Book.java @@ -0,0 +1,53 @@ +package com.baeldung.jacksonannotation.serialization.jsonserialize; + +import com.fasterxml.jackson.databind.annotation.JsonSerialize; + +import java.math.BigDecimal; +import java.util.Date; + +/** + * Source code github.com/eugenp/tutorials + * + * @author Alex Theedom www.baeldung.com + * @version 1.0 + */ +public class Book extends Item { + + private String ISBN; + + @JsonSerialize(using = CustomDateSerializer.class) + private Date published; + private BigDecimal pages; + + public Book(){ + super(); + } + + public Book(String title, Author author) { + super(title, author); + } + + public String getISBN() { + return ISBN; + } + + public void setISBN(String ISBN) { + this.ISBN = ISBN; + } + + public Date getPublished() { + return published; + } + + public void setPublished(Date published) { + this.published = published; + } + + public BigDecimal getPages() { + return pages; + } + + public void setPages(BigDecimal pages) { + this.pages = pages; + } +} diff --git a/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/serialization/jsonserialize/CustomDateSerializer.java b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/serialization/jsonserialize/CustomDateSerializer.java new file mode 100644 index 0000000000..8dacf1f2db --- /dev/null +++ b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/serialization/jsonserialize/CustomDateSerializer.java @@ -0,0 +1,36 @@ +package com.baeldung.jacksonannotation.serialization.jsonserialize; + +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.ser.std.StdSerializer; + +import java.io.IOException; +import java.text.SimpleDateFormat; +import java.util.Date; + +/** + * Source code github.com/eugenp/tutorials + * + * @author Alex Theedom www.baeldung.com + * @version 1.0 + */ +public class CustomDateSerializer extends StdSerializer { + + private static SimpleDateFormat formatter = + new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); + + public CustomDateSerializer() { + this(null); + } + + public CustomDateSerializer(Class t) { + super(t); + } + + @Override + public void serialize(Date value, JsonGenerator gen, SerializerProvider arg2) + throws IOException, JsonProcessingException { + gen.writeString(formatter.format(value)); + } +} diff --git a/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/serialization/jsonserialize/Item.java b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/serialization/jsonserialize/Item.java new file mode 100644 index 0000000000..7d50305399 --- /dev/null +++ b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/serialization/jsonserialize/Item.java @@ -0,0 +1,61 @@ +package com.baeldung.jacksonannotation.serialization.jsonserialize; + +import com.baeldung.jacksonannotation.domain.Person; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +/** + * Source code github.com/eugenp/tutorials + * + * @author Alex Theedom www.baeldung.com + * @version 1.0 + */ +public class Item { + + private UUID id; + private String title; + private List authors = new ArrayList<>(); + private float price; + + public Item(){} + + public Item(String title, Author author) { + this.id = UUID.randomUUID(); + this.title = title; + this.authors.add(author); + } + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public List getAuthors() { + return authors; + } + + public void setAuthors(List authors) { + this.authors = authors; + } + + public float getPrice() { + return price; + } + + public void setPrice(float price) { + this.price = price; + } +} diff --git a/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/serialization/jsonvalue/Author.java b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/serialization/jsonvalue/Author.java new file mode 100644 index 0000000000..6f0a28cc73 --- /dev/null +++ b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/serialization/jsonvalue/Author.java @@ -0,0 +1,40 @@ +package com.baeldung.jacksonannotation.serialization.jsonvalue; + +import com.baeldung.jacksonannotation.domain.Item; +import com.baeldung.jacksonannotation.domain.Person; +import com.fasterxml.jackson.annotation.JsonValue; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Source code github.com/eugenp/tutorials + * + * @author Alex Theedom www.baeldung.com + * @version 1.0 + */ +public class Author extends Person { + + List items = new ArrayList<>(); + + public Author(String firstName, String lastName) { + super(firstName, lastName); + } + + public List getItems() { + return items; + } + + public void setItems(List items) { + this.items = items; + } + + @JsonValue + public Map toJson() { + Map values = new HashMap<>(); + values.put("name", getFirstName() + " " + getLastName()); + return values; + } +} diff --git a/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/serialization/jsonvalue/Course.java b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/serialization/jsonvalue/Course.java new file mode 100644 index 0000000000..7e8b4708ee --- /dev/null +++ b/video-tutorials/jackson-annotations/src/main/java/com/baeldung/jacksonannotation/serialization/jsonvalue/Course.java @@ -0,0 +1,76 @@ +package com.baeldung.jacksonannotation.serialization.jsonvalue; + +import com.baeldung.jacksonannotation.domain.Author; +import com.baeldung.jacksonannotation.domain.Item; +import com.fasterxml.jackson.annotation.JsonValue; + +import java.util.List; + +/** + * Source code github.com/eugenp/tutorials + * + * @author Alex Theedom www.baeldung.com + * @version 1.0 + */ +public class Course extends Item { + + public enum Medium {CLASSROOM, ONLINE} + + public enum Level { + BEGINNER("Beginner", 1), INTERMEDIATE("Intermediate", 2), ADVANCED("Advanced", 3); + + private String name; + private int number; + + Level(String name, int number) { + this.name = name; + this.number = number; + } + + @JsonValue + public String getName() { + return name; + } + } + + private float duration; + private Medium medium; + private Level level; + private List prerequisite; + + public Course(String title, Author author) { + super(title, author); + } + + public float getDuration() { + return duration; + } + + public void setDuration(float duration) { + this.duration = duration; + } + + public Medium getMedium() { + return medium; + } + + public void setMedium(Medium medium) { + this.medium = medium; + } + + public Level getLevel() { + return level; + } + + public void setLevel(Level level) { + this.level = level; + } + + public List getPrerequisite() { + return prerequisite; + } + + public void setPrerequisite(List prerequisite) { + this.prerequisite = prerequisite; + } +} diff --git a/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/deserialization/jacksoninject/JacksonInjectTest.java b/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/deserialization/jacksoninject/JacksonInjectTest.java new file mode 100644 index 0000000000..e6c12f14a6 --- /dev/null +++ b/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/deserialization/jacksoninject/JacksonInjectTest.java @@ -0,0 +1,45 @@ +package com.baeldung.jacksonannotation.deserialization.jacksoninject; + +import com.fasterxml.jackson.databind.InjectableValues; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.Test; + +import java.io.IOException; +import java.util.UUID; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Source code github.com/eugenp/tutorials + * + * @author Alex Theedom www.baeldung.com + * @version 1.0 + */ +public class JacksonInjectTest { + + @Test + public void whenDeserializingUsingJacksonInject_thenCorrect() throws IOException { + + UUID id = UUID.fromString("9616dc8c-bad3-11e6-a4a6-cec0c932ce01"); + + // arrange + String authorJson = "{\"firstName\": \"Alex\", \"lastName\": \"Theedom\"}"; + + // act + InjectableValues inject = new InjectableValues.Std().addValue(UUID.class, id); + Author author = new ObjectMapper().reader(inject).forType(Author.class).readValue(authorJson); + + // assert + assertThat(author.getId()).isEqualTo(id); + + + /* + { + "firstName": "Alex", + "lastName": "Theedom", + "publications": [] + } + */ + + } +} \ No newline at end of file diff --git a/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/deserialization/jsonanysetter/JsonAnySetterTest.java b/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/deserialization/jsonanysetter/JsonAnySetterTest.java new file mode 100644 index 0000000000..3d49d699ac --- /dev/null +++ b/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/deserialization/jsonanysetter/JsonAnySetterTest.java @@ -0,0 +1,37 @@ +package com.baeldung.jacksonannotation.deserialization.jsonanysetter; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.Test; + +import java.io.IOException; + +import static io.restassured.path.json.JsonPath.from; +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Source code github.com/eugenp/tutorials + * + * @author Alex Theedom www.baeldung.com + * @version 1.0 + */ +public class JsonAnySetterTest { + + @Test + public void whenDeserializingUsingJsonAnySetter_thenCorrect() throws IOException { + + // arrange + String json = "{\"USA\":10.00,\"UK\":15.00,\"China\":23.00,\"Brazil\":12.00,\"France\":8.00,\"Russia\":18.00}"; + + // act + Inventory inventory = new ObjectMapper().readerFor(Inventory.class).readValue(json); + + // assert + assertThat(from(json).getMap(".").get("USA")).isEqualTo(inventory.getCountryDeliveryCost().get("USA")); + assertThat(from(json).getMap(".").get("UK")).isEqualTo(inventory.getCountryDeliveryCost().get("UK")); + assertThat(from(json).getMap(".").get("China")).isEqualTo(inventory.getCountryDeliveryCost().get("China")); + assertThat(from(json).getMap(".").get("Brazil")).isEqualTo(inventory.getCountryDeliveryCost().get("Brazil")); + assertThat(from(json).getMap(".").get("France")).isEqualTo(inventory.getCountryDeliveryCost().get("France")); + assertThat(from(json).getMap(".").get("Russia")).isEqualTo(inventory.getCountryDeliveryCost().get("Russia")); + + } +} \ No newline at end of file diff --git a/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/deserialization/jsoncreator/JsonCreatorTest.java b/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/deserialization/jsoncreator/JsonCreatorTest.java new file mode 100644 index 0000000000..b40c639042 --- /dev/null +++ b/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/deserialization/jsoncreator/JsonCreatorTest.java @@ -0,0 +1,44 @@ +package com.baeldung.jacksonannotation.deserialization.jsoncreator; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.Test; + +import java.io.IOException; + +import static io.restassured.path.json.JsonPath.from; +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Source code github.com/eugenp/tutorials + * + * @author Alex Theedom www.baeldung.com + * @version 1.0 + */ +public class JsonCreatorTest { + + @Test + public void whenDeserializingUsingJsonCreator_thenCorrect() throws IOException { + + // arrange + String authorJson = + "{" + + " \"christianName\": \"Alex\"," + + " \"surname\": \"Theedom\"" + + "}"; + + // act + final Author author = new ObjectMapper().readerFor(Author.class).readValue(authorJson); + + // assert + assertThat(from(authorJson).getString("christianName")).isEqualTo(author.getFirstName()); + assertThat(from(authorJson).getString("surname")).isEqualTo(author.getLastName()); + + /* + { + "christianName": "Alex", + "surname": "Theedom" + } + */ + + } +} \ No newline at end of file diff --git a/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/deserialization/jsondeserialize/JsonDeserializeTest.java b/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/deserialization/jsondeserialize/JsonDeserializeTest.java new file mode 100644 index 0000000000..77dde1b59b --- /dev/null +++ b/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/deserialization/jsondeserialize/JsonDeserializeTest.java @@ -0,0 +1,34 @@ +package com.baeldung.jacksonannotation.deserialization.jsondeserialize; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.Test; + +import java.io.IOException; +import java.text.SimpleDateFormat; + +import static io.restassured.path.json.JsonPath.from; +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Source code github.com/eugenp/tutorials + * + * @author Alex Theedom www.baeldung.com + * @version 1.0 + */ +public class JsonDeserializeTest { + + @Test + public void whenDeserializingUsingJsonDeserialize_thenCorrect() throws IOException { + + // arrange + String bookJson = "{\"id\":\"957c43f2-fa2e-42f9-bf75-6e3d5bb6960a\",\"title\":\"Effective Java\",\"authors\":[{\"id\":\"9bcd817d-0141-42e6-8f04-e5aaab0980b6\",\"firstName\":\"Joshua\",\"lastName\":\"Bloch\"}],\"price\":0,\"published\":\"25-12-2017 13:30:25\",\"pages\":null,\"isbn\":null}"; + + // act + Book book = new ObjectMapper().readerFor(Book.class).readValue(bookJson); + + // assert + SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); + assertThat(from(bookJson).getString("published")).isEqualTo(df.format(book.getPublished())); + + } +} \ No newline at end of file diff --git a/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/deserialization/jsonsetter/JsonSetterTest.java b/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/deserialization/jsonsetter/JsonSetterTest.java new file mode 100644 index 0000000000..3a99c972b6 --- /dev/null +++ b/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/deserialization/jsonsetter/JsonSetterTest.java @@ -0,0 +1,32 @@ +package com.baeldung.jacksonannotation.deserialization.jsonsetter; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.Test; + +import java.io.IOException; + +import static io.restassured.path.json.JsonPath.from; +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Source code github.com/eugenp/tutorials + * + * @author Alex Theedom www.baeldung.com + * @version 1.0 + */ +public class JsonSetterTest { + + @Test + public void whenDeserializingUsingJsonSetter_thenCorrect() throws IOException { + + // arrange + String json = "{\"firstName\":\"Alex\",\"lastName\":\"Theedom\",\"publications\":[{\"title\":\"Professional Java EE Design Patterns\"}]}"; + + // act + Author author = new ObjectMapper().readerFor(Author.class).readValue(json); + + // assert + assertThat(from(json).getList("publications").size()).isEqualTo(author.getItems().size()); + + } +} \ No newline at end of file diff --git a/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/general/jsonfilter/JsonFilterTest.java b/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/general/jsonfilter/JsonFilterTest.java new file mode 100644 index 0000000000..cd18eed6fe --- /dev/null +++ b/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/general/jsonfilter/JsonFilterTest.java @@ -0,0 +1,42 @@ +package com.baeldung.jacksonannotation.general.jsonfilter; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.ser.FilterProvider; +import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter; +import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider; +import org.junit.Test; + +import static io.restassured.path.json.JsonPath.from; +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Source code github.com/eugenp/tutorials + * + * @author Alex Theedom www.baeldung.com + * @version 1.0 + */ +public class JsonFilterTest { + + @Test + public void whenSerializingUsingJsonFilter_thenCorrect() throws JsonProcessingException { + + // arrange + Author author = new Author("Alex", "Theedom"); + FilterProvider filters = new SimpleFilterProvider() + .addFilter("authorFilter", SimpleBeanPropertyFilter.filterOutAllExcept("lastName")); + + // act + String result = new ObjectMapper().writer(filters).writeValueAsString(author); + + // assert + assertThat(from(result).getList("items")).isNull(); + + /* + { + "lastName": "Theedom" + } + */ + + } +} \ No newline at end of file diff --git a/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/general/jsonformat/JsonFormatTest.java b/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/general/jsonformat/JsonFormatTest.java new file mode 100644 index 0000000000..8f35cf0270 --- /dev/null +++ b/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/general/jsonformat/JsonFormatTest.java @@ -0,0 +1,66 @@ +package com.baeldung.jacksonannotation.general.jsonformat; + +import com.baeldung.jacksonannotation.domain.Author; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.Test; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.TimeZone; + +import static io.restassured.path.json.JsonPath.from; +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Source code github.com/eugenp/tutorials + * + * @author Alex Theedom www.baeldung.com + * @version 1.0 + */ +public class JsonFormatTest { + + @Test + public void whenSerializingUsingJsonFormat_thenCorrect() throws JsonProcessingException, ParseException { + + // arrange + SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); + df.setTimeZone(TimeZone.getTimeZone("UTC")); + + String toParse = "20-12-2014 14:30:00"; + Date date = df.parse(toParse); + + Book book = new Book( + "Design Patterns: Elements of Reusable Object-oriented Software", + new Author("The", "GoF") + ); + book.setPublished(date); + + // act + String result = new ObjectMapper().writeValueAsString(book); + + // assert + assertThat(from(result).getString("published")).isEqualTo(toParse); + + /* + { + "id": "762b39be-fd5b-489e-8688-aeb3b9bbf019", + "title": "Design Patterns: Elements of Reusable Object-oriented Software", + "authors": [ + { + "id": "6941b780-0f54-4259-adcb-85523c8f25f4", + "firstName": "The", + "lastName": "GoF", + "items": [] + } + ], + "price": 0, + "published": "20-12-2014 02:30:00", + "pages": null, + "isbn": null + } + */ + + } +} \ No newline at end of file diff --git a/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/general/jsonidentityinfo/JsonIdentityInfoTest.java b/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/general/jsonidentityinfo/JsonIdentityInfoTest.java new file mode 100644 index 0000000000..e3e53ebdbd --- /dev/null +++ b/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/general/jsonidentityinfo/JsonIdentityInfoTest.java @@ -0,0 +1,60 @@ +package com.baeldung.jacksonannotation.general.jsonidentityinfo; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.Test; + +import java.util.Collections; + +import static io.restassured.path.json.JsonPath.from; +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Source code github.com/eugenp/tutorials + * + * @author Alex Theedom www.baeldung.com + * @version 1.0 + */ +public class JsonIdentityInfoTest { + + @Test + public void whenSerializingUsingJsonIdentityInfo_thenCorrect() throws JsonProcessingException { + + // arrange + Author author = new Author("Alex", "Theedom"); + + Course course = new Course("Java EE Introduction", author); + author.setItems(Collections.singletonList(course)); + course.setAuthors(Collections.singletonList(author)); + + // act + String result = new ObjectMapper().writeValueAsString(author); + + // assert + assertThat(from(result).getString("items[0].authors")).isNotNull(); + + /* + Authors are included. + { + "id": "1b408bf9-5946-4a14-a112-fde2953a7fe7", + "firstName": "Alex", + "lastName": "Theedom", + "items": [ + { + "id": "5ed30530-f0a5-42eb-b786-be2c655da968", + "title": "Java EE Introduction", + "authors": [ + "1b408bf9-5946-4a14-a112-fde2953a7fe7" + ], + "price": 0, + "duration": 0, + "medium": null, + "level": null, + "prerequisite": null + } + ] + } + */ + + } +} \ No newline at end of file diff --git a/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/general/jsonproperty/JsonPropertyTest.java b/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/general/jsonproperty/JsonPropertyTest.java new file mode 100644 index 0000000000..a05c3b2294 --- /dev/null +++ b/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/general/jsonproperty/JsonPropertyTest.java @@ -0,0 +1,73 @@ +package com.baeldung.jacksonannotation.general.jsonproperty; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.Test; + +import java.io.IOException; + +import static io.restassured.path.json.JsonPath.from; +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Source code github.com/eugenp/tutorials + * + * @author Alex Theedom www.baeldung.com + * @version 1.0 + */ +public class JsonPropertyTest { + + @Test + public void whenSerializingUsingJsonProperty_thenCorrect() throws JsonProcessingException { + + // arrange + Book book = new Book( + "Design Patterns: Elements of Reusable Object-oriented Software", + new Author("The", "GoF") + ); + book.configureBinding("Hardback"); + + // act + String result = new ObjectMapper().writeValueAsString(book); + + // assert + assertThat(from(result).getString("binding")).isEqualTo("Hardback"); + + /* + { + "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", + "items": [] + } + ], + "price": 0, + "published": null, + "pages": null, + "isbn": null, + "binding": "Hardback" + } + */ + + } + + @Test + public void whenDeserializingUsingJsonProperty_thenCorrect() throws IOException { + + // arrange + String result = "{\"id\":\"cd941587-d1ae-4c2a-9a36-29533bf50411\",\"title\":\"Design Patterns: Elements of Reusable Object-oriented Software\",\"authors\":[{\"id\":\"c8e26318-2f5b-4fa2-9fdc-6e99be021fca\",\"firstName\":\"The\",\"lastName\":\"GoF\"}],\"binding\":\"Hardback\"}"; + + // act + Book book = new ObjectMapper().readerFor(Book.class).readValue(result); + + // assert + assertThat(book.coverBinding()).isEqualTo("Hardback"); + + } + + +} \ No newline at end of file diff --git a/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/general/jsonunwrapped/JsonUnwrappedTest.java b/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/general/jsonunwrapped/JsonUnwrappedTest.java new file mode 100644 index 0000000000..6fff64c64e --- /dev/null +++ b/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/general/jsonunwrapped/JsonUnwrappedTest.java @@ -0,0 +1,44 @@ +package com.baeldung.jacksonannotation.general.jsonunwrapped; + + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.Test; + +import static io.restassured.path.json.JsonPath.from; +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Source code github.com/eugenp/tutorials + * + * @author Alex Theedom www.baeldung.com + * @version 1.0 + */ +public class JsonUnwrappedTest { + + @Test + public void whenSerializingUsingJsonUnwrapped_thenCorrect() throws JsonProcessingException { + + // arrange + Order.Type preorderType = new Order.Type(); + preorderType.id = 10; + preorderType.name = "pre-order"; + + Order order = new Order(preorderType); + + // act + String result = new ObjectMapper().writeValueAsString(order); + + // assert + assertThat(from(result).getInt("id")).isEqualTo(10); + assertThat(from(result).getString("name")).isEqualTo("pre-order"); + + /* + { + "id": 10, + "name": "pre-order" + } + */ + + } +} \ No newline at end of file diff --git a/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/general/jsonview/JsonViewTest.java b/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/general/jsonview/JsonViewTest.java new file mode 100644 index 0000000000..3e06b0f669 --- /dev/null +++ b/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/general/jsonview/JsonViewTest.java @@ -0,0 +1,72 @@ +package com.baeldung.jacksonannotation.general.jsonview; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.Test; + +import static io.restassured.path.json.JsonPath.from; +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Source code github.com/eugenp/tutorials + * + * @author Alex Theedom www.baeldung.com + * @version 1.0 + */ +public class JsonViewTest { + + @Test + public void whenSerializingUsingJsonView_andInternalView_thenCorrect() throws JsonProcessingException { + + // arrange + Order order = new Order(120); + + // act + String result = new ObjectMapper().writerWithView(Views.Internal.class).writeValueAsString(order); + + // assert + assertThat(from(result).getUUID("id")).isNotNull(); + assertThat(from(result).getObject("type", Order.Type.class)).isNotNull(); + assertThat(from(result).getInt("internalAudit")).isEqualTo(120); + + /* + { + "id": "33806388-795b-4812-b90a-60292111bc5c", + "type": { + "id": 20, + "name": "Order" + }, + "internalAudit": 120 + } + */ + + } + + @Test + public void whenSerializingUsingJsonView_andPublicView_thenCorrect() throws JsonProcessingException { + + // arrange + Order order = new Order(120); + + // act + String result = new ObjectMapper().writerWithView(Views.Public.class).writeValueAsString(order); + + // assert + assertThat(from(result).getUUID("id")).isNotNull(); + assertThat(from(result).getObject("type", Order.Type.class)).isNotNull(); + assertThat(result).doesNotContain("internalAudit"); + + /* + { + "id": "5184d5fc-e359-4cdf-93fa-4054025bef4e", + "type": { + "id": 20, + "name": "Order" + } + } + */ + + } + + +} \ No newline at end of file diff --git a/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/general/reference/ReferenceTest.java b/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/general/reference/ReferenceTest.java new file mode 100644 index 0000000000..34b223c98f --- /dev/null +++ b/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/general/reference/ReferenceTest.java @@ -0,0 +1,59 @@ +package com.baeldung.jacksonannotation.general.reference; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.Test; + +import java.util.Collections; + +import static io.restassured.path.json.JsonPath.from; +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Source code github.com/eugenp/tutorials + * + * @author Alex Theedom www.baeldung.com + * @version 1.0 + */ +public class ReferenceTest { + + @Test + public void whenSerializingUsingReference_thenCorrect() throws JsonProcessingException { + + // arrange + Author author = new Author("Alex", "Theedom"); + + Course course = new Course("Java EE Introduction", author); + author.setItems(Collections.singletonList(course)); + course.setAuthors(Collections.singletonList(author)); + + // act + String result = new ObjectMapper().writeValueAsString(author); + + // assert + assertThat(from(result).getString("items[0].authors")).isNull(); + + /* + Without references defined it throws StackOverflowError. + Authors excluded. + + { + "id": "9c45d9b3-4888-4c24-8b74-65ef35627cd7", + "firstName": "Alex", + "lastName": "Theedom", + "items": [ + { + "id": "f8309629-d178-4d67-93a4-b513ec4a7f47", + "title": "Java EE Introduction", + "price": 0, + "duration": 0, + "medium": null, + "level": null, + "prerequisite": null + } + ] + } + */ + + } +} \ No newline at end of file diff --git a/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/inclusion/jsonautodetect/JsonAutoDetectTest.java b/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/inclusion/jsonautodetect/JsonAutoDetectTest.java new file mode 100644 index 0000000000..87d3e7ddbf --- /dev/null +++ b/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/inclusion/jsonautodetect/JsonAutoDetectTest.java @@ -0,0 +1,52 @@ +package com.baeldung.jacksonannotation.inclusion.jsonautodetect; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.Test; + +import static io.restassured.path.json.JsonPath.from; +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Source code github.com/eugenp/tutorials + * + * @author Alex Theedom www.baeldung.com + * @version 1.0 + */ +public class JsonAutoDetectTest { + + @Test + public void whenSerializingUsingJsonAutoDetect_thenCorrect() throws JsonProcessingException { + + // arrange + Order order = new Order(1234567890); + + // act + String result = new ObjectMapper().writeValueAsString(order); + + // assert + assertThat(from(result).getInt("internalAudit")).isEqualTo(1234567890); + + /* + With @JsonAutoDetect + { + "id": "c94774d9-de8f-4244-85d5-624bd3a4567a", + "type": { + "id": 20, + "name": "Order" + }, + "internalAudit": 1234567890 + } + + Without @JsonAutoDetect + { + "id": "c94774d9-de8f-4244-85d5-624bd3a4567a", + "type": { + "id": 20, + "name": "Order" + } + } + */ + + } +} \ No newline at end of file diff --git a/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/inclusion/jsonignore/JsonIgnoreTest.java b/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/inclusion/jsonignore/JsonIgnoreTest.java new file mode 100644 index 0000000000..eeff2069b6 --- /dev/null +++ b/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/inclusion/jsonignore/JsonIgnoreTest.java @@ -0,0 +1,41 @@ +package com.baeldung.jacksonannotation.inclusion.jsonignore; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.Test; + +import static io.restassured.path.json.JsonPath.from; +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Source code github.com/eugenp/tutorials + * + * @author Alex Theedom www.baeldung.com + * @version 1.0 + */ +public class JsonIgnoreTest { + + @Test + public void whenSerializingUsingJsonIgnore_thenCorrect() throws JsonProcessingException { + + // arrange + Author author = new Author("Alex", "Theedom"); + + // act + String result = new ObjectMapper().writeValueAsString(author); + + // assert + assertThat(from(result).getString("firstName")).isEqualTo("Alex"); + assertThat(from(result).getString("lastName")).isEqualTo("Theedom"); + assertThat(from(result).getString("id")).isNull(); + + /* + { + "firstName": "Alex", + "lastName": "Theedom", + "items": [] + } + */ + + } +} \ No newline at end of file diff --git a/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/inclusion/jsonignoreproperties/JsonIgnorePropertiesTest.java b/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/inclusion/jsonignoreproperties/JsonIgnorePropertiesTest.java new file mode 100644 index 0000000000..f0e6f1b684 --- /dev/null +++ b/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/inclusion/jsonignoreproperties/JsonIgnorePropertiesTest.java @@ -0,0 +1,52 @@ +package com.baeldung.jacksonannotation.inclusion.jsonignoreproperties; + +import com.baeldung.jacksonannotation.domain.Author; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.Test; + +import static io.restassured.path.json.JsonPath.from; +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Source code github.com/eugenp/tutorials + * + * @author Alex Theedom www.baeldung.com + * @version 1.0 + */ +public class JsonIgnorePropertiesTest { + + @Test + public void whenSerializingUsingJsonIgnoreProperties_thenCorrect() throws JsonProcessingException { + + // arrange + Course course = new Course("Spring Security", new Author("Eugen", "Paraschiv")); + course.setMedium(Course.Medium.ONLINE); + + // act + String result = new ObjectMapper().writeValueAsString(course); + + // assert + assertThat(from(result).getString("medium")).isNull(); + + /* + { + "id": "ef0c8d2b-b088-409e-905c-95ac88dc0ed0", + "title": "Spring Security", + "authors": [ + { + "id": "47a4f498-b0f3-4daf-909f-d2c35a0fe3c2", + "firstName": "Eugen", + "lastName": "Paraschiv", + "items": [] + } + ], + "price": 0, + "duration": 0, + "level": null, + "prerequisite": null + } + */ + + } +} \ No newline at end of file diff --git a/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/inclusion/jsonignoretype/JsonIgnoreTypeTest.java b/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/inclusion/jsonignoretype/JsonIgnoreTypeTest.java new file mode 100644 index 0000000000..dbb12b46d5 --- /dev/null +++ b/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/inclusion/jsonignoretype/JsonIgnoreTypeTest.java @@ -0,0 +1,40 @@ +package com.baeldung.jacksonannotation.inclusion.jsonignoretype; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.Test; + +import static io.restassured.path.json.JsonPath.from; +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Source code github.com/eugenp/tutorials + * + * @author Alex Theedom www.baeldung.com + * @version 1.0 + */ +public class JsonIgnoreTypeTest { + + @Test + public void whenSerializingUsingJsonIgnoreType_thenCorrect() throws JsonProcessingException { + + // arrange + Order.Type type = new Order.Type(); + type.id = 10; + type.name = "Pre-order"; + + Order order = new Order(type); + + // act + String result = new ObjectMapper().writeValueAsString(order); + + // assert + assertThat(from(result).getString("id")).isNotNull(); + assertThat(from(result).getString("type")).isNull(); + + /* + {"id":"ac2428da-523e-443c-a18a-4ea4d2791fea"} + */ + + } +} \ No newline at end of file diff --git a/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/inclusion/jsoninclude/JsonIncludeTest.java b/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/inclusion/jsoninclude/JsonIncludeTest.java new file mode 100644 index 0000000000..7d24d006e8 --- /dev/null +++ b/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/inclusion/jsoninclude/JsonIncludeTest.java @@ -0,0 +1,41 @@ +package com.baeldung.jacksonannotation.inclusion.jsoninclude; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.Test; + +import static io.restassured.path.json.JsonPath.from; +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Source code github.com/eugenp/tutorials + * + * @author Alex Theedom www.baeldung.com + * @version 1.0 + */ +public class JsonIncludeTest { + + @Test + public void whenSerializingUsingJsonInclude_thenCorrect() throws JsonProcessingException { + + // arrange + Author author = new Author("Alex", null); + + // act + String result = new ObjectMapper().writeValueAsString(author); + + // assert + assertThat(from(result).getString("firstName")).isEqualTo("Alex"); + assertThat(result).doesNotContain("lastName"); + + + /* + { + "id": "e8bb4802-6e0c-4fa5-9f68-c233272399cd", + "firstName": "Alex", + "items": [] + } + */ + + } +} \ No newline at end of file diff --git a/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/miscellaneous/custom/CustomTest.java b/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/miscellaneous/custom/CustomTest.java new file mode 100644 index 0000000000..aa885d6804 --- /dev/null +++ b/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/miscellaneous/custom/CustomTest.java @@ -0,0 +1,51 @@ +package com.baeldung.jacksonannotation.miscellaneous.custom; + +import com.baeldung.jacksonannotation.domain.Author; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.Test; + +import static io.restassured.path.json.JsonPath.from; +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Source code github.com/eugenp/tutorials + * + * @author Alex Theedom www.baeldung.com + * @version 1.0 + */ +public class CustomTest { + + @Test + public void whenSerializingUsingCustom_thenCorrect() throws JsonProcessingException { + + // arrange + Course course = new Course("Spring Security", new Author("Eugen", "Paraschiv")); + course.setMedium(Course.Medium.ONLINE); + + // act + String result = new ObjectMapper().writeValueAsString(course); + + // assert + assertThat(from(result).getString("title")).isEqualTo("Spring Security"); + + /* + { + "title": "Spring Security", + "price": 0, + "id": "7dfd4db9-1175-432f-a53b-687423f7bb9b", + "duration": 0, + "authors": [ + { + "id": "da0738f6-033c-4974-8d87-92820e5ccf27", + "firstName": "Eugen", + "lastName": "Paraschiv", + "items": [] + } + ], + "medium": "ONLINE" + } + */ + + } +} \ No newline at end of file diff --git a/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/miscellaneous/disable/DisableTest.java b/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/miscellaneous/disable/DisableTest.java new file mode 100644 index 0000000000..b66adea8c8 --- /dev/null +++ b/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/miscellaneous/disable/DisableTest.java @@ -0,0 +1,58 @@ +package com.baeldung.jacksonannotation.miscellaneous.disable; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.MapperFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.Test; + +import static io.restassured.path.json.JsonPath.from; +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Source code github.com/eugenp/tutorials + * + * @author Alex Theedom www.baeldung.com + * @version 1.0 + */ +public class DisableTest { + + @Test + public void whenSerializingUsingDisable_thenCorrect() throws JsonProcessingException { + + // arrange + Author author = new Author("Alex", "Theedom"); + + // act + ObjectMapper mapper = new ObjectMapper(); + String result = mapper.writeValueAsString(author); + + // assert + assertThat(from(result).getList("items")).isNull(); + + /* + { + "lastName": "Theedom", + "firstName": "Alex", + "id": "de4afbb4-b24d-45c8-bb00-fd6b9acb42f1" + } + */ + + // act + mapper = new ObjectMapper(); + mapper.disable(MapperFeature.USE_ANNOTATIONS); + result = mapper.writeValueAsString(author); + + // assert + assertThat(from(result).getList("items")).isNotNull(); + + /* + { + "id": "81e6ed72-6b27-4fe9-a36f-e3171c5b55ef", + "firstName": "Alex", + "lastName": "Theedom", + "items": [] + } + */ + + } +} \ No newline at end of file diff --git a/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/miscellaneous/mixin/MixInTest.java b/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/miscellaneous/mixin/MixInTest.java new file mode 100644 index 0000000000..7c021e5a4f --- /dev/null +++ b/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/miscellaneous/mixin/MixInTest.java @@ -0,0 +1,58 @@ +package com.baeldung.jacksonannotation.miscellaneous.mixin; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.Test; + +import java.util.List; + +import static io.restassured.path.json.JsonPath.from; +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Source code github.com/eugenp/tutorials + * + * @author Alex Theedom www.baeldung.com + * @version 1.0 + */ +public class MixInTest { + + @Test + public void whenSerializingUsingMixIn_thenCorrect() throws JsonProcessingException { + + // arrange + Author author = new Author("Alex", "Theedom"); + + // act + String result = new ObjectMapper().writeValueAsString(author); + + // assert + assertThat(from(result).getList("items")).isNotNull(); + + /* + { + "id": "f848b076-00a4-444a-a50b-328595dd9bf5", + "firstName": "Alex", + "lastName": "Theedom", + "items": [] + } + */ + + ObjectMapper mapper = new ObjectMapper(); + mapper.addMixIn(List.class, IgnoreListMixIn.class); + + result = mapper.writeValueAsString(author); + + // assert + assertThat(from(result).getList("items")).isNull(); + + /* + { + "id": "9ffefb7d-e56f-447c-9009-e92e142f8347", + "firstName": "Alex", + "lastName": "Theedom" + } + */ + + } +} \ No newline at end of file diff --git a/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/polymorphism/PolymorphismTest.java b/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/polymorphism/PolymorphismTest.java new file mode 100644 index 0000000000..702c39eb11 --- /dev/null +++ b/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/polymorphism/PolymorphismTest.java @@ -0,0 +1,64 @@ +package com.baeldung.jacksonannotation.polymorphism; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.Test; + +import java.io.IOException; + +import static io.restassured.path.json.JsonPath.from; +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Source code github.com/eugenp/tutorials + * + * @author Alex Theedom www.baeldung.com + * @version 1.0 + */ +public class PolymorphismTest { + + @Test + public void whenSerializingUsingPolymorphism_thenCorrect() throws JsonProcessingException { + + // arrange + Order.InternalType internalType = new Order.InternalType(); + internalType.id = 250; + internalType.name = "staff"; + + Order order = new Order(internalType); + + // act + String result = new ObjectMapper().writeValueAsString(order); + + // assert + assertThat(from(result).getString("type.ordertype")).isEqualTo("internal"); + + /* + { + "id": "7fc898e3-b4e7-41b0-8ffa-664cf3663f2e", + "type": { + "ordertype": "internal", + "id": 250, + "name": "staff" + } + } + */ + + } + + @Test + public void whenDeserializingPolymorphic_thenCorrect() throws IOException { + + // arrange + String orderJson = "{\"type\":{\"ordertype\":\"internal\",\"id\":100,\"name\":\"directors\"}}"; + + // act + Order order = new ObjectMapper().readerFor(Order.class).readValue(orderJson); + + // assert + assertThat(from(orderJson).getString("type.ordertype")).isEqualTo("internal"); + assertThat(((Order.InternalType) order.getType()).name).isEqualTo("directors"); + assertThat(((Order.InternalType) order.getType()).id).isEqualTo(100); + assertThat(order.getType().getClass()).isEqualTo(Order.InternalType.class); + } +} \ No newline at end of file diff --git a/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/serialization/jsonanygetter/JsonAnyGetterTest.java b/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/serialization/jsonanygetter/JsonAnyGetterTest.java new file mode 100644 index 0000000000..efbc271b2a --- /dev/null +++ b/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/serialization/jsonanygetter/JsonAnyGetterTest.java @@ -0,0 +1,49 @@ +package com.baeldung.jacksonannotation.serialization.jsonanygetter; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.Test; + +import java.util.Map; + +import static io.restassured.path.json.JsonPath.from; +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Source code github.com/eugenp/tutorials + * + * @author Alex Theedom www.baeldung.com + * @version 1.0 + */ +public class JsonAnyGetterTest { + + @Test + public void whenSerializingUsingJsonAnyGetter_thenCorrect() throws JsonProcessingException { + + // arrange + Inventory inventory = new Inventory(); + Map countryDeliveryCost = inventory.getCountryDeliveryCost(); + inventory.setLocation("France"); + + countryDeliveryCost.put("USA", 10.00f); + countryDeliveryCost.put("UK", 15.00f); + + // act + String result = new ObjectMapper().writeValueAsString(inventory); + + // assert + assertThat(from(result).getString("location")).isEqualTo("France"); + assertThat(from(result).getFloat("USA")).isEqualTo(10.00f); + assertThat(from(result).getFloat("UK")).isEqualTo(15.00f); + + /* + { + "location": "France", + "USA": 10, + "UK": 15 + } + */ + + } + +} diff --git a/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/serialization/jsongetter/JsonGetterTest.java b/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/serialization/jsongetter/JsonGetterTest.java new file mode 100644 index 0000000000..2aa97e0baf --- /dev/null +++ b/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/serialization/jsongetter/JsonGetterTest.java @@ -0,0 +1,40 @@ +package com.baeldung.jacksonannotation.serialization.jsongetter; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.Test; + +import static io.restassured.path.json.JsonPath.from; +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Source code github.com/eugenp/tutorials + * + * @author Alex Theedom www.baeldung.com + * @version 1.0 + */ +public class JsonGetterTest { + + @Test + public void whenSerializingUsingJsonGetter_thenCorrect() throws JsonProcessingException { + + // arrange + Author author = new Author("Alex", "Theedom"); + + // act + String result = new ObjectMapper().writeValueAsString(author); + + // assert + assertThat(from(result).getList("publications")).isNotNull(); + assertThat(from(result).getList("items")).isNull(); + + /* + { + "firstName": "Alex", + "lastName": "Theedom", + "publications": [] + } + */ + + } +} diff --git a/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/serialization/jsonpropertyorder/JsonPropertyOrderTest.java b/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/serialization/jsonpropertyorder/JsonPropertyOrderTest.java new file mode 100644 index 0000000000..cfd0f5a28b --- /dev/null +++ b/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/serialization/jsonpropertyorder/JsonPropertyOrderTest.java @@ -0,0 +1,46 @@ +package com.baeldung.jacksonannotation.serialization.jsonpropertyorder; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.Test; + +import static io.restassured.module.jsv.JsonSchemaValidator.matchesJsonSchemaInClasspath; +import static org.hamcrest.MatcherAssert.assertThat; + +/** + * Source code github.com/eugenp/tutorials + * + * @author Alex Theedom www.baeldung.com + * @version 1.0 + */ +public class JsonPropertyOrderTest { + + @Test + public void whenSerializingUsingJsonPropertyOrder_thenCorrect() throws JsonProcessingException { + + // arrange + Author author = new Author("Alex", "Theedom"); + author.setzIndex("z123"); + author.setAlphaIndex("z123"); + + // act + String result = new ObjectMapper().writeValueAsString(author); + + // assert + assertThat(result, matchesJsonSchemaInClasspath("author-jsonpropertyorder-schema.json")); + + // NOTE: property order is not enforced by the JSON specification. + + /* + { + "items": [], + "firstName": "Alex", + "lastName": "Theedom", + "id": "31ca2af9-df0a-4d49-a74c-86c0a3f944a2", + "alphaIndex": "z123", + "zIndex": "z123" + } + */ + + } +} diff --git a/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/serialization/jsonrawvalue/JsonRawValueTest.java b/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/serialization/jsonrawvalue/JsonRawValueTest.java new file mode 100644 index 0000000000..9d15be149a --- /dev/null +++ b/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/serialization/jsonrawvalue/JsonRawValueTest.java @@ -0,0 +1,46 @@ +package com.baeldung.jacksonannotation.serialization.jsonrawvalue; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Source code github.com/eugenp/tutorials + * + * @author Alex Theedom www.baeldung.com + * @version 1.0 + */ +public class JsonRawValueTest { + + @Test + public void whenSerializingUsingJsonRawValue_thenCorrect() throws JsonProcessingException { + + // arrange + String customerConfig = "{\"colour\":\"red\",\"device\":\"mobile\",\"orientation\":\"landscape\"}"; + Customer customer = new Customer("Alex", "Theedom"); + customer.setConfiguration("{\"colour\":\"red\",\"device\":\"mobile\",\"orientation\":\"landscape\"}"); + + // act + String result = new ObjectMapper().writeValueAsString(customer); + + // assert + assertThat(result.contains(customerConfig)); + + + /* + { + "id": "7674fbec-527f-4008-a619-f9967cd0cbe0", + "firstName": "Alex", + "lastName": "Theedom", + "configuration": { + "colour": "red", + "device": "mobile", + "orientation": "landscape" + } + } + */ + + } +} diff --git a/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/serialization/jsonrootname/JsonRootNameTest.java b/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/serialization/jsonrootname/JsonRootNameTest.java new file mode 100644 index 0000000000..6d63d28eaf --- /dev/null +++ b/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/serialization/jsonrootname/JsonRootNameTest.java @@ -0,0 +1,46 @@ +package com.baeldung.jacksonannotation.serialization.jsonrootname; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import org.junit.Test; + +import static io.restassured.path.json.JsonPath.from; +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Source code github.com/eugenp/tutorials + * + * @author Alex Theedom www.baeldung.com + * @version 1.0 + */ +public class JsonRootNameTest { + + @Test + public void whenSerializingUsingJsonRootName_thenCorrect() throws JsonProcessingException { + + // arrange + Author author = new Author("Alex", "Theedom"); + + // act + ObjectMapper mapper = new ObjectMapper(); + mapper.enable(SerializationFeature.WRAP_ROOT_VALUE); + String result = mapper.writeValueAsString(author); + + // assert + assertThat(from(result).getString("writer.firstName")).isEqualTo("Alex"); + assertThat(from(result).getString("author.firstName")).isNull(); + + /* + { + "writer": { + "id": "0f50dca6-3dd7-4801-a334-fd1614276389", + "firstName": "Alex", + "lastName": "Theedom", + "items": [] + } + } + */ + + } +} diff --git a/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/serialization/jsonserialize/JsonSerializeTest.java b/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/serialization/jsonserialize/JsonSerializeTest.java new file mode 100644 index 0000000000..4b15f1f459 --- /dev/null +++ b/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/serialization/jsonserialize/JsonSerializeTest.java @@ -0,0 +1,58 @@ +package com.baeldung.jacksonannotation.serialization.jsonserialize; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.Test; + +import java.text.ParseException; +import java.text.SimpleDateFormat; + +import static io.restassured.path.json.JsonPath.from; +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Source code github.com/eugenp/tutorials + * + * @author Alex Theedom www.baeldung.com + * @version 1.0 + */ +public class JsonSerializeTest { + + @Test + public void whenSerializingUsingJsonSerialize_thenCorrect() throws JsonProcessingException, ParseException { + + // arrange + Author joshuaBloch = new Author("Joshua", "Bloch"); + Book book = new Book("Effective Java", joshuaBloch); + + SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); + String toParse = "25-12-2017 13:30:25"; + book.setPublished(df.parse(toParse)); + + // act + String result = new ObjectMapper().writeValueAsString(book); + + // assert + assertThat(from(result).getString("published")).isEqualTo(toParse); + + /* + { + "id": "957c43f2-fa2e-42f9-bf75-6e3d5bb6960a", + "title": "Effective Java", + "authors": [ + { + "id": "9bcd817d-0141-42e6-8f04-e5aaab0980b6", + "firstName": "Joshua", + "lastName": "Bloch", + "items": [] + } + ], + "price": 0, + "published": "25-12-2017 13:30:25", + "pages": null, + "isbn": null + } + */ + + } +} diff --git a/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/serialization/jsonvalue/JsonValueTest.java b/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/serialization/jsonvalue/JsonValueTest.java new file mode 100644 index 0000000000..91541f60f2 --- /dev/null +++ b/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/serialization/jsonvalue/JsonValueTest.java @@ -0,0 +1,54 @@ +package com.baeldung.jacksonannotation.serialization.jsonvalue; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Source code github.com/eugenp/tutorials + * + * @author Alex Theedom www.baeldung.com + * @version 1.0 + */ +public class JsonValueTest { + + @Test + public void whenSerializingUsingJsonValue_thenCorrect() throws JsonProcessingException { + + // act + String result = new ObjectMapper().writeValueAsString(Course.Level.ADVANCED); + + // assert + assertThat(result).isEqualTo("\"Advanced\""); + + /* + + "Advanced" + + */ + + } + + @Test + public void whenSerializingAuthorUsingJsonValue_thenFirstNameAndLastNameAreConcatenated() throws JsonProcessingException { + + // arrange + Author me = new Author("Alex", "Theedom"); + + // act + String result = new ObjectMapper().writeValueAsString(me); + + // assert + assertThat(result).contains("Alex Theedom"); + + /* + { + "name": "Alex Theedom" + } + + */ + + } +} \ No newline at end of file diff --git a/video-tutorials/jackson-annotations/src/test/resources/author-jsonpropertyorder-schema.json b/video-tutorials/jackson-annotations/src/test/resources/author-jsonpropertyorder-schema.json new file mode 100644 index 0000000000..14d596e47f --- /dev/null +++ b/video-tutorials/jackson-annotations/src/test/resources/author-jsonpropertyorder-schema.json @@ -0,0 +1,37 @@ +{ + "$schema": "http://json-schema.org/draft-04/schema#", + "title": "Author", + "description": "An author", + "type": "object", + "properties": { + "items": { + "type": "array", + "items": { + "type": "object" + } + }, + "firstName": { + "type": "string" + }, + "lastName": { + "type": "string" + }, + "id": { + "type": "string" + }, + "zIndex": { + "type": "string" + }, + "alphaIndex": { + "type": "string" + } + }, + "required": [ + "items", + "firstName", + "lastName", + "id", + "alphaIndex", + "zIndex" + ] +} \ No newline at end of file diff --git a/video-tutorials/pom.xml b/video-tutorials/pom.xml new file mode 100644 index 0000000000..0ddbad2407 --- /dev/null +++ b/video-tutorials/pom.xml @@ -0,0 +1,16 @@ + + 4.0.0 + com.baeldung + video-tutorials + 1.0.0-SNAPSHOT + + pom + video-tutorials + + jackson-annotations + + + + +