diff --git a/algorithms-miscellaneous-1/README.md b/algorithms-miscellaneous-1/README.md index 59765588b0..6f18396005 100644 --- a/algorithms-miscellaneous-1/README.md +++ b/algorithms-miscellaneous-1/README.md @@ -14,3 +14,4 @@ - [Calculate Factorial in Java](https://www.baeldung.com/java-calculate-factorial) - [Find Substrings That Are Palindromes in Java](https://www.baeldung.com/java-palindrome-substrings) - [Find the Longest Substring without Repeating Characters](https://www.baeldung.com/java-longest-substring-without-repeated-characters) +- [Java Two Pointer Technique](https://www.baeldung.com/java-two-pointer-technique) diff --git a/apache-spark/src/main/java/com/baeldung/data/pipeline/WordCountingApp.java b/apache-spark/src/main/java/com/baeldung/data/pipeline/WordCountingApp.java index 08695b3631..db2a73b411 100644 --- a/apache-spark/src/main/java/com/baeldung/data/pipeline/WordCountingApp.java +++ b/apache-spark/src/main/java/com/baeldung/data/pipeline/WordCountingApp.java @@ -6,7 +6,6 @@ import static com.datastax.spark.connector.japi.CassandraJavaUtil.mapToRow; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; -import java.util.Iterator; import java.util.List; import java.util.Map; @@ -15,13 +14,7 @@ import org.apache.kafka.common.serialization.StringDeserializer; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.spark.SparkConf; -import org.apache.spark.api.java.JavaPairRDD; import org.apache.spark.api.java.JavaRDD; -import org.apache.spark.api.java.function.FlatMapFunction; -import org.apache.spark.api.java.function.Function; -import org.apache.spark.api.java.function.Function2; -import org.apache.spark.api.java.function.PairFunction; -import org.apache.spark.api.java.function.VoidFunction; import org.apache.spark.streaming.Durations; import org.apache.spark.streaming.api.java.JavaDStream; import org.apache.spark.streaming.api.java.JavaInputDStream; @@ -35,7 +28,6 @@ import scala.Tuple2; public class WordCountingApp { - @SuppressWarnings("serial") public static void main(String[] args) throws InterruptedException { Logger.getLogger("org") .setLevel(Level.OFF); @@ -61,52 +53,24 @@ public class WordCountingApp { JavaInputDStream> messages = KafkaUtils.createDirectStream(streamingContext, LocationStrategies.PreferConsistent(), ConsumerStrategies. Subscribe(topics, kafkaParams)); - JavaPairDStream results = messages.mapToPair(new PairFunction, String, String>() { - @Override - public Tuple2 call(ConsumerRecord record) { - return new Tuple2<>(record.key(), record.value()); - } - }); + JavaPairDStream results = messages.mapToPair(record -> new Tuple2<>(record.key(), record.value())); - JavaDStream lines = results.map(new Function, String>() { - @Override - public String call(Tuple2 tuple2) { - return tuple2._2(); - } - }); + JavaDStream lines = results.map(tuple2 -> tuple2._2()); - JavaDStream words = lines.flatMap(new FlatMapFunction() { - @Override - public Iterator call(String x) { - return Arrays.asList(x.split("\\s+")) - .iterator(); - } - }); + JavaDStream words = lines.flatMap(x -> Arrays.asList(x.split("\\s+")) + .iterator()); - JavaPairDStream wordCounts = words.mapToPair(new PairFunction() { - @Override - public Tuple2 call(String s) { - return new Tuple2<>(s, 1); - } - }) - .reduceByKey(new Function2() { - @Override - public Integer call(Integer i1, Integer i2) { - return i1 + i2; - } - }); + JavaPairDStream wordCounts = words.mapToPair(s -> new Tuple2<>(s, 1)) + .reduceByKey((i1, i2) -> i1 + i2); - wordCounts.foreachRDD(new VoidFunction>() { - @Override - public void call(JavaPairRDD javaRdd) throws Exception { - Map wordCountMap = javaRdd.collectAsMap(); - for (String key : wordCountMap.keySet()) { - List words = Arrays.asList(new Word(key, wordCountMap.get(key))); - JavaRDD rdd = streamingContext.sparkContext() - .parallelize(words); - javaFunctions(rdd).writerBuilder("vocabulary", "words", mapToRow(Word.class)) - .saveToCassandra(); - } + wordCounts.foreachRDD(javaRdd -> { + Map wordCountMap = javaRdd.collectAsMap(); + for (String key : wordCountMap.keySet()) { + List wordList = Arrays.asList(new Word(key, wordCountMap.get(key))); + JavaRDD rdd = streamingContext.sparkContext() + .parallelize(wordList); + javaFunctions(rdd).writerBuilder("vocabulary", "words", mapToRow(Word.class)) + .saveToCassandra(); } }); diff --git a/apache-spark/src/main/java/com/baeldung/data/pipeline/WordCountingAppWithCheckpoint.java b/apache-spark/src/main/java/com/baeldung/data/pipeline/WordCountingAppWithCheckpoint.java index e20b910635..efbe5f3851 100644 --- a/apache-spark/src/main/java/com/baeldung/data/pipeline/WordCountingAppWithCheckpoint.java +++ b/apache-spark/src/main/java/com/baeldung/data/pipeline/WordCountingAppWithCheckpoint.java @@ -6,7 +6,6 @@ import static com.datastax.spark.connector.japi.CassandraJavaUtil.mapToRow; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; -import java.util.Iterator; import java.util.List; import java.util.Map; @@ -15,18 +14,10 @@ import org.apache.kafka.common.serialization.StringDeserializer; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.spark.SparkConf; -import org.apache.spark.api.java.JavaPairRDD; import org.apache.spark.api.java.JavaRDD; import org.apache.spark.api.java.JavaSparkContext; -import org.apache.spark.api.java.Optional; -import org.apache.spark.api.java.function.FlatMapFunction; -import org.apache.spark.api.java.function.Function; import org.apache.spark.api.java.function.Function2; -import org.apache.spark.api.java.function.Function3; -import org.apache.spark.api.java.function.PairFunction; -import org.apache.spark.api.java.function.VoidFunction; import org.apache.spark.streaming.Durations; -import org.apache.spark.streaming.State; import org.apache.spark.streaming.StateSpec; import org.apache.spark.streaming.api.java.JavaDStream; import org.apache.spark.streaming.api.java.JavaInputDStream; @@ -43,7 +34,6 @@ public class WordCountingAppWithCheckpoint { public static JavaSparkContext sparkContext; - @SuppressWarnings("serial") public static void main(String[] args) throws InterruptedException { Logger.getLogger("org") @@ -74,63 +64,30 @@ public class WordCountingAppWithCheckpoint { JavaInputDStream> messages = KafkaUtils.createDirectStream(streamingContext, LocationStrategies.PreferConsistent(), ConsumerStrategies. Subscribe(topics, kafkaParams)); - JavaPairDStream results = messages.mapToPair(new PairFunction, String, String>() { - @Override - public Tuple2 call(ConsumerRecord record) { - return new Tuple2<>(record.key(), record.value()); - } - }); + JavaPairDStream results = messages.mapToPair(record -> new Tuple2<>(record.key(), record.value())); - JavaDStream lines = results.map(new Function, String>() { - @Override - public String call(Tuple2 tuple2) { - return tuple2._2(); - } - }); + JavaDStream lines = results.map(tuple2 -> tuple2._2()); - JavaDStream words = lines.flatMap(new FlatMapFunction() { - @Override - public Iterator call(String x) { - return Arrays.asList(x.split("\\s+")) - .iterator(); - } - }); + JavaDStream words = lines.flatMap(x -> Arrays.asList(x.split("\\s+")) + .iterator()); - JavaPairDStream wordCounts = words.mapToPair(new PairFunction() { - @Override - public Tuple2 call(String s) { - return new Tuple2<>(s, 1); - } - }) - .reduceByKey(new Function2() { - @Override - public Integer call(Integer i1, Integer i2) { - return i1 + i2; - } - }); + JavaPairDStream wordCounts = words.mapToPair(s -> new Tuple2<>(s, 1)) + .reduceByKey((Function2) (i1, i2) -> i1 + i2); - Function3, State, Tuple2> mappingFunc = (word, one, state) -> { + JavaMapWithStateDStream> cumulativeWordCounts = wordCounts.mapWithState(StateSpec.function((word, one, state) -> { int sum = one.orElse(0) + (state.exists() ? state.get() : 0); Tuple2 output = new Tuple2<>(word, sum); state.update(sum); return output; - }; + })); - JavaPairRDD initialRDD = JavaPairRDD.fromJavaRDD(sparkContext.emptyRDD()); - - JavaMapWithStateDStream> cumulativeWordCounts = wordCounts.mapWithState(StateSpec.function(mappingFunc) - .initialState(initialRDD)); - - cumulativeWordCounts.foreachRDD(new VoidFunction>>() { - @Override - public void call(JavaRDD> javaRdd) throws Exception { - List> wordCountList = javaRdd.collect(); - for (Tuple2 tuple : wordCountList) { - List words = Arrays.asList(new Word(tuple._1, tuple._2)); - JavaRDD rdd = sparkContext.parallelize(words); - javaFunctions(rdd).writerBuilder("vocabulary", "words", mapToRow(Word.class)) - .saveToCassandra(); - } + cumulativeWordCounts.foreachRDD(javaRdd -> { + List> wordCountList = javaRdd.collect(); + for (Tuple2 tuple : wordCountList) { + List wordList = Arrays.asList(new Word(tuple._1, tuple._2)); + JavaRDD rdd = sparkContext.parallelize(wordList); + javaFunctions(rdd).writerBuilder("vocabulary", "words", mapToRow(Word.class)) + .saveToCassandra(); } }); diff --git a/core-java-8/src/test/java/com/baeldung/time/InstantUnitTest.java b/core-java-8/src/test/java/com/baeldung/time/InstantUnitTest.java new file mode 100644 index 0000000000..8400748710 --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/time/InstantUnitTest.java @@ -0,0 +1,42 @@ +package com.baeldung.time; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneId; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; +import static org.powermock.api.mockito.PowerMockito.mockStatic; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ Instant.class }) +public class InstantUnitTest { + + @Test + public void givenInstantMock_whenNow_thenGetFixedInstant() { + String instantExpected = "2014-12-22T10:15:30Z"; + Clock clock = Clock.fixed(Instant.parse(instantExpected), ZoneId.of("UTC")); + Instant instant = Instant.now(clock); + mockStatic(Instant.class); + when(Instant.now()).thenReturn(instant); + + Instant now = Instant.now(); + + assertThat(now.toString()).isEqualTo(instantExpected); + } + + @Test + public void givenFixedClock_whenNow_thenGetFixedInstant() { + String instantExpected = "2014-12-22T10:15:30Z"; + Clock clock = Clock.fixed(Instant.parse(instantExpected), ZoneId.of("UTC")); + + Instant instant = Instant.now(clock); + + assertThat(instant.toString()).isEqualTo(instantExpected); + } +} diff --git a/core-java-8/src/test/java/com/baeldung/time/InstantWithJMockUnitTest.java b/core-java-8/src/test/java/com/baeldung/time/InstantWithJMockUnitTest.java new file mode 100644 index 0000000000..8f83b91101 --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/time/InstantWithJMockUnitTest.java @@ -0,0 +1,47 @@ +package com.baeldung.time; + +import mockit.Expectations; +import mockit.Mock; +import mockit.MockUp; +import org.junit.jupiter.api.Test; + +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneId; + +import static org.assertj.core.api.Assertions.assertThat; + +public class InstantWithJMockUnitTest { + + @Test + public void givenInstantWithJMock_whenNow_thenGetFixedInstant() { + String instantExpected = "2014-12-21T10:15:30Z"; + Clock clock = Clock.fixed(Instant.parse(instantExpected), ZoneId.of("UTC")); + new MockUp() { + @Mock + public Instant now() { + return Instant.now(clock); + } + }; + + Instant now = Instant.now(); + + assertThat(now.toString()).isEqualTo(instantExpected); + } + + @Test + public void givenInstantWithExpectations_whenNow_thenGetFixedInstant() { + Clock clock = Clock.fixed(Instant.parse("2014-12-23T10:15:30.00Z"), ZoneId.of("UTC")); + Instant instantExpected = Instant.now(clock); + new Expectations(Instant.class) { + { + Instant.now(); + result = instantExpected; + } + }; + + Instant now = Instant.now(); + + assertThat(now).isEqualTo(instantExpected); + } +} diff --git a/core-java-collections/src/main/java/com/baeldung/java/list/VectorExample.java b/core-java-collections/src/main/java/com/baeldung/java/list/VectorExample.java new file mode 100644 index 0000000000..7debc07911 --- /dev/null +++ b/core-java-collections/src/main/java/com/baeldung/java/list/VectorExample.java @@ -0,0 +1,27 @@ +package com.baeldung.java.list; + +import java.util.Enumeration; +import java.util.Iterator; +import java.util.Vector; + +public class VectorExample { + + public static void main(String[] args) { + + Vector vector = new Vector<>(); + vector.add("baeldung"); + vector.add("Vector"); + vector.add("example"); + + Enumeration e = vector.elements(); + while(e.hasMoreElements()){ + System.out.println(e.nextElement()); + } + + Iterator iterator = vector.iterator(); + while (iterator.hasNext()) { + System.out.println(iterator.next()); + } + } + +} diff --git a/core-java-collections/src/main/java/com/baeldung/performance/ArrayListBenchmark.java b/core-java-collections/src/main/java/com/baeldung/performance/ArrayListBenchmark.java index dddd85007d..331ae8d908 100644 --- a/core-java-collections/src/main/java/com/baeldung/performance/ArrayListBenchmark.java +++ b/core-java-collections/src/main/java/com/baeldung/performance/ArrayListBenchmark.java @@ -9,7 +9,7 @@ import java.util.*; import java.util.concurrent.TimeUnit; @BenchmarkMode(Mode.AverageTime) -@OutputTimeUnit(TimeUnit.MICROSECONDS) +@OutputTimeUnit(TimeUnit.NANOSECONDS) @Warmup(iterations = 10) public class ArrayListBenchmark { @@ -17,6 +17,7 @@ public class ArrayListBenchmark { public static class MyState { List employeeList = new ArrayList<>(); + Vector employeeVector = new Vector<>(); //LinkedList employeeList = new LinkedList<>(); long iterations = 100000; @@ -29,9 +30,11 @@ public class ArrayListBenchmark { public void setUp() { for (long i = 0; i < iterations; i++) { employeeList.add(new Employee(i, "John")); + employeeVector.add(new Employee(i, "John")); } employeeList.add(employee); + employeeVector.add(employee); employeeIndex = employeeList.indexOf(employee); } } @@ -46,6 +49,11 @@ public class ArrayListBenchmark { return state.employeeList.contains(state.employee); } + @Benchmark + public boolean testContainsVector(ArrayListBenchmark.MyState state) { + return state.employeeVector.contains(state.employee); + } + @Benchmark public int testIndexOf(ArrayListBenchmark.MyState state) { return state.employeeList.indexOf(state.employee); @@ -56,19 +64,24 @@ public class ArrayListBenchmark { return state.employeeList.get(state.employeeIndex); } + @Benchmark + public Employee testVectorGet(ArrayListBenchmark.MyState state) { + return state.employeeVector.get(state.employeeIndex); + } + @Benchmark public boolean testRemove(ArrayListBenchmark.MyState state) { return state.employeeList.remove(state.employee); } -// @Benchmark -// public void testAdd(ArrayListBenchmark.MyState state) { -// state.employeeList.add(new Employee(state.iterations + 1, "John")); -// } + @Benchmark + public void testAdd(ArrayListBenchmark.MyState state) { + state.employeeList.add(new Employee(state.iterations + 1, "John")); + } public static void main(String[] args) throws Exception { Options options = new OptionsBuilder() - .include(ArrayListBenchmark.class.getSimpleName()).threads(1) + .include(ArrayListBenchmark.class.getSimpleName()).threads(3) .forks(1).shouldFailOnError(true) .shouldDoGC(true) .jvmArgs("-server").build(); diff --git a/core-java-collections/src/main/java/com/baeldung/queueInterface/CustomBaeldungQueue.java b/core-java-collections/src/main/java/com/baeldung/queueInterface/CustomBaeldungQueue.java new file mode 100644 index 0000000000..6b088a5079 --- /dev/null +++ b/core-java-collections/src/main/java/com/baeldung/queueInterface/CustomBaeldungQueue.java @@ -0,0 +1,48 @@ +package com.baeldung.queueinterface; + +import java.util.AbstractQueue; +import java.util.Iterator; +import java.util.LinkedList; + +public class CustomBaeldungQueue extends AbstractQueue { + + private LinkedList elements; + + public CustomBaeldungQueue() { + this.elements = new LinkedList(); + } + + @Override + public Iterator iterator() { + return elements.iterator(); + } + + @Override + public int size() { + return elements.size(); + } + + @Override + public boolean offer(T t) { + if(t == null) return false; + elements.add(t); + return true; + } + + @Override + public T poll() { + + Iterator iter = elements.iterator(); + T t = iter.next(); + if(t != null){ + iter.remove(); + return t; + } + return null; + } + + @Override + public T peek() { + return elements.getFirst(); + } +} diff --git a/core-java-collections/src/test/java/com/baeldung/queueInterface/PriorityQueueUnitTest.java b/core-java-collections/src/test/java/com/baeldung/queueInterface/PriorityQueueUnitTest.java new file mode 100644 index 0000000000..c5b564b55b --- /dev/null +++ b/core-java-collections/src/test/java/com/baeldung/queueInterface/PriorityQueueUnitTest.java @@ -0,0 +1,53 @@ +package com.baeldung.queueinterface; + +import org.junit.Before; +import org.junit.Test; + +import java.util.PriorityQueue; + +import static org.junit.Assert.assertEquals; + +public class PriorityQueueUnitTest { + + + + @Test + public void givenIntegerQueue_whenIntegersOutOfOrder_checkRetrievalOrderIsNatural() { + + PriorityQueue integerQueue = new PriorityQueue<>(); + + integerQueue.add(9); + integerQueue.add(2); + integerQueue.add(4); + + int first = integerQueue.poll(); + int second = integerQueue.poll(); + int third = integerQueue.poll(); + + assertEquals(2, first); + assertEquals(4, second); + assertEquals(9, third); + + + } + + @Test + public void givenStringQueue_whenStringsAddedOutOfNaturalOrder_checkRetrievalOrderNatural() { + + PriorityQueue stringQueue = new PriorityQueue<>(); + + stringQueue.add("banana"); + stringQueue.add("apple"); + stringQueue.add("cherry"); + + String first = stringQueue.poll(); + String second = stringQueue.poll(); + String third = stringQueue.poll(); + + assertEquals("apple", first); + assertEquals("banana", second); + assertEquals("cherry", third); + + + } +} diff --git a/core-java-collections/src/test/java/com/baeldung/queueinterface/CustomBaeldungQueueUnitTest.java b/core-java-collections/src/test/java/com/baeldung/queueinterface/CustomBaeldungQueueUnitTest.java new file mode 100644 index 0000000000..6dec768542 --- /dev/null +++ b/core-java-collections/src/test/java/com/baeldung/queueinterface/CustomBaeldungQueueUnitTest.java @@ -0,0 +1,30 @@ +package com.baeldung.queueinterface; + +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.*; + +public class CustomBaeldungQueueUnitTest { + + private CustomBaeldungQueue customQueue; + + @Before + public void setUp() throws Exception { + customQueue = new CustomBaeldungQueue<>(); + } + + @Test + public void givenQueueWithTwoElements_whenElementsRetrieved_checkRetrievalCorrect() { + + customQueue.add(7); + customQueue.add(5); + + int first = customQueue.poll(); + int second = customQueue.poll(); + + assertEquals(7, first); + assertEquals(5, second); + + } +} diff --git a/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/application/Application.java b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/application/Application.java new file mode 100644 index 0000000000..0c5caba8a0 --- /dev/null +++ b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/application/Application.java @@ -0,0 +1,86 @@ +package com.baeldung.concurrent.threadsafety.application; + +import com.baeldung.concurrent.threadsafety.callables.AtomicCounterCallable; +import com.baeldung.concurrent.threadsafety.mathutils.MathUtils; +import com.baeldung.concurrent.threadsafety.callables.CounterCallable; +import com.baeldung.concurrent.threadsafety.callables.ExtrinsicLockCounterCallable; +import com.baeldung.concurrent.threadsafety.callables.MessageServiceCallable; +import com.baeldung.concurrent.threadsafety.callables.ReentranReadWriteLockCounterCallable; +import com.baeldung.concurrent.threadsafety.callables.ReentrantLockCounterCallable; +import com.baeldung.concurrent.threadsafety.services.AtomicCounter; +import com.baeldung.concurrent.threadsafety.services.Counter; +import com.baeldung.concurrent.threadsafety.services.ExtrinsicLockCounter; +import com.baeldung.concurrent.threadsafety.services.MessageService; +import com.baeldung.concurrent.threadsafety.services.ReentrantLockCounter; +import com.baeldung.concurrent.threadsafety.services.ReentrantReadWriteLockCounter; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; + +public class Application { + + public static void main(String[] args) throws InterruptedException, ExecutionException { + + new Thread(() -> { + System.out.println(MathUtils.factorial(10)); + }).start(); + new Thread(() -> { + System.out.println(MathUtils.factorial(5)); + }).start(); + + ExecutorService executorService = Executors.newFixedThreadPool(10); + MessageService messageService = new MessageService("Welcome to Baeldung!"); + Future future1 = (Future) executorService.submit(new MessageServiceCallable(messageService)); + Future future2 = (Future) executorService.submit(new MessageServiceCallable(messageService)); + System.out.println(future1.get()); + System.out.println(future2.get()); + + Counter counter = new Counter(); + Future future3 = (Future) executorService.submit(new CounterCallable(counter)); + Future future4 = (Future) executorService.submit(new CounterCallable(counter)); + System.out.println(future3.get()); + System.out.println(future4.get()); + + ExtrinsicLockCounter extrinsicLockCounter = new ExtrinsicLockCounter(); + Future future5 = (Future) executorService.submit(new ExtrinsicLockCounterCallable(extrinsicLockCounter)); + Future future6 = (Future) executorService.submit(new ExtrinsicLockCounterCallable(extrinsicLockCounter)); + System.out.println(future5.get()); + System.out.println(future6.get()); + + ReentrantLockCounter reentrantLockCounter = new ReentrantLockCounter(); + Future future7 = (Future) executorService.submit(new ReentrantLockCounterCallable(reentrantLockCounter)); + Future future8 = (Future) executorService.submit(new ReentrantLockCounterCallable(reentrantLockCounter)); + System.out.println(future7.get()); + System.out.println(future8.get()); + + ReentrantReadWriteLockCounter reentrantReadWriteLockCounter = new ReentrantReadWriteLockCounter(); + Future future9 = (Future) executorService.submit(new ReentranReadWriteLockCounterCallable(reentrantReadWriteLockCounter)); + Future future10 = (Future) executorService.submit(new ReentranReadWriteLockCounterCallable(reentrantReadWriteLockCounter)); + System.out.println(future9.get()); + System.out.println(future10.get()); + + AtomicCounter atomicCounter = new AtomicCounter(); + Future future11 = (Future) executorService.submit(new AtomicCounterCallable(atomicCounter)); + Future future12 = (Future) executorService.submit(new AtomicCounterCallable(atomicCounter)); + System.out.println(future11.get()); + System.out.println(future12.get()); + + Collection syncCollection = Collections.synchronizedCollection(new ArrayList<>()); + Thread thread11 = new Thread(() -> syncCollection.addAll(Arrays.asList(1, 2, 3, 4, 5, 6))); + Thread thread12 = new Thread(() -> syncCollection.addAll(Arrays.asList(1, 2, 3, 4, 5, 6))); + thread11.start(); + thread12.start(); + + Map concurrentMap = new ConcurrentHashMap<>(); + concurrentMap.put("1", "one"); + concurrentMap.put("2", "two"); + concurrentMap.put("3", "three"); + } +} diff --git a/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/callables/AtomicCounterCallable.java b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/callables/AtomicCounterCallable.java new file mode 100644 index 0000000000..d711299b5c --- /dev/null +++ b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/callables/AtomicCounterCallable.java @@ -0,0 +1,19 @@ +package com.baeldung.concurrent.threadsafety.callables; + +import com.baeldung.concurrent.threadsafety.services.AtomicCounter; +import java.util.concurrent.Callable; + +public class AtomicCounterCallable implements Callable { + + private final AtomicCounter counter; + + public AtomicCounterCallable(AtomicCounter counter) { + this.counter = counter; + } + + @Override + public Integer call() throws Exception { + counter.incrementCounter(); + return counter.getCounter(); + } +} diff --git a/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/callables/CounterCallable.java b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/callables/CounterCallable.java new file mode 100644 index 0000000000..cdcd84a17b --- /dev/null +++ b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/callables/CounterCallable.java @@ -0,0 +1,19 @@ +package com.baeldung.concurrent.threadsafety.callables; + +import com.baeldung.concurrent.threadsafety.services.Counter; +import java.util.concurrent.Callable; + +public class CounterCallable implements Callable { + + private final Counter counter; + + public CounterCallable(Counter counter) { + this.counter = counter; + } + + @Override + public Integer call() throws Exception { + counter.incrementCounter(); + return counter.getCounter(); + } +} diff --git a/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/callables/ExtrinsicLockCounterCallable.java b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/callables/ExtrinsicLockCounterCallable.java new file mode 100644 index 0000000000..29533e7630 --- /dev/null +++ b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/callables/ExtrinsicLockCounterCallable.java @@ -0,0 +1,19 @@ +package com.baeldung.concurrent.threadsafety.callables; + +import com.baeldung.concurrent.threadsafety.services.ExtrinsicLockCounter; +import java.util.concurrent.Callable; + +public class ExtrinsicLockCounterCallable implements Callable { + + private final ExtrinsicLockCounter counter; + + public ExtrinsicLockCounterCallable(ExtrinsicLockCounter counter) { + this.counter = counter; + } + + @Override + public Integer call() throws Exception { + counter.incrementCounter(); + return counter.getCounter(); + } +} diff --git a/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/callables/MessageServiceCallable.java b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/callables/MessageServiceCallable.java new file mode 100644 index 0000000000..84e8c7bb51 --- /dev/null +++ b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/callables/MessageServiceCallable.java @@ -0,0 +1,19 @@ +package com.baeldung.concurrent.threadsafety.callables; + +import com.baeldung.concurrent.threadsafety.services.MessageService; +import java.util.concurrent.Callable; + +public class MessageServiceCallable implements Callable { + + private final MessageService messageService; + + public MessageServiceCallable(MessageService messageService) { + this.messageService = messageService; + + } + + @Override + public String call() { + return messageService.getMesssage(); + } +} diff --git a/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/callables/ReentranReadWriteLockCounterCallable.java b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/callables/ReentranReadWriteLockCounterCallable.java new file mode 100644 index 0000000000..e806460d50 --- /dev/null +++ b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/callables/ReentranReadWriteLockCounterCallable.java @@ -0,0 +1,20 @@ +package com.baeldung.concurrent.threadsafety.callables; + +import com.baeldung.concurrent.threadsafety.services.ReentrantReadWriteLockCounter; +import java.util.concurrent.Callable; + +public class ReentranReadWriteLockCounterCallable implements Callable { + + private final ReentrantReadWriteLockCounter counter; + + public ReentranReadWriteLockCounterCallable(ReentrantReadWriteLockCounter counter) { + this.counter = counter; + } + + @Override + public Integer call() throws Exception { + counter.incrementCounter(); + return counter.getCounter(); + } + +} diff --git a/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/callables/ReentrantLockCounterCallable.java b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/callables/ReentrantLockCounterCallable.java new file mode 100644 index 0000000000..3511a98c60 --- /dev/null +++ b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/callables/ReentrantLockCounterCallable.java @@ -0,0 +1,19 @@ +package com.baeldung.concurrent.threadsafety.callables; + +import com.baeldung.concurrent.threadsafety.services.ReentrantLockCounter; +import java.util.concurrent.Callable; + +public class ReentrantLockCounterCallable implements Callable { + + private final ReentrantLockCounter counter; + + public ReentrantLockCounterCallable(ReentrantLockCounter counter) { + this.counter = counter; + } + + @Override + public Integer call() throws Exception { + counter.incrementCounter(); + return counter.getCounter(); + } +} diff --git a/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/mathutils/MathUtils.java b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/mathutils/MathUtils.java new file mode 100644 index 0000000000..f560cd4281 --- /dev/null +++ b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/mathutils/MathUtils.java @@ -0,0 +1,14 @@ +package com.baeldung.concurrent.threadsafety.mathutils; + +import java.math.BigInteger; + +public class MathUtils { + + public static BigInteger factorial(int number) { + BigInteger f = new BigInteger("1"); + for (int i = 2; i <= number; i++) { + f = f.multiply(BigInteger.valueOf(i)); + } + return f; + } +} diff --git a/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/services/AtomicCounter.java b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/services/AtomicCounter.java new file mode 100644 index 0000000000..32a373495c --- /dev/null +++ b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/services/AtomicCounter.java @@ -0,0 +1,18 @@ +package com.baeldung.concurrent.threadsafety.services; + +import java.util.concurrent.atomic.AtomicInteger; + +public class AtomicCounter { + + private final AtomicInteger counter = new AtomicInteger(); + + public AtomicCounter() {} + + public void incrementCounter() { + counter.incrementAndGet(); + } + + public synchronized int getCounter() { + return counter.get(); + } +} diff --git a/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/services/Counter.java b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/services/Counter.java new file mode 100644 index 0000000000..f7dbc05639 --- /dev/null +++ b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/services/Counter.java @@ -0,0 +1,18 @@ +package com.baeldung.concurrent.threadsafety.services; + +public class Counter { + + private volatile int counter; + + public Counter() { + this.counter = 0; + } + + public synchronized void incrementCounter() { + counter += 1; + } + + public int getCounter() { + return counter; + } +} diff --git a/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/services/ExtrinsicLockCounter.java b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/services/ExtrinsicLockCounter.java new file mode 100644 index 0000000000..8ab431fbc3 --- /dev/null +++ b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/services/ExtrinsicLockCounter.java @@ -0,0 +1,23 @@ +package com.baeldung.concurrent.threadsafety.services; + +public class ExtrinsicLockCounter { + + private int counter; + private final Object lock = new Object(); + + public ExtrinsicLockCounter() { + this.counter = 0; + } + + public void incrementCounter() { + synchronized (lock) { + counter += 1; + } + } + + public int getCounter() { + synchronized (lock) { + return counter; + } + } +} diff --git a/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/services/MessageService.java b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/services/MessageService.java new file mode 100644 index 0000000000..33981381ea --- /dev/null +++ b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/services/MessageService.java @@ -0,0 +1,14 @@ +package com.baeldung.concurrent.threadsafety.services; + +public class MessageService { + + private final String message; + + public MessageService(String message) { + this.message = message; + } + + public String getMesssage() { + return message; + } +} diff --git a/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/services/ReentrantLockCounter.java b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/services/ReentrantLockCounter.java new file mode 100644 index 0000000000..717f0717af --- /dev/null +++ b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/services/ReentrantLockCounter.java @@ -0,0 +1,26 @@ +package com.baeldung.concurrent.threadsafety.services; + +import java.util.concurrent.locks.ReentrantLock; + +public class ReentrantLockCounter { + + private int counter; + private final ReentrantLock reLock = new ReentrantLock(true); + + public ReentrantLockCounter() { + this.counter = 0; + } + + public void incrementCounter() { + reLock.lock(); + try { + counter += 1; + } finally { + reLock.unlock(); + } + } + + public int getCounter() { + return counter; + } +} diff --git a/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/services/ReentrantReadWriteLockCounter.java b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/services/ReentrantReadWriteLockCounter.java new file mode 100644 index 0000000000..f740c938b1 --- /dev/null +++ b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/services/ReentrantReadWriteLockCounter.java @@ -0,0 +1,34 @@ +package com.baeldung.concurrent.threadsafety.services; + +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantReadWriteLock; + +public class ReentrantReadWriteLockCounter { + + private int counter; + private final ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock(); + private final Lock readLock = rwLock.readLock(); + private final Lock writeLock = rwLock.writeLock(); + + public ReentrantReadWriteLockCounter() { + this.counter = 0; + } + + public void incrementCounter() { + writeLock.lock(); + try { + counter += 1; + } finally { + writeLock.unlock(); + } + } + + public int getCounter() { + readLock.lock(); + try { + return counter; + } finally { + readLock.unlock(); + } + } +} diff --git a/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/services/StateHolder.java b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/services/StateHolder.java new file mode 100644 index 0000000000..5bbff9f39c --- /dev/null +++ b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/services/StateHolder.java @@ -0,0 +1,14 @@ +package com.baeldung.concurrent.threadsafety.services; + +public class StateHolder { + + private final String state; + + public StateHolder(String state) { + this.state = state; + } + + public String getState() { + return state; + } +} diff --git a/core-java-concurrency-basic/src/test/com/baeldung/concurrent/threadsafety/tests/CounterTest.java b/core-java-concurrency-basic/src/test/com/baeldung/concurrent/threadsafety/tests/CounterTest.java new file mode 100644 index 0000000000..3abbb1bdad --- /dev/null +++ b/core-java-concurrency-basic/src/test/com/baeldung/concurrent/threadsafety/tests/CounterTest.java @@ -0,0 +1,23 @@ +package com.baeldung.concurrent.threadsafety.tests; + +import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; +import com.baeldung.concurrent.threadsafety.callables.CounterCallable; +import com.baeldung.concurrent.threadsafety.services.Counter; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; + +public class CounterTest { + + @Test + public void whenCalledIncrementCounter_thenCorrect() throws Exception { + ExecutorService executorService = Executors.newFixedThreadPool(2); + Counter counter = new Counter(); + Future future1 = (Future) executorService.submit(new CounterCallable(counter)); + Future future2 = (Future) executorService.submit(new CounterCallable(counter)); + + assertThat(future1.get()).isEqualTo(1); + assertThat(future2.get()).isEqualTo(2); + } +} diff --git a/core-java-concurrency-basic/src/test/com/baeldung/concurrent/threadsafety/tests/ExtrinsicLockCounterTest.java b/core-java-concurrency-basic/src/test/com/baeldung/concurrent/threadsafety/tests/ExtrinsicLockCounterTest.java new file mode 100644 index 0000000000..dba90f5b74 --- /dev/null +++ b/core-java-concurrency-basic/src/test/com/baeldung/concurrent/threadsafety/tests/ExtrinsicLockCounterTest.java @@ -0,0 +1,23 @@ +package com.baeldung.concurrent.threadsafety.tests; + +import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; +import com.baeldung.concurrent.threadsafety.callables.ExtrinsicLockCounterCallable; +import com.baeldung.concurrent.threadsafety.services.ExtrinsicLockCounter; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; + +public class ExtrinsicLockCounterTest { + + @Test + public void whenCalledIncrementCounter_thenCorrect() throws Exception { + ExecutorService executorService = Executors.newFixedThreadPool(2); + ExtrinsicLockCounter counter = new ExtrinsicLockCounter(); + Future future1 = (Future) executorService.submit(new ExtrinsicLockCounterCallable(counter)); + Future future2 = (Future) executorService.submit(new ExtrinsicLockCounterCallable(counter)); + + assertThat(future1.get()).isEqualTo(1); + assertThat(future2.get()).isEqualTo(2); + } +} diff --git a/core-java-concurrency-basic/src/test/com/baeldung/concurrent/threadsafety/tests/MathUtilsTest.java b/core-java-concurrency-basic/src/test/com/baeldung/concurrent/threadsafety/tests/MathUtilsTest.java new file mode 100644 index 0000000000..8f3f574b03 --- /dev/null +++ b/core-java-concurrency-basic/src/test/com/baeldung/concurrent/threadsafety/tests/MathUtilsTest.java @@ -0,0 +1,13 @@ +package com.baeldung.concurrent.threadsafety.tests; + +import com.baeldung.concurrent.threadsafety.mathutils.MathUtils; +import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; + +public class MathUtilsTest { + + @Test + public void whenCalledFactorialMethod_thenCorrect() { + assertThat(MathUtils.factorial(2)).isEqualTo(2); + } +} diff --git a/core-java-concurrency-basic/src/test/com/baeldung/concurrent/threadsafety/tests/MessageServiceTest.java b/core-java-concurrency-basic/src/test/com/baeldung/concurrent/threadsafety/tests/MessageServiceTest.java new file mode 100644 index 0000000000..8f1f1a8754 --- /dev/null +++ b/core-java-concurrency-basic/src/test/com/baeldung/concurrent/threadsafety/tests/MessageServiceTest.java @@ -0,0 +1,23 @@ +package com.baeldung.concurrent.threadsafety.tests; + +import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; +import com.baeldung.concurrent.threadsafety.callables.MessageServiceCallable; +import com.baeldung.concurrent.threadsafety.services.MessageService; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; + +public class MessageServiceTest { + + @Test + public void whenCalledgetMessage_thenCorrect() throws Exception { + ExecutorService executorService = Executors.newFixedThreadPool(2); + MessageService messageService = new MessageService("Welcome to Baeldung!"); + Future future1 = (Future) executorService.submit(new MessageServiceCallable(messageService)); + Future future2 = (Future) executorService.submit(new MessageServiceCallable(messageService)); + + assertThat(future1.get()).isEqualTo("Welcome to Baeldung!"); + assertThat(future2.get()).isEqualTo("Welcome to Baeldung!"); + } +} diff --git a/core-java-concurrency-basic/src/test/com/baeldung/concurrent/threadsafety/tests/ReentrantLockCounterTest.java b/core-java-concurrency-basic/src/test/com/baeldung/concurrent/threadsafety/tests/ReentrantLockCounterTest.java new file mode 100644 index 0000000000..05c721ab26 --- /dev/null +++ b/core-java-concurrency-basic/src/test/com/baeldung/concurrent/threadsafety/tests/ReentrantLockCounterTest.java @@ -0,0 +1,23 @@ +package com.baeldung.concurrent.threadsafety.tests; + +import com.baeldung.concurrent.threadsafety.callables.ReentrantLockCounterCallable; +import com.baeldung.concurrent.threadsafety.services.ReentrantLockCounter; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import static org.assertj.core.api.Assertions.assertThat; +import org.junit.Test; + +public class ReentrantLockCounterTest { + + @Test + public void whenCalledIncrementCounter_thenCorrect() throws Exception { + ExecutorService executorService = Executors.newFixedThreadPool(2); + ReentrantLockCounter counter = new ReentrantLockCounter(); + Future future1 = (Future) executorService.submit(new ReentrantLockCounterCallable(counter)); + Future future2 = (Future) executorService.submit(new ReentrantLockCounterCallable(counter)); + + assertThat(future1.get()).isEqualTo(1); + assertThat(future2.get()).isEqualTo(2); + } +} diff --git a/core-java-concurrency-basic/src/test/com/baeldung/concurrent/threadsafety/tests/ReentrantReadWriteLockCounterTest.java b/core-java-concurrency-basic/src/test/com/baeldung/concurrent/threadsafety/tests/ReentrantReadWriteLockCounterTest.java new file mode 100644 index 0000000000..c56137ce04 --- /dev/null +++ b/core-java-concurrency-basic/src/test/com/baeldung/concurrent/threadsafety/tests/ReentrantReadWriteLockCounterTest.java @@ -0,0 +1,24 @@ +package com.baeldung.concurrent.threadsafety.tests; + +import com.baeldung.concurrent.threadsafety.callables.ReentranReadWriteLockCounterCallable; +import com.baeldung.concurrent.threadsafety.services.ReentrantReadWriteLockCounter; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import static org.assertj.core.api.Assertions.assertThat; +import org.junit.Test; + +public class ReentrantReadWriteLockCounterTest { + + @Test + public void whenCalledIncrementCounter_thenCorrect() throws Exception { + ExecutorService executorService = Executors.newFixedThreadPool(2); + ReentrantReadWriteLockCounter counter = new ReentrantReadWriteLockCounter(); + Future future1 = (Future) executorService.submit(new ReentranReadWriteLockCounterCallable(counter)); + Future future2 = (Future) executorService.submit(new ReentranReadWriteLockCounterCallable(counter)); + + assertThat(future1.get()).isEqualTo(1); + assertThat(future2.get()).isEqualTo(2); + } + +} diff --git a/core-java-io/src/test/java/com/baeldung/directories/NewDirectoryUnitTest.java b/core-java-io/src/test/java/com/baeldung/directories/NewDirectoryUnitTest.java new file mode 100644 index 0000000000..e0111c2702 --- /dev/null +++ b/core-java-io/src/test/java/com/baeldung/directories/NewDirectoryUnitTest.java @@ -0,0 +1,100 @@ +package com.baeldung.directories; + +import org.junit.Before; +import org.junit.Test; + +import java.io.File; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +public class NewDirectoryUnitTest { + + private static final File TEMP_DIRECTORY = new File(System.getProperty("java.io.tmpdir")); + + @Before + public void beforeEach() { + File newDirectory = new File(TEMP_DIRECTORY, "new_directory"); + File nestedInNewDirectory = new File(newDirectory, "nested_directory"); + File existingDirectory = new File(TEMP_DIRECTORY, "existing_directory"); + File existingNestedDirectory = new File(existingDirectory, "existing_nested_directory"); + File nestedInExistingDirectory = new File(existingDirectory, "nested_directory"); + + nestedInNewDirectory.delete(); + newDirectory.delete(); + nestedInExistingDirectory.delete(); + existingDirectory.mkdir(); + existingNestedDirectory.mkdir(); + } + + @Test + public void givenUnexistingDirectory_whenMkdir_thenTrue() { + File newDirectory = new File(TEMP_DIRECTORY, "new_directory"); + assertFalse(newDirectory.exists()); + + boolean directoryCreated = newDirectory.mkdir(); + + assertTrue(directoryCreated); + } + + @Test + public void givenExistingDirectory_whenMkdir_thenFalse() { + File newDirectory = new File(TEMP_DIRECTORY, "new_directory"); + newDirectory.mkdir(); + assertTrue(newDirectory.exists()); + + boolean directoryCreated = newDirectory.mkdir(); + + assertFalse(directoryCreated); + } + + @Test + public void givenUnexistingNestedDirectories_whenMkdir_thenFalse() { + File newDirectory = new File(TEMP_DIRECTORY, "new_directory"); + File nestedDirectory = new File(newDirectory, "nested_directory"); + assertFalse(newDirectory.exists()); + assertFalse(nestedDirectory.exists()); + + boolean directoriesCreated = nestedDirectory.mkdir(); + + assertFalse(directoriesCreated); + } + + @Test + public void givenUnexistingNestedDirectories_whenMkdirs_thenTrue() { + File newDirectory = new File(TEMP_DIRECTORY, "new_directory"); + File nestedDirectory = new File(newDirectory, "nested_directory"); + assertFalse(newDirectory.exists()); + assertFalse(nestedDirectory.exists()); + + boolean directoriesCreated = nestedDirectory.mkdirs(); + + assertTrue(directoriesCreated); + } + + @Test + public void givenExistingParentDirectories_whenMkdirs_thenTrue() { + File newDirectory = new File(TEMP_DIRECTORY, "existing_directory"); + newDirectory.mkdir(); + File nestedDirectory = new File(newDirectory, "nested_directory"); + assertTrue(newDirectory.exists()); + assertFalse(nestedDirectory.exists()); + + boolean directoriesCreated = nestedDirectory.mkdirs(); + + assertTrue(directoriesCreated); + } + + @Test + public void givenExistingNestedDirectories_whenMkdirs_thenFalse() { + File existingDirectory = new File(TEMP_DIRECTORY, "existing_directory"); + File existingNestedDirectory = new File(existingDirectory, "existing_nested_directory"); + assertTrue(existingDirectory.exists()); + assertTrue(existingNestedDirectory.exists()); + + boolean directoriesCreated = existingNestedDirectory.mkdirs(); + + assertFalse(directoriesCreated); + } + +} diff --git a/core-java-io/src/test/java/org/baeldung/java/io/InputStreamToByteBufferUnitTest.java b/core-java-io/src/test/java/org/baeldung/java/io/InputStreamToByteBufferUnitTest.java new file mode 100644 index 0000000000..fedadde04b --- /dev/null +++ b/core-java-io/src/test/java/org/baeldung/java/io/InputStreamToByteBufferUnitTest.java @@ -0,0 +1,60 @@ +package org.baeldung.java.io; + + +import com.google.common.io.ByteStreams; +import org.apache.commons.io.IOUtils; +import org.junit.jupiter.api.Test; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.channels.ReadableByteChannel; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class InputStreamToByteBufferUnitTest { + + @Test + public void givenUsingCoreClasses_whenWritingAFileIntoAByteBuffer_thenBytesLengthMustMatch() throws IOException { + File inputFile = getFile(); + ByteBuffer bufferByte = ByteBuffer.allocate((int) inputFile.length()); + FileInputStream in = new FileInputStream(inputFile); + in.getChannel().read(bufferByte); + + assertEquals(bufferByte.position(), inputFile.length()); + } + + @Test + public void givenUsingCommonsIo_whenWritingAFileIntoAByteBuffer_thenBytesLengthMustMatch() throws IOException { + File inputFile = getFile(); + ByteBuffer bufferByte = ByteBuffer.allocateDirect((int) inputFile.length()); + ReadableByteChannel readableByteChannel = new FileInputStream(inputFile).getChannel(); + IOUtils.readFully(readableByteChannel, bufferByte); + + assertEquals(bufferByte.position(), inputFile.length()); + } + + @Test + public void givenUsingGuava_whenWritingAFileIntoAByteBuffer_thenBytesLengthMustMatch() throws IOException { + File inputFile = getFile(); + FileInputStream in = new FileInputStream(inputFile); + byte[] targetArray = ByteStreams.toByteArray(in); + ByteBuffer bufferByte = ByteBuffer.wrap(targetArray); + bufferByte.rewind(); + while (bufferByte.hasRemaining()) { + bufferByte.get(); + } + + assertEquals(bufferByte.position(), inputFile.length()); + } + + private File getFile() { + ClassLoader classLoader = new InputStreamToByteBufferUnitTest().getClass().getClassLoader(); + + String fileName = "frontenac-2257154_960_720.jpg"; + + return new File(classLoader.getResource(fileName).getFile()); + } + +} diff --git a/core-java-io/src/test/resources/frontenac-2257154_960_720.jpg b/core-java-io/src/test/resources/frontenac-2257154_960_720.jpg new file mode 100644 index 0000000000..77c459b0e3 Binary files /dev/null and b/core-java-io/src/test/resources/frontenac-2257154_960_720.jpg differ diff --git a/core-java-lang-syntax/src/main/java/com/baeldung/keyword/Circle.java b/core-java-lang-syntax/src/main/java/com/baeldung/keyword/Circle.java new file mode 100644 index 0000000000..231b2f5a59 --- /dev/null +++ b/core-java-lang-syntax/src/main/java/com/baeldung/keyword/Circle.java @@ -0,0 +1,5 @@ +package com.baeldung.keyword; + +public class Circle extends Round implements Shape { + +} diff --git a/core-java-lang-syntax/src/main/java/com/baeldung/keyword/Ring.java b/core-java-lang-syntax/src/main/java/com/baeldung/keyword/Ring.java new file mode 100644 index 0000000000..99873f9640 --- /dev/null +++ b/core-java-lang-syntax/src/main/java/com/baeldung/keyword/Ring.java @@ -0,0 +1,4 @@ +package com.baeldung.keyword; + +public class Ring extends Round { +} diff --git a/core-java-lang-syntax/src/main/java/com/baeldung/keyword/Round.java b/core-java-lang-syntax/src/main/java/com/baeldung/keyword/Round.java new file mode 100644 index 0000000000..0e2cc2c8c7 --- /dev/null +++ b/core-java-lang-syntax/src/main/java/com/baeldung/keyword/Round.java @@ -0,0 +1,4 @@ +package com.baeldung.keyword; + +public class Round { +} diff --git a/core-java-lang-syntax/src/main/java/com/baeldung/keyword/Shape.java b/core-java-lang-syntax/src/main/java/com/baeldung/keyword/Shape.java new file mode 100644 index 0000000000..8d00c165a3 --- /dev/null +++ b/core-java-lang-syntax/src/main/java/com/baeldung/keyword/Shape.java @@ -0,0 +1,4 @@ +package com.baeldung.keyword; + +public interface Shape { +} diff --git a/core-java-lang-syntax/src/main/java/com/baeldung/keyword/Triangle.java b/core-java-lang-syntax/src/main/java/com/baeldung/keyword/Triangle.java new file mode 100644 index 0000000000..406b8f23e5 --- /dev/null +++ b/core-java-lang-syntax/src/main/java/com/baeldung/keyword/Triangle.java @@ -0,0 +1,4 @@ +package com.baeldung.keyword; + +public class Triangle implements Shape { +} diff --git a/core-java-lang-syntax/src/test/java/com/baeldung/keyword/test/InstanceOfUnitTest.java b/core-java-lang-syntax/src/test/java/com/baeldung/keyword/test/InstanceOfUnitTest.java new file mode 100644 index 0000000000..4c010e3a16 --- /dev/null +++ b/core-java-lang-syntax/src/test/java/com/baeldung/keyword/test/InstanceOfUnitTest.java @@ -0,0 +1,55 @@ +package com.baeldung.keyword.test; + +import org.junit.Assert; +import org.junit.jupiter.api.Test; + +import com.baeldung.keyword.Circle; +import com.baeldung.keyword.Ring; +import com.baeldung.keyword.Round; +import com.baeldung.keyword.Shape; +import com.baeldung.keyword.Triangle; + +public class InstanceOfUnitTest { + + @Test + public void giveWhenInstanceIsCorrect_thenReturnTrue() { + Ring ring = new Ring(); + Assert.assertTrue("ring is instance of Round ", ring instanceof Round); + } + + @Test + public void giveWhenObjectIsInstanceOfType_thenReturnTrue() { + Circle circle = new Circle(); + Assert.assertTrue("circle is instance of Circle ", circle instanceof Circle); + } + + + @Test + public void giveWhenInstanceIsOfSubtype_thenReturnTrue() { + Circle circle = new Circle(); + Assert.assertTrue("circle is instance of Round", circle instanceof Round); + } + + @Test + public void giveWhenTypeIsInterface_thenReturnTrue() { + Circle circle = new Circle(); + Assert.assertTrue("circle is instance of Shape", circle instanceof Shape); + } + + @Test + public void giveWhenTypeIsOfObjectType_thenReturnTrue() { + Thread thread = new Thread(); + Assert.assertTrue("thread is instance of Object", thread instanceof Object); + } + + @Test + public void giveWhenInstanceValueIsNull_thenReturnFalse() { + Circle circle = null; + Assert.assertFalse("circle is instance of Round", circle instanceof Round); + } + + @Test + public void giveWhenComparingClassInDiffHierarchy_thenCompilationError() { + // Assert.assertFalse("circle is instance of Triangle", circle instanceof Triangle); + } +} diff --git a/core-java-8/src/main/java/com/baeldung/enums/values/Element1.java b/core-java-lang/src/main/java/com/baeldung/enums/values/Element1.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/enums/values/Element1.java rename to core-java-lang/src/main/java/com/baeldung/enums/values/Element1.java diff --git a/core-java-8/src/main/java/com/baeldung/enums/values/Element2.java b/core-java-lang/src/main/java/com/baeldung/enums/values/Element2.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/enums/values/Element2.java rename to core-java-lang/src/main/java/com/baeldung/enums/values/Element2.java diff --git a/core-java-8/src/main/java/com/baeldung/enums/values/Element3.java b/core-java-lang/src/main/java/com/baeldung/enums/values/Element3.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/enums/values/Element3.java rename to core-java-lang/src/main/java/com/baeldung/enums/values/Element3.java diff --git a/core-java-8/src/main/java/com/baeldung/enums/values/Element4.java b/core-java-lang/src/main/java/com/baeldung/enums/values/Element4.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/enums/values/Element4.java rename to core-java-lang/src/main/java/com/baeldung/enums/values/Element4.java diff --git a/core-java-8/src/main/java/com/baeldung/enums/values/Labeled.java b/core-java-lang/src/main/java/com/baeldung/enums/values/Labeled.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/enums/values/Labeled.java rename to core-java-lang/src/main/java/com/baeldung/enums/values/Labeled.java diff --git a/core-java-8/src/test/java/com/baeldung/enums/values/Element1UnitTest.java b/core-java-lang/src/test/java/com/baeldung/enums/values/Element1UnitTest.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/enums/values/Element1UnitTest.java rename to core-java-lang/src/test/java/com/baeldung/enums/values/Element1UnitTest.java diff --git a/core-java-8/src/test/java/com/baeldung/enums/values/Element2UnitTest.java b/core-java-lang/src/test/java/com/baeldung/enums/values/Element2UnitTest.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/enums/values/Element2UnitTest.java rename to core-java-lang/src/test/java/com/baeldung/enums/values/Element2UnitTest.java diff --git a/core-java-8/src/test/java/com/baeldung/enums/values/Element3UnitTest.java b/core-java-lang/src/test/java/com/baeldung/enums/values/Element3UnitTest.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/enums/values/Element3UnitTest.java rename to core-java-lang/src/test/java/com/baeldung/enums/values/Element3UnitTest.java diff --git a/core-java-8/src/test/java/com/baeldung/enums/values/Element4UnitTest.java b/core-java-lang/src/test/java/com/baeldung/enums/values/Element4UnitTest.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/enums/values/Element4UnitTest.java rename to core-java-lang/src/test/java/com/baeldung/enums/values/Element4UnitTest.java diff --git a/core-java-perf/src/main/java/com/baeldung/flightrecorder/FlightRecorder.java b/core-java-perf/src/main/java/com/baeldung/flightrecorder/FlightRecorder.java new file mode 100644 index 0000000000..02c3e96124 --- /dev/null +++ b/core-java-perf/src/main/java/com/baeldung/flightrecorder/FlightRecorder.java @@ -0,0 +1,32 @@ +package com.baeldung.flightrecorder; + +import java.util.ArrayList; +import java.util.List; + +/** + * Simple program that illustrates how to use Java Flight Recorder. + * + * This programs creates a list, inserts objects in it until + * an OutOfMemoryError is thrown. + * + */ +public class FlightRecorder { + + public static void main(String[] args) { + List items = new ArrayList<>(1); + try { + while (true) { + items.add(new Object()); + } + } catch (OutOfMemoryError e) { + System.out.println(e.getMessage()); + } + assert items.size() > 0; + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + System.out.println(e.getMessage()); + } + } + +} diff --git a/core-java-security/src/main/java/com/baeldung/ssl/EnableTLSv12.java b/core-java-security/src/main/java/com/baeldung/ssl/EnableTLSv12.java new file mode 100644 index 0000000000..aa70b11584 --- /dev/null +++ b/core-java-security/src/main/java/com/baeldung/ssl/EnableTLSv12.java @@ -0,0 +1,115 @@ +package com.baeldung.ssl; + +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.OutputStreamWriter; +import java.io.PrintWriter; +import java.net.URL; +import java.net.UnknownHostException; +import java.security.KeyManagementException; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; + +import javax.net.ssl.HttpsURLConnection; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLParameters; +import javax.net.ssl.SSLSocket; +import javax.net.ssl.SSLSocketFactory; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class EnableTLSv12 { + + private final Logger logger = LoggerFactory.getLogger(EnableTLSv12.class); + + public String url = ""; + public Integer port = null; + + public EnableTLSv12() { + } + + public static void main(String[] args) throws IOException, KeyManagementException, NoSuchAlgorithmException { + EnableTLSv12 enableTLSv12 = new EnableTLSv12(); + if (args.length != 2) { + System.out.println("Provide the server url and the secure port:"); + System.exit(-1); + } + enableTLSv12.setHost(args); + enableTLSv12.setPort(args); + enableTLSv12.enableTLSv12UsingHttpConnection(); + enableTLSv12.enableTLSv12UsingProtocol(); + enableTLSv12.enableTLSv12UsingSSLContext(); + enableTLSv12.enableTLSv12UsingSSLParameters(); + } + + private void setPort(String[] args) { + url = args[0]; + } + + private void setHost(String[] args) { + String portNumber = args[1]; + port = Integer.parseInt(portNumber); + } + + private void handleCommunication(SSLSocket socket, String usedTLSProcess) throws IOException { + logger.debug("Enabled TLS v1.2 on " + usedTLSProcess); + try (PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()))); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()))) { + out.println("GET / HTTP/1.0"); + out.println(); + out.flush(); + if (out.checkError()) { + logger.error("SSLSocketClient: java.io.PrintWriter error"); + return; + } + + String inputLine; + while ((inputLine = in.readLine()) != null) + logger.info(inputLine); + } + } + + public void enableTLSv12UsingSSLParameters() throws UnknownHostException, IOException { + SSLSocketFactory socketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault(); + SSLSocket sslSocket = (SSLSocket) socketFactory.createSocket(url.trim(), port); + SSLParameters params = new SSLParameters(); + params.setProtocols(new String[] { "TLSv1.2" }); + sslSocket.setSSLParameters(params); + sslSocket.startHandshake(); + handleCommunication(sslSocket, "SSLSocketFactory-SSLParameters"); + } + + public void enableTLSv12UsingProtocol() throws IOException { + SSLSocketFactory socketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault(); + SSLSocket sslSocket = (SSLSocket) socketFactory.createSocket(url, port); + sslSocket.setEnabledProtocols(new String[] { "TLSv1.2" }); + sslSocket.startHandshake(); + handleCommunication(sslSocket, "SSLSocketFactory-EnabledProtocols"); + } + + public void enableTLSv12UsingHttpConnection() throws IOException, NoSuchAlgorithmException, KeyManagementException { + URL urls = new URL("https://" + url + ":" + port); + SSLContext sslContext = SSLContext.getInstance("TLSv1.2"); + sslContext.init(null, null, new SecureRandom()); + HttpsURLConnection connection = (HttpsURLConnection) urls.openConnection(); + connection.setSSLSocketFactory(sslContext.getSocketFactory()); + try (BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()))) { + String input; + while ((input = br.readLine()) != null) { + logger.info(input); + } + } + logger.debug("Created TLSv1.2 connection on HttpsURLConnection"); + } + + public void enableTLSv12UsingSSLContext() throws NoSuchAlgorithmException, KeyManagementException, UnknownHostException, IOException { + SSLContext sslContext = SSLContext.getInstance("TLSv1.2"); + sslContext.init(null, null, new SecureRandom()); + SSLSocketFactory socketFactory = sslContext.getSocketFactory(); + SSLSocket socket = (SSLSocket) socketFactory.createSocket(url, port); + handleCommunication(socket, "SSLContext"); + } + +} diff --git a/core-java/pom.xml b/core-java/pom.xml index 6c58653d5a..d21c624997 100644 --- a/core-java/pom.xml +++ b/core-java/pom.xml @@ -13,6 +13,7 @@ ../parent-java + commons-io diff --git a/core-java/src/test/java/com/baeldung/curltojava/JavaCurlExamplesUnitTest.java b/core-java/src/test/java/com/baeldung/curltojava/JavaCurlExamplesLiveTest.java similarity index 56% rename from core-java/src/test/java/com/baeldung/curltojava/JavaCurlExamplesUnitTest.java rename to core-java/src/test/java/com/baeldung/curltojava/JavaCurlExamplesLiveTest.java index 4e82059f2b..2ec62cbbf9 100644 --- a/core-java/src/test/java/com/baeldung/curltojava/JavaCurlExamplesUnitTest.java +++ b/core-java/src/test/java/com/baeldung/curltojava/JavaCurlExamplesLiveTest.java @@ -3,19 +3,16 @@ package com.baeldung.curltojava; import java.io.File; import java.io.IOException; import java.io.InputStream; -import java.net.HttpURLConnection; -import java.net.URL; import org.junit.Assert; import org.junit.Test; -public class JavaCurlExamplesUnitTest { - +public class JavaCurlExamplesLiveTest { @Test public void givenCommand_whenCalled_thenProduceZeroExitCode() throws IOException { - String command = "curl --location --request GET \"https://postman-echo.com/get?foo1=bar1&foo2=bar2\""; - ProcessBuilder processBuilder = new ProcessBuilder(command.replaceAll("\"", "").split(" ")); + String command = "curl -X GET https://postman-echo.com/get?foo1=bar1&foo2=bar2"; + ProcessBuilder processBuilder = new ProcessBuilder(command.split(" ")); processBuilder.directory(new File("/home/")); Process process = processBuilder.start(); InputStream inputStream = process.getInputStream(); @@ -28,8 +25,8 @@ public class JavaCurlExamplesUnitTest { @Test public void givenNewCommands_whenCalled_thenCheckIfIsAlive() throws IOException { - String command = "curl --location --request GET \"https://postman-echo.com/get?foo1=bar1&foo2=bar2\""; - ProcessBuilder processBuilder = new ProcessBuilder(command.replaceAll("\"", "").split(" ")); + String command = "curl -X GET https://postman-echo.com/get?foo1=bar1&foo2=bar2"; + ProcessBuilder processBuilder = new ProcessBuilder(command.split(" ")); processBuilder.directory(new File("/home/")); Process process = processBuilder.start(); @@ -40,16 +37,14 @@ public class JavaCurlExamplesUnitTest { } @Test - public void whenRequestGet_thenReturnSuccessResponseCode() throws IOException { - String url = "https://postman-echo.com/get?foo1=bar1&foo2=bar2"; - URL urlObj = new URL(url); - HttpURLConnection connection = (HttpURLConnection) urlObj.openConnection(); - connection.setDoOutput(true); - connection.setInstanceFollowRedirects(false); - connection.setRequestMethod("GET"); - connection.connect(); + public void whenRequestPost_thenCheckIfReturnContent() throws IOException { + String command = "curl -X POST https://postman-echo.com/post --data foo1=bar1&foo2=bar2"; + Process process = Runtime.getRuntime().exec(command); - Assert.assertEquals(HttpURLConnection.HTTP_OK, connection.getResponseCode()); + // Get the POST result + String content = JavaCurlExamples.inputStreamToString(process.getInputStream()); + + Assert.assertTrue(null != content && !content.isEmpty()); } } diff --git a/core-java/src/test/java/com/baeldung/leapyear/LeapYearUnitTest.java b/core-java/src/test/java/com/baeldung/leapyear/LeapYearUnitTest.java new file mode 100644 index 0000000000..e710eecc66 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/leapyear/LeapYearUnitTest.java @@ -0,0 +1,41 @@ +package com.baeldung.leapyear; + +import java.time.LocalDate; +import java.time.Year; +import java.time.format.DateTimeFormatter; +import java.util.GregorianCalendar; + +import org.junit.Assert; +import org.junit.Test; + +public class LeapYearUnitTest { + + //Before Java8 + @Test + public void testLeapYearUsingGregorianCalendar () { + Assert.assertFalse(new GregorianCalendar().isLeapYear(2018)); + } + + //Java 8 and above + @Test + public void testLeapYearUsingJavaTimeYear () { + Assert.assertTrue(Year.isLeap(2012)); + } + + @Test + public void testBCYearUsingJavaTimeYear () { + Assert.assertTrue(Year.isLeap(-4)); + } + + @Test + public void testWrongLeapYearUsingJavaTimeYear () { + Assert.assertFalse(Year.isLeap(2018)); + } + + @Test + public void testLeapYearInDateUsingJavaTimeYear () { + LocalDate date = LocalDate.parse("2020-01-05", DateTimeFormatter.ISO_LOCAL_DATE); + Assert.assertTrue(Year.from(date).isLeap()); + } + +} diff --git a/core-kotlin/pom.xml b/core-kotlin/pom.xml index 8b871f28ee..ed79ebc01b 100644 --- a/core-kotlin/pom.xml +++ b/core-kotlin/pom.xml @@ -72,17 +72,6 @@ injekt-core 1.16.1 - - uy.kohesive.kovert - kovert-vertx - [1.5.0,1.6.0) - - - nl.komponents.kovenant - kovenant - - - diff --git a/ethereum/pom.xml b/ethereum/pom.xml index 85cb260670..c7f82eaf22 100644 --- a/ethereum/pom.xml +++ b/ethereum/pom.xml @@ -37,17 +37,17 @@ org.springframework spring-core - ${springframework.version} + ${spring.version} org.springframework spring-web - ${springframework.version} + ${spring.version} org.springframework spring-webmvc - ${springframework.version} + ${spring.version} @@ -123,12 +123,12 @@ org.springframework spring-context - ${springframework.version} + ${spring.version} org.springframework spring-test - ${springframework.version} + ${spring.version} test @@ -212,7 +212,6 @@ 8.5.4 1.5.0-RELEASE 3.3.1 - 5.0.5.RELEASE 1.5.6.RELEASE 2.21.0 2.9.7 diff --git a/jackson/src/main/java/com/baeldung/jackson/deserialization/immutable/Employee.java b/jackson/src/main/java/com/baeldung/jackson/deserialization/immutable/Employee.java new file mode 100644 index 0000000000..44b10ee39b --- /dev/null +++ b/jackson/src/main/java/com/baeldung/jackson/deserialization/immutable/Employee.java @@ -0,0 +1,24 @@ +package com.baeldung.jackson.deserialization.immutable; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; + +public class Employee { + + private final long id; + private final String name; + + @JsonCreator(mode = JsonCreator.Mode.PROPERTIES) + public Employee(@JsonProperty("id") long id, @JsonProperty("name") String name) { + this.id = id; + this.name = name; + } + + public long getId() { + return id; + } + + public String getName() { + return name; + } +} diff --git a/jackson/src/main/java/com/baeldung/jackson/deserialization/immutable/Person.java b/jackson/src/main/java/com/baeldung/jackson/deserialization/immutable/Person.java new file mode 100644 index 0000000000..d9041720b6 --- /dev/null +++ b/jackson/src/main/java/com/baeldung/jackson/deserialization/immutable/Person.java @@ -0,0 +1,44 @@ +package com.baeldung.jackson.deserialization.immutable; + +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder; + +@JsonDeserialize(builder = Person.Builder.class) +public class Person { + + private final String name; + private final Integer age; + + private Person(String name, Integer age) { + this.name = name; + this.age = age; + } + + public String getName() { + return name; + } + + public Integer getAge() { + return age; + } + + @JsonPOJOBuilder + static class Builder { + String name; + Integer age; + + Builder withName(String name) { + this.name = name; + return this; + } + + Builder withAge(Integer age) { + this.age = age; + return this; + } + + Person build() { + return new Person(name, age); + } + } +} diff --git a/jackson/src/test/java/com/baeldung/jackson/deserialization/immutable/ImmutableObjectDeserializationUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/deserialization/immutable/ImmutableObjectDeserializationUnitTest.java new file mode 100644 index 0000000000..1252179e3a --- /dev/null +++ b/jackson/src/test/java/com/baeldung/jackson/deserialization/immutable/ImmutableObjectDeserializationUnitTest.java @@ -0,0 +1,38 @@ +package com.baeldung.jackson.deserialization.immutable; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.Test; + +import java.io.IOException; + +import static org.junit.Assert.*; + +public class ImmutableObjectDeserializationUnitTest { + + @Test + public void whenPublicConstructorIsUsed_thenObjectIsDeserialized() throws IOException { + final String json = "{\"name\":\"Frank\",\"id\":5000}"; + Employee employee = new ObjectMapper().readValue(json, Employee.class); + + assertEquals("Frank", employee.getName()); + assertEquals(5000, employee.getId()); + } + + @Test + public void whenBuilderIsUsedAndFieldIsNull_thenObjectIsDeserialized() throws IOException { + final String json = "{\"name\":\"Frank\"}"; + Person person = new ObjectMapper().readValue(json, Person.class); + + assertEquals("Frank", person.getName()); + assertNull(person.getAge()); + } + + @Test + public void whenBuilderIsUsedAndAllFieldsPresent_thenObjectIsDeserialized() throws IOException { + final String json = "{\"name\":\"Frank\",\"age\":50}"; + Person person = new ObjectMapper().readValue(json, Person.class); + + assertEquals("Frank", person.getName()); + assertEquals(50, (int) person.getAge()); + } +} diff --git a/java-collections-maps/src/main/java/com/baeldung/convert/MapToString.java b/java-collections-maps/src/main/java/com/baeldung/convert/MapToString.java new file mode 100644 index 0000000000..aca0d05ef1 --- /dev/null +++ b/java-collections-maps/src/main/java/com/baeldung/convert/MapToString.java @@ -0,0 +1,34 @@ +package com.baeldung.convert; + +import com.google.common.base.Joiner; +import org.apache.commons.lang3.StringUtils; + +import java.util.Map; +import java.util.stream.Collectors; + +public class MapToString { + + public static String convertWithIteration(Map map) { + StringBuilder mapAsString = new StringBuilder("{"); + for (Integer key : map.keySet()) { + mapAsString.append(key + "=" + map.get(key) + ", "); + } + mapAsString.delete(mapAsString.length()-2, mapAsString.length()).append("}"); + return mapAsString.toString(); + } + + public static String convertWithStream(Map map) { + String mapAsString = map.keySet().stream() + .map(key -> key + "=" + map.get(key)) + .collect(Collectors.joining(", ", "{", "}")); + return mapAsString; + } + + public static String convertWithGuava(Map map) { + return Joiner.on(",").withKeyValueSeparator("=").join(map); + } + + public static String convertWithApache(Map map) { + return StringUtils.join(map); + } +} diff --git a/java-collections-maps/src/main/java/com/baeldung/convert/StringToMap.java b/java-collections-maps/src/main/java/com/baeldung/convert/StringToMap.java new file mode 100644 index 0000000000..caabca4a09 --- /dev/null +++ b/java-collections-maps/src/main/java/com/baeldung/convert/StringToMap.java @@ -0,0 +1,21 @@ +package com.baeldung.convert; + +import com.google.common.base.Splitter; + +import java.util.Arrays; +import java.util.Map; +import java.util.stream.Collectors; + +public class StringToMap { + + public static Map convertWithStream(String mapAsString) { + Map map = Arrays.stream(mapAsString.split(",")) + .map(entry -> entry.split("=")) + .collect(Collectors.toMap(entry -> entry[0], entry -> entry[1])); + return map; + } + + public static Map convertWithGuava(String mapAsString) { + return Splitter.on(',').withKeyValueSeparator('=').split(mapAsString); + } +} diff --git a/java-collections-maps/src/test/java/com/baeldung/convert/MapToStringUnitTest.java b/java-collections-maps/src/test/java/com/baeldung/convert/MapToStringUnitTest.java new file mode 100644 index 0000000000..d9923e74a0 --- /dev/null +++ b/java-collections-maps/src/test/java/com/baeldung/convert/MapToStringUnitTest.java @@ -0,0 +1,48 @@ +package com.baeldung.convert; + +import org.apache.commons.collections4.MapUtils; +import org.junit.Assert; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.HashMap; +import java.util.Map; + +public class MapToStringUnitTest { + + private Map wordsByKey = new HashMap<>(); + + @BeforeEach + public void setup() { + wordsByKey.clear(); + wordsByKey.put(1, "one"); + wordsByKey.put(2, "two"); + wordsByKey.put(3, "three"); + wordsByKey.put(4, "four"); + } + + @Test + public void givenMap_WhenUsingIteration_ThenResultingMapIsCorrect() { + String mapAsString = MapToString.convertWithIteration(wordsByKey); + Assert.assertEquals("{1=one, 2=two, 3=three, 4=four}", mapAsString); + } + + @Test + public void givenMap_WhenUsingStream_ThenResultingMapIsCorrect() { + String mapAsString = MapToString.convertWithStream(wordsByKey); + Assert.assertEquals("{1=one, 2=two, 3=three, 4=four}", mapAsString); + } + + @Test + public void givenMap_WhenUsingGuava_ThenResultingMapIsCorrect() { + String mapAsString = MapToString.convertWithGuava(wordsByKey); + Assert.assertEquals("1=one,2=two,3=three,4=four", mapAsString); + } + + @Test + public void givenMap_WhenUsingApache_ThenResultingMapIsCorrect() { + String mapAsString = MapToString.convertWithApache(wordsByKey); + Assert.assertEquals("{1=one, 2=two, 3=three, 4=four}", mapAsString); + MapUtils.debugPrint(System.out, "Map as String", wordsByKey); + } +} \ No newline at end of file diff --git a/java-collections-maps/src/test/java/com/baeldung/convert/StringToMapUnitTest.java b/java-collections-maps/src/test/java/com/baeldung/convert/StringToMapUnitTest.java new file mode 100644 index 0000000000..8fb906efd0 --- /dev/null +++ b/java-collections-maps/src/test/java/com/baeldung/convert/StringToMapUnitTest.java @@ -0,0 +1,23 @@ +package com.baeldung.convert; + +import org.junit.Assert; +import org.junit.jupiter.api.Test; + +import java.util.Map; + +public class StringToMapUnitTest { + + @Test + public void givenString_WhenUsingStream_ThenResultingStringIsCorrect() { + Map wordsByKey = StringToMap.convertWithStream("1=one,2=two,3=three,4=four"); + Assert.assertEquals(4, wordsByKey.size()); + Assert.assertEquals("one", wordsByKey.get("1")); + } + + @Test + void givenString_WhenUsingGuava_ThenResultingStringIsCorrect() { + Map wordsByKey = StringToMap.convertWithGuava("1=one,2=two,3=three,4=four"); + Assert.assertEquals(4, wordsByKey.size()); + Assert.assertEquals("one", wordsByKey.get("1")); + } +} \ No newline at end of file diff --git a/java-numbers/pom.xml b/java-numbers/pom.xml index bb63c8cfe1..0f5140ea5e 100644 --- a/java-numbers/pom.xml +++ b/java-numbers/pom.xml @@ -72,16 +72,6 @@ - - org.apache.maven.plugins - maven-surefire-plugin - - - **/*IntegrationTest.java - - true - - org.apache.maven.plugins diff --git a/java-streams/src/test/java/com/baeldung/stream/PeekUnitTest.java b/java-streams/src/test/java/com/baeldung/stream/PeekUnitTest.java new file mode 100644 index 0000000000..a3a2816e9c --- /dev/null +++ b/java-streams/src/test/java/com/baeldung/stream/PeekUnitTest.java @@ -0,0 +1,118 @@ +package com.baeldung.stream; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.StringWriter; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +public class PeekUnitTest { + + private StringWriter out; + + @BeforeEach + void setup() { + out = new StringWriter(); + } + + @Test + void givenStringStream_whenCallingPeekOnly_thenNoElementProcessed() { + // given + Stream nameStream = Stream.of("Alice", "Bob", "Chuck"); + + // when + nameStream.peek(out::append); + + // then + assertThat(out.toString()).isEmpty(); + } + + @Test + void givenStringStream_whenCallingForEachOnly_thenElementsProcessed() { + // given + Stream nameStream = Stream.of("Alice", "Bob", "Chuck"); + + // when + nameStream.forEach(out::append); + + // then + assertThat(out.toString()).isEqualTo("AliceBobChuck"); + } + + @Test + void givenStringStream_whenCallingPeekAndNoopForEach_thenElementsProcessed() { + // given + Stream nameStream = Stream.of("Alice", "Bob", "Chuck"); + + // when + nameStream.peek(out::append) + .forEach(this::noop); + + // then + assertThat(out.toString()).isEqualTo("AliceBobChuck"); + } + + @Test + void givenStringStream_whenCallingPeekAndCollect_thenElementsProcessed() { + // given + Stream nameStream = Stream.of("Alice", "Bob", "Chuck"); + + // when + nameStream.peek(out::append) + .collect(Collectors.toList()); + + // then + assertThat(out.toString()).isEqualTo("AliceBobChuck"); + } + + @Test + void givenStringStream_whenCallingPeekAndForEach_thenElementsProcessedTwice() { + // given + Stream nameStream = Stream.of("Alice", "Bob", "Chuck"); + + // when + nameStream.peek(out::append) + .forEach(out::append); + + // then + assertThat(out.toString()).isEqualTo("AliceAliceBobBobChuckChuck"); + } + + @Test + void givenStringStream_whenCallingPeek_thenElementsProcessedTwice() { + // given + Stream userStream = Stream.of(new User("Alice"), new User("Bob"), new User("Chuck")); + + // when + userStream.peek(u -> u.setName(u.getName().toLowerCase())) + .map(User::getName) + .forEach(out::append); + + // then + assertThat(out.toString()).isEqualTo("alicebobchuck"); + } + + private static class User { + private String name; + + public User(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + } + + private void noop(String s) { + } + +} diff --git a/java-strings/README.md b/java-strings/README.md index 08fbec35ab..b72a378d06 100644 --- a/java-strings/README.md +++ b/java-strings/README.md @@ -49,3 +49,4 @@ - [Add a Character to a String at a Given Position](https://www.baeldung.com/java-add-character-to-string) - [Remove Leading and Trailing Characters from a String](https://www.baeldung.com/java-remove-trailing-characters) - [Concatenating Strings In Java](https://www.baeldung.com/java-strings-concatenation) +- [Java toString() Method](https://www.baeldung.com/java-tostring) diff --git a/java-strings/src/main/java/com/baeldung/string/Pangram.java b/java-strings/src/main/java/com/baeldung/string/Pangram.java new file mode 100644 index 0000000000..c09b0c1d29 --- /dev/null +++ b/java-strings/src/main/java/com/baeldung/string/Pangram.java @@ -0,0 +1,61 @@ +package com.baeldung.string; + +import java.util.Arrays; +import java.util.Map; +import java.util.function.Function; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +public class Pangram { + private static final int ALPHABET_COUNT = 26; + + public static boolean isPangram(String str) { + if (str == null) + return false; + Boolean[] alphabetMarker = new Boolean[ALPHABET_COUNT]; + Arrays.fill(alphabetMarker, false); + int alphabetIndex = 0; + String strUpper = str.toUpperCase(); + for (int i = 0; i < str.length(); i++) { + if ('A' <= strUpper.charAt(i) && strUpper.charAt(i) <= 'Z') { + alphabetIndex = strUpper.charAt(i) - 'A'; + alphabetMarker[alphabetIndex] = true; + } + } + for (boolean index : alphabetMarker) { + if (!index) + return false; + } + return true; + } + + public static boolean isPangramWithStreams(String str) { + if (str == null) + return false; + + // filtered character stream + String strUpper = str.toUpperCase(); + Stream filteredCharStream = strUpper.chars() + .filter(item -> ((item >= 'A' && item <= 'Z'))) + .mapToObj(c -> (char) c); + Map alphabetMap = filteredCharStream.collect(Collectors.toMap(item -> item, k -> Boolean.TRUE, (p1, p2) -> p1)); + + return (alphabetMap.size() == ALPHABET_COUNT); + } + + public static boolean isPerfectPangram(String str) { + if (str == null) + return false; + + // filtered character stream + String strUpper = str.toUpperCase(); + Stream filteredCharStream = strUpper.chars() + .filter(item -> ((item >= 'A' && item <= 'Z'))) + .mapToObj(c -> (char) c); + Map alphabetFrequencyMap = filteredCharStream.collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); + + return (alphabetFrequencyMap.size() == ALPHABET_COUNT && alphabetFrequencyMap.values() + .stream() + .allMatch(item -> item == 1)); + } +} diff --git a/java-strings/src/main/java/com/baeldung/string/tostring/Customer.java b/java-strings/src/main/java/com/baeldung/string/tostring/Customer.java new file mode 100644 index 0000000000..e914a83f0e --- /dev/null +++ b/java-strings/src/main/java/com/baeldung/string/tostring/Customer.java @@ -0,0 +1,19 @@ +package com.baeldung.string.tostring; + +public class Customer { + private String firstName; + private String 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; + } +} diff --git a/java-strings/src/main/java/com/baeldung/string/tostring/CustomerArrayToString.java b/java-strings/src/main/java/com/baeldung/string/tostring/CustomerArrayToString.java new file mode 100644 index 0000000000..1736657276 --- /dev/null +++ b/java-strings/src/main/java/com/baeldung/string/tostring/CustomerArrayToString.java @@ -0,0 +1,19 @@ +package com.baeldung.string.tostring; + +import java.util.Arrays; + +public class CustomerArrayToString extends Customer { + private Order[] orders; + + public Order[] getOrders() { + return orders; + } + public void setOrders(Order[] orders) { + this.orders = orders; + } + @Override + public String toString() { + return "Customer [orders=" + Arrays.toString(orders) + ", getFirstName()=" + getFirstName() + + ", getLastName()=" + getLastName() + "]"; + } +} diff --git a/java-strings/src/main/java/com/baeldung/string/tostring/CustomerComplexObjectToString.java b/java-strings/src/main/java/com/baeldung/string/tostring/CustomerComplexObjectToString.java new file mode 100644 index 0000000000..9bede1b3fc --- /dev/null +++ b/java-strings/src/main/java/com/baeldung/string/tostring/CustomerComplexObjectToString.java @@ -0,0 +1,19 @@ +package com.baeldung.string.tostring; + +public class CustomerComplexObjectToString extends Customer { + private Order order; + + public Order getOrder() { + return order; + } + + public void setOrder(Order order) { + this.order = order; + } + + @Override + public String toString() { + return "Customer [order=" + order + ", getFirstName()=" + getFirstName() + + ", getLastName()=" + getLastName() + "]"; + } +} \ No newline at end of file diff --git a/java-strings/src/main/java/com/baeldung/string/tostring/CustomerPrimitiveToString.java b/java-strings/src/main/java/com/baeldung/string/tostring/CustomerPrimitiveToString.java new file mode 100644 index 0000000000..86e08ca447 --- /dev/null +++ b/java-strings/src/main/java/com/baeldung/string/tostring/CustomerPrimitiveToString.java @@ -0,0 +1,19 @@ +package com.baeldung.string.tostring; + +public class CustomerPrimitiveToString extends Customer { + private long balance; + + public long getBalance() { + return balance; + } + + public void setBalance(long balance) { + this.balance = balance; + } + + @Override + public String toString() { + return "Customer [balance=" + balance + ", getFirstName()=" + getFirstName() + + ", getLastName()=" + getLastName() + "]"; + } +} diff --git a/java-strings/src/main/java/com/baeldung/string/tostring/CustomerReflectionToString.java b/java-strings/src/main/java/com/baeldung/string/tostring/CustomerReflectionToString.java new file mode 100644 index 0000000000..2da1163c63 --- /dev/null +++ b/java-strings/src/main/java/com/baeldung/string/tostring/CustomerReflectionToString.java @@ -0,0 +1,41 @@ +package com.baeldung.string.tostring; + +import java.util.List; + +import org.apache.commons.lang3.builder.ReflectionToStringBuilder; + +public class CustomerReflectionToString extends Customer{ + + private Integer score; + private List orders; + private StringBuffer fullname; + + public Integer getScore() { + return score; + } + + public void setScore(Integer score) { + this.score = score; + } + + public List getOrders() { + return orders; + } + + public void setOrders(List orders) { + this.orders = orders; + } + + public StringBuffer getFullname() { + return fullname; + } + + public void setFullname(StringBuffer fullname) { + this.fullname = fullname; + } + + @Override + public String toString() { + return ReflectionToStringBuilder.toString(this); + } +} diff --git a/java-strings/src/main/java/com/baeldung/string/tostring/CustomerWrapperCollectionToString.java b/java-strings/src/main/java/com/baeldung/string/tostring/CustomerWrapperCollectionToString.java new file mode 100644 index 0000000000..6c7b999045 --- /dev/null +++ b/java-strings/src/main/java/com/baeldung/string/tostring/CustomerWrapperCollectionToString.java @@ -0,0 +1,39 @@ +package com.baeldung.string.tostring; + +import java.util.List; + +public class CustomerWrapperCollectionToString extends Customer { + private Integer score; + private List orders; + private StringBuffer fullname; + + public Integer getScore() { + return score; + } + + public void setScore(Integer score) { + this.score = score; + } + + public List getOrders() { + return orders; + } + + public void setOrders(List orders) { + this.orders = orders; + } + + public StringBuffer getFullname() { + return fullname; + } + + public void setFullname(StringBuffer fullname) { + this.fullname = fullname; + } + + @Override + public String toString() { + return "Customer [score=" + score + ", orders=" + orders + ", fullname=" + fullname + + ", getFirstName()=" + getFirstName() + ", getLastName()=" + getLastName() + "]"; + } +} diff --git a/java-strings/src/main/java/com/baeldung/string/tostring/Order.java b/java-strings/src/main/java/com/baeldung/string/tostring/Order.java new file mode 100644 index 0000000000..017e2d9bc8 --- /dev/null +++ b/java-strings/src/main/java/com/baeldung/string/tostring/Order.java @@ -0,0 +1,46 @@ +package com.baeldung.string.tostring; + +public class Order { + + private String orderId; + private String desc; + private long value; + private String status; + + public String getOrderId() { + return orderId; + } + + public void setOrderId(String orderId) { + this.orderId = orderId; + } + + public String getDesc() { + return desc; + } + + public void setDesc(String desc) { + this.desc = desc; + } + + public long getValue() { + return value; + } + + public void setValue(long value) { + this.value = value; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + @Override + public String toString() { + return "Order [orderId=" + orderId + ", desc=" + desc + ", value=" + value + "]"; + } + +} diff --git a/java-strings/src/test/java/com/baeldung/string/PangramUnitTest.java b/java-strings/src/test/java/com/baeldung/string/PangramUnitTest.java new file mode 100644 index 0000000000..36e603b535 --- /dev/null +++ b/java-strings/src/test/java/com/baeldung/string/PangramUnitTest.java @@ -0,0 +1,43 @@ +package com.baeldung.string; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import org.junit.Test; + +public class PangramUnitTest { + + @Test + public void givenValidString_isPangram_shouldReturnSuccess() { + String input = "Two driven jocks help fax my big quiz"; + assertTrue(Pangram.isPangram(input)); + assertTrue(Pangram.isPangramWithStreams(input)); + } + + @Test + public void givenNullString_isPangram_shouldReturnFailure() { + String input = null; + assertFalse(Pangram.isPangram(input)); + assertFalse(Pangram.isPangramWithStreams(input)); + assertFalse(Pangram.isPerfectPangram(input)); + } + + @Test + public void givenPerfectPangramString_isPerfectPangram_shouldReturnSuccess() { + String input = "abcdefghijklmNoPqrStuVwxyz"; + assertTrue(Pangram.isPerfectPangram(input)); + } + + @Test + public void givenNonPangramString_isPangram_shouldReturnFailure() { + String input = "invalid pangram"; + assertFalse(Pangram.isPangram(input)); + assertFalse(Pangram.isPangramWithStreams(input)); + } + + @Test + public void givenPangram_isPerfectPangram_shouldReturnFailure() { + String input = "Two driven jocks help fax my big quiz"; + assertFalse(Pangram.isPerfectPangram(input)); + } + +} diff --git a/java-strings/src/test/java/com/baeldung/string/StringReplaceAndRemoveUnitTest.java b/java-strings/src/test/java/com/baeldung/string/StringReplaceAndRemoveUnitTest.java index d952d2383b..4d2b54241b 100644 --- a/java-strings/src/test/java/com/baeldung/string/StringReplaceAndRemoveUnitTest.java +++ b/java-strings/src/test/java/com/baeldung/string/StringReplaceAndRemoveUnitTest.java @@ -1,7 +1,7 @@ package com.baeldung.string; - import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.RegExUtils; import org.junit.Test; import static org.junit.Assert.assertFalse; @@ -9,7 +9,6 @@ import static org.junit.Assert.assertTrue; public class StringReplaceAndRemoveUnitTest { - @Test public void givenTestStrings_whenReplace_thenProcessedString() { @@ -26,7 +25,7 @@ public class StringReplaceAndRemoveUnitTest { public void givenTestStrings_whenReplaceAll_thenProcessedString() { String master2 = "Welcome to Baeldung, Hello World Baeldung"; - String regexTarget= "(Baeldung)$"; + String regexTarget = "(Baeldung)$"; String replacement = "Java"; String processed2 = master2.replaceAll(regexTarget, replacement); assertTrue(processed2.endsWith("Java")); @@ -45,18 +44,16 @@ public class StringReplaceAndRemoveUnitTest { StringBuilder builder = new StringBuilder(master); - builder.delete(startIndex, stopIndex); - assertFalse(builder.toString().contains(target)); - + assertFalse(builder.toString() + .contains(target)); builder.replace(startIndex, stopIndex, replacement); - assertTrue(builder.toString().contains(replacement)); - + assertTrue(builder.toString() + .contains(replacement)); } - @Test public void givenTestStrings_whenStringUtilsMethods_thenProcessedStrings() { @@ -74,10 +71,20 @@ public class StringReplaceAndRemoveUnitTest { } + @Test + public void givenTestStrings_whenReplaceExactWord_thenProcessedString() { + String sentence = "A car is not the same as a carriage, and some planes can carry cars inside them!"; + String regexTarget = "\\bcar\\b"; + String exactWordReplaced = sentence.replaceAll(regexTarget, "truck"); + assertTrue("A truck is not the same as a carriage, and some planes can carry cars inside them!".equals(exactWordReplaced)); + } - - - - + @Test + public void givenTestStrings_whenReplaceExactWordUsingRegExUtilsMethod_thenProcessedString() { + String sentence = "A car is not the same as a carriage, and some planes can carry cars inside them!"; + String regexTarget = "\\bcar\\b"; + String exactWordReplaced = RegExUtils.replaceAll(sentence, regexTarget, "truck"); + assertTrue("A truck is not the same as a carriage, and some planes can carry cars inside them!".equals(exactWordReplaced)); + } } diff --git a/java-strings/src/test/java/com/baeldung/string/tostring/CustomerArrayToStringUnitTest.java b/java-strings/src/test/java/com/baeldung/string/tostring/CustomerArrayToStringUnitTest.java new file mode 100644 index 0000000000..9a88416179 --- /dev/null +++ b/java-strings/src/test/java/com/baeldung/string/tostring/CustomerArrayToStringUnitTest.java @@ -0,0 +1,26 @@ +package com.baeldung.string.tostring; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Test; + +public class CustomerArrayToStringUnitTest { + private static final String CUSTOMER_ARRAY_TO_STRING + = "Customer [orders=[Order [orderId=A1111, desc=Game, value=0]], getFirstName()=Rajesh, getLastName()=Bhojwani]"; + + @Test + public void givenArray_whenToString_thenCustomerDetails() { + CustomerArrayToString customer = new CustomerArrayToString(); + customer.setFirstName("Rajesh"); + customer.setLastName("Bhojwani"); + Order[] orders = new Order[1]; + orders[0] = new Order(); + orders[0].setOrderId("A1111"); + orders[0].setDesc("Game"); + orders[0].setStatus("In-Shiping"); + customer.setOrders(orders); + + assertEquals(CUSTOMER_ARRAY_TO_STRING, customer.toString()); + } + +} diff --git a/java-strings/src/test/java/com/baeldung/string/tostring/CustomerComplexObjectToStringUnitTest.java b/java-strings/src/test/java/com/baeldung/string/tostring/CustomerComplexObjectToStringUnitTest.java new file mode 100644 index 0000000000..5ffb0d0e58 --- /dev/null +++ b/java-strings/src/test/java/com/baeldung/string/tostring/CustomerComplexObjectToStringUnitTest.java @@ -0,0 +1,25 @@ +package com.baeldung.string.tostring; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Test; + +public class CustomerComplexObjectToStringUnitTest { + private static final String CUSTOMER_COMPLEX_TO_STRING + = "Customer [order=Order [orderId=A1111, desc=Game, value=0], getFirstName()=Rajesh, getLastName()=Bhojwani]"; + + @Test + public void givenComplex_whenToString_thenCustomerDetails() { + CustomerComplexObjectToString customer = new CustomerComplexObjectToString(); + customer.setFirstName("Rajesh"); + customer.setLastName("Bhojwani"); + Order order = new Order(); + order.setOrderId("A1111"); + order.setDesc("Game"); + order.setStatus("In-Shiping"); + customer.setOrder(order); + + assertEquals(CUSTOMER_COMPLEX_TO_STRING, customer.toString()); + } + +} diff --git a/java-strings/src/test/java/com/baeldung/string/tostring/CustomerPrimitiveToStringUnitTest.java b/java-strings/src/test/java/com/baeldung/string/tostring/CustomerPrimitiveToStringUnitTest.java new file mode 100644 index 0000000000..d43733bc60 --- /dev/null +++ b/java-strings/src/test/java/com/baeldung/string/tostring/CustomerPrimitiveToStringUnitTest.java @@ -0,0 +1,22 @@ +package com.baeldung.string.tostring; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Test; + +public class CustomerPrimitiveToStringUnitTest { + + private static final String CUSTOMER_PRIMITIVE_TO_STRING + = "Customer [balance=110, getFirstName()=Rajesh, getLastName()=Bhojwani]"; + + @Test + public void givenPrimitive_whenToString_thenCustomerDetails() { + CustomerPrimitiveToString customer = new CustomerPrimitiveToString(); + customer.setFirstName("Rajesh"); + customer.setLastName("Bhojwani"); + customer.setBalance(110); + + assertEquals(CUSTOMER_PRIMITIVE_TO_STRING, customer.toString()); + } +} + diff --git a/java-strings/src/test/java/com/baeldung/string/tostring/CustomerWrapperCollectionToStringUnitTest.java b/java-strings/src/test/java/com/baeldung/string/tostring/CustomerWrapperCollectionToStringUnitTest.java new file mode 100644 index 0000000000..e04512ff75 --- /dev/null +++ b/java-strings/src/test/java/com/baeldung/string/tostring/CustomerWrapperCollectionToStringUnitTest.java @@ -0,0 +1,33 @@ +package com.baeldung.string.tostring; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.jupiter.api.Test; + +public class CustomerWrapperCollectionToStringUnitTest { + private static final String CUSTOMER_WRAPPER_COLLECTION_TO_STRING + = "Customer [score=8, orders=[Book, Pen], fullname=Bhojwani, Rajesh, getFirstName()=Rajesh, getLastName()=Bhojwani]"; + + @Test + public void givenWrapperCollectionStrBuffer_whenToString_thenCustomerDetails() { + CustomerWrapperCollectionToString customer = new CustomerWrapperCollectionToString(); + customer.setFirstName("Rajesh"); + customer.setLastName("Bhojwani"); + customer.setScore(8); + + List orders = new ArrayList(); + orders.add("Book"); + orders.add("Pen"); + customer.setOrders(orders); + + StringBuffer fullname = new StringBuffer(); + fullname.append(customer.getLastName()+", "+ customer.getFirstName()); + customer.setFullname(fullname); + + assertEquals(CUSTOMER_WRAPPER_COLLECTION_TO_STRING, customer.toString()); + } + +} diff --git a/kotlin-libraries/pom.xml b/kotlin-libraries/pom.xml index ae77a9aa2d..507e5820d4 100644 --- a/kotlin-libraries/pom.xml +++ b/kotlin-libraries/pom.xml @@ -95,6 +95,23 @@ 0.7.3 + + uy.kohesive.kovert + kovert-vertx + [1.5.0,1.6.0) + + + nl.komponents.kovenant + kovenant + + + + + nl.komponents.kovenant + kovenant + 3.3.0 + pom + @@ -110,4 +127,4 @@ 0.10.4 - \ No newline at end of file + diff --git a/core-kotlin/src/main/kotlin/com/baeldung/kovert/AnnotatedServer.kt b/kotlin-libraries/src/main/kotlin/com/baeldung/kovert/AnnotatedServer.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/kovert/AnnotatedServer.kt rename to kotlin-libraries/src/main/kotlin/com/baeldung/kovert/AnnotatedServer.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/kovert/ErrorServer.kt b/kotlin-libraries/src/main/kotlin/com/baeldung/kovert/ErrorServer.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/kovert/ErrorServer.kt rename to kotlin-libraries/src/main/kotlin/com/baeldung/kovert/ErrorServer.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/kovert/JsonServer.kt b/kotlin-libraries/src/main/kotlin/com/baeldung/kovert/JsonServer.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/kovert/JsonServer.kt rename to kotlin-libraries/src/main/kotlin/com/baeldung/kovert/JsonServer.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/kovert/NoopServer.kt b/kotlin-libraries/src/main/kotlin/com/baeldung/kovert/NoopServer.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/kovert/NoopServer.kt rename to kotlin-libraries/src/main/kotlin/com/baeldung/kovert/NoopServer.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/kovert/SecuredServer.kt b/kotlin-libraries/src/main/kotlin/com/baeldung/kovert/SecuredServer.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/kovert/SecuredServer.kt rename to kotlin-libraries/src/main/kotlin/com/baeldung/kovert/SecuredServer.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/kovert/SimpleServer.kt b/kotlin-libraries/src/main/kotlin/com/baeldung/kovert/SimpleServer.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/kovert/SimpleServer.kt rename to kotlin-libraries/src/main/kotlin/com/baeldung/kovert/SimpleServer.kt diff --git a/core-kotlin/src/main/resources/kovert.conf b/kotlin-libraries/src/main/resources/kovert.conf similarity index 100% rename from core-kotlin/src/main/resources/kovert.conf rename to kotlin-libraries/src/main/resources/kovert.conf diff --git a/libraries-data/src/main/kafka-connect/04_Custom/connect-distributed.properties b/libraries-data/src/main/kafka-connect/04_Custom/connect-distributed.properties deleted file mode 100644 index 5b91baddbd..0000000000 --- a/libraries-data/src/main/kafka-connect/04_Custom/connect-distributed.properties +++ /dev/null @@ -1,88 +0,0 @@ -## -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You under the Apache License, Version 2.0 -# (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -## - -# This file contains some of the configurations for the Kafka Connect distributed worker. This file is intended -# to be used with the examples, and some settings may differ from those used in a production system, especially -# the `bootstrap.servers` and those specifying replication factors. - -# A list of host/port pairs to use for establishing the initial connection to the Kafka cluster. -bootstrap.servers=localhost:9092 - -# unique name for the cluster, used in forming the Connect cluster group. Note that this must not conflict with consumer group IDs -group.id=connect-cluster - -# The converters specify the format of data in Kafka and how to translate it into Connect data. Every Connect user will -# need to configure these based on the format they want their data in when loaded from or stored into Kafka -key.converter=org.apache.kafka.connect.json.JsonConverter -value.converter=org.apache.kafka.connect.json.JsonConverter -# Converter-specific settings can be passed in by prefixing the Converter's setting with the converter we want to apply -# it to -key.converter.schemas.enable=true -value.converter.schemas.enable=true - -# Topic to use for storing offsets. This topic should have many partitions and be replicated and compacted. -# Kafka Connect will attempt to create the topic automatically when needed, but you can always manually create -# the topic before starting Kafka Connect if a specific topic configuration is needed. -# Most users will want to use the built-in default replication factor of 3 or in some cases even specify a larger value. -# Since this means there must be at least as many brokers as the maximum replication factor used, we'd like to be able -# to run this example on a single-broker cluster and so here we instead set the replication factor to 1. -offset.storage.topic=connect-offsets -offset.storage.replication.factor=1 -#offset.storage.partitions=25 - -# Topic to use for storing connector and task configurations; note that this should be a single partition, highly replicated, -# and compacted topic. Kafka Connect will attempt to create the topic automatically when needed, but you can always manually create -# the topic before starting Kafka Connect if a specific topic configuration is needed. -# Most users will want to use the built-in default replication factor of 3 or in some cases even specify a larger value. -# Since this means there must be at least as many brokers as the maximum replication factor used, we'd like to be able -# to run this example on a single-broker cluster and so here we instead set the replication factor to 1. -config.storage.topic=connect-configs -config.storage.replication.factor=1 - -# Topic to use for storing statuses. This topic can have multiple partitions and should be replicated and compacted. -# Kafka Connect will attempt to create the topic automatically when needed, but you can always manually create -# the topic before starting Kafka Connect if a specific topic configuration is needed. -# Most users will want to use the built-in default replication factor of 3 or in some cases even specify a larger value. -# Since this means there must be at least as many brokers as the maximum replication factor used, we'd like to be able -# to run this example on a single-broker cluster and so here we instead set the replication factor to 1. -status.storage.topic=connect-status -status.storage.replication.factor=1 -#status.storage.partitions=5 - -# Flush much faster than normal, which is useful for testing/debugging -offset.flush.interval.ms=10000 - -# These are provided to inform the user about the presence of the REST host and port configs -# Hostname & Port for the REST API to listen on. If this is set, it will bind to the interface used to listen to requests. -#rest.host.name= -#rest.port=8083 - -# The Hostname & Port that will be given out to other workers to connect to i.e. URLs that are routable from other servers. -#rest.advertised.host.name= -#rest.advertised.port= - -# Set to a list of filesystem paths separated by commas (,) to enable class loading isolation for plugins -# (connectors, converters, transformations). The list should consist of top level directories that include -# any combination of: -# a) directories immediately containing jars with plugins and their dependencies -# b) uber-jars with plugins and their dependencies -# c) directories immediately containing the package directory structure of classes of plugins and their dependencies -# Examples: -# plugin.path=/usr/local/share/java,/usr/local/share/kafka/plugins,/opt/connectors, -# Replace the relative path below with an absolute path if you are planning to start Kafka Connect from within a -# directory other than the home directory of Confluent Platform. -plugin.path=./share/java diff --git a/libraries-data/src/main/kafka-connect/04_Custom/connect-mongodb-sink.json b/libraries-data/src/main/kafka-connect/04_Custom/connect-mongodb-sink.json index 333768e4b7..852f400fc6 100644 --- a/libraries-data/src/main/kafka-connect/04_Custom/connect-mongodb-sink.json +++ b/libraries-data/src/main/kafka-connect/04_Custom/connect-mongodb-sink.json @@ -1,22 +1,14 @@ { - "firstName": "John", - "lastName": "Smith", - "age": 25, - "address": { - "streetAddress": "21 2nd Street", - "city": "New York", - "state": "NY", - "postalCode": "10021" - }, - "phoneNumber": [{ - "type": "home", - "number": "212 555-1234" - }, { - "type": "fax", - "number": "646 555-4567" - } - ], - "gender": { - "type": "male" + "name": "mongodb-sink", + "config": { + "connector.class": "at.grahsl.kafka.connect.mongodb.MongoDbSinkConnector", + "tasks.max": 1, + "topics": "connect-custom", + "mongodb.connection.uri": "mongodb://mongo-db/test?retryWrites=true", + "mongodb.collection": "MyCollection", + "key.converter": "org.apache.kafka.connect.json.JsonConverter", + "key.converter.schemas.enable": false, + "value.converter": "org.apache.kafka.connect.json.JsonConverter", + "value.converter.schemas.enable": false } } diff --git a/libraries-data/src/main/kafka-connect/04_Custom/connect-mqtt-source.json b/libraries-data/src/main/kafka-connect/04_Custom/connect-mqtt-source.json index 02d87c5ad7..c76d326c0a 100644 --- a/libraries-data/src/main/kafka-connect/04_Custom/connect-mqtt-source.json +++ b/libraries-data/src/main/kafka-connect/04_Custom/connect-mqtt-source.json @@ -3,9 +3,11 @@ "config": { "connector.class": "io.confluent.connect.mqtt.MqttSourceConnector", "tasks.max": 1, - "mqtt.server.uri": "ws://broker.hivemq.com:8000/mqtt", + "mqtt.server.uri": "tcp://mosquitto:1883", "mqtt.topics": "baeldung", "kafka.topic": "connect-custom", - "value.converter": "org.apache.kafka.connect.converters.ByteArrayConverter" + "value.converter": "org.apache.kafka.connect.converters.ByteArrayConverter", + "confluent.topic.bootstrap.servers": "kafka:9092", + "confluent.topic.replication.factor": 1 } -} +} \ No newline at end of file diff --git a/libraries-data/src/main/kafka-connect/04_Custom/docker-compose.yaml b/libraries-data/src/main/kafka-connect/04_Custom/docker-compose.yaml new file mode 100644 index 0000000000..26cd653335 --- /dev/null +++ b/libraries-data/src/main/kafka-connect/04_Custom/docker-compose.yaml @@ -0,0 +1,94 @@ +version: '3.3' + +services: + mosquitto: + image: eclipse-mosquitto:1.5.5 + hostname: mosquitto + container_name: mosquitto + expose: + - "1883" + ports: + - "1883:1883" + zookeeper: + image: zookeeper:3.4.9 + restart: unless-stopped + hostname: zookeeper + container_name: zookeeper + ports: + - "2181:2181" + environment: + ZOO_MY_ID: 1 + ZOO_PORT: 2181 + ZOO_SERVERS: server.1=zookeeper:2888:3888 + volumes: + - ./zookeeper/data:/data + - ./zookeeper/datalog:/datalog + kafka: + image: confluentinc/cp-kafka:5.1.0 + hostname: kafka + container_name: kafka + ports: + - "9092:9092" + environment: + KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT + KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka:9092,PLAINTEXT_HOST://localhost:29092 + KAFKA_ZOOKEEPER_CONNECT: "zookeeper:2181" + KAFKA_BROKER_ID: 1 + KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1 + volumes: + - ./kafka/data:/var/lib/kafka/data + depends_on: + - zookeeper + kafka-connect: + image: confluentinc/cp-kafka-connect:5.1.0 + hostname: kafka-connect + container_name: kafka-connect + ports: + - "8083:8083" + environment: + CONNECT_BOOTSTRAP_SERVERS: "kafka:9092" + CONNECT_REST_ADVERTISED_HOST_NAME: connect + CONNECT_REST_PORT: 8083 + CONNECT_GROUP_ID: compose-connect-group + CONNECT_CONFIG_STORAGE_TOPIC: docker-connect-configs + CONNECT_OFFSET_STORAGE_TOPIC: docker-connect-offsets + CONNECT_STATUS_STORAGE_TOPIC: docker-connect-status + CONNECT_KEY_CONVERTER: org.apache.kafka.connect.json.JsonConverter + CONNECT_VALUE_CONVERTER: org.apache.kafka.connect.json.JsonConverter + CONNECT_INTERNAL_KEY_CONVERTER: "org.apache.kafka.connect.json.JsonConverter" + CONNECT_INTERNAL_VALUE_CONVERTER: "org.apache.kafka.connect.json.JsonConverter" + CONNECT_CONFIG_STORAGE_REPLICATION_FACTOR: "1" + CONNECT_OFFSET_STORAGE_REPLICATION_FACTOR: "1" + CONNECT_STATUS_STORAGE_REPLICATION_FACTOR: "1" + CONNECT_PLUGIN_PATH: '/usr/share/java,/etc/kafka-connect/jars' + CONNECT_CONFLUENT_TOPIC_REPLICATION_FACTOR: 1 + volumes: + - /tmp/custom/jars:/etc/kafka-connect/jars + depends_on: + - zookeeper + - kafka + - mosquitto + mongo-db: + image: mongo:4.0.5 + hostname: mongo-db + container_name: mongo-db + expose: + - "27017" + ports: + - "27017:27017" + command: --bind_ip_all --smallfiles + volumes: + - ./mongo-db:/data + mongoclient: + image: mongoclient/mongoclient:2.2.0 + container_name: mongoclient + hostname: mongoclient + depends_on: + - mongo-db + ports: + - 3000:3000 + environment: + MONGO_URL: "mongodb://mongo-db:27017" + PORT: 3000 + expose: + - "3000" \ No newline at end of file diff --git a/parent-java/pom.xml b/parent-java/pom.xml index 86be34d508..8f603b2d09 100644 --- a/parent-java/pom.xml +++ b/parent-java/pom.xml @@ -24,7 +24,7 @@ - 22.0 + 23.0 - \ No newline at end of file + diff --git a/parent-spring-5/pom.xml b/parent-spring-5/pom.xml index 6a15f38884..51a2c1fd1f 100644 --- a/parent-spring-5/pom.xml +++ b/parent-spring-5/pom.xml @@ -29,11 +29,11 @@ - 5.0.6.RELEASE + 5.1.2.RELEASE 5.0.2 2.9.6 2.9.6 - 5.0.6.RELEASE + 5.1.2.RELEASE \ No newline at end of file diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/exception/EntityWithNoId.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/exception/EntityWithNoId.java new file mode 100644 index 0000000000..989fa1281a --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/exception/EntityWithNoId.java @@ -0,0 +1,16 @@ +package com.baeldung.hibernate.exception; + +import javax.persistence.Entity; + +@Entity +public class EntityWithNoId { + private int id; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/exception/HibernateUtil.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/exception/HibernateUtil.java new file mode 100644 index 0000000000..ae5174ac9c --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/exception/HibernateUtil.java @@ -0,0 +1,63 @@ +package com.baeldung.hibernate.exception; + +import java.io.FileInputStream; +import java.io.IOException; +import java.net.URL; +import java.util.Properties; + +import org.apache.commons.lang3.StringUtils; +import org.hibernate.SessionFactory; +import org.hibernate.boot.Metadata; +import org.hibernate.boot.MetadataSources; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.service.ServiceRegistry; + +public class HibernateUtil { + private static SessionFactory sessionFactory; + private static String PROPERTY_FILE_NAME; + + public static SessionFactory getSessionFactory() throws IOException { + return getSessionFactory(null); + } + + public static SessionFactory getSessionFactory(String propertyFileName) + throws IOException { + PROPERTY_FILE_NAME = propertyFileName; + if (sessionFactory == null) { + ServiceRegistry serviceRegistry = configureServiceRegistry(); + sessionFactory = makeSessionFactory(serviceRegistry); + } + return sessionFactory; + } + + private static SessionFactory makeSessionFactory( + ServiceRegistry serviceRegistry) { + MetadataSources metadataSources = new MetadataSources(serviceRegistry); + metadataSources.addAnnotatedClass(Product.class); + Metadata metadata = metadataSources.getMetadataBuilder() + .build(); + return metadata.getSessionFactoryBuilder() + .build(); + + } + + private static ServiceRegistry configureServiceRegistry() + throws IOException { + Properties properties = getProperties(); + return new StandardServiceRegistryBuilder().applySettings(properties) + .build(); + } + + private static Properties getProperties() throws IOException { + Properties properties = new Properties(); + URL propertiesURL = Thread.currentThread() + .getContextClassLoader() + .getResource(StringUtils.defaultString(PROPERTY_FILE_NAME, + "hibernate-exception.properties")); + try (FileInputStream inputStream = new FileInputStream( + propertiesURL.getFile())) { + properties.load(inputStream); + } + return properties; + } +} \ No newline at end of file diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/exception/Product.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/exception/Product.java new file mode 100644 index 0000000000..031fa38de0 --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/exception/Product.java @@ -0,0 +1,40 @@ +package com.baeldung.hibernate.exception; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; + +@Entity +public class Product { + + private int id; + + private String name; + private String description; + + @Id + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + @Column(nullable=false) + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } +} diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/exception/HibernateExceptionUnitTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/exception/HibernateExceptionUnitTest.java new file mode 100644 index 0000000000..3581c81daa --- /dev/null +++ b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/exception/HibernateExceptionUnitTest.java @@ -0,0 +1,425 @@ +package com.baeldung.hibernate.exception; + +import static org.hamcrest.CoreMatchers.isA; +import static org.junit.Assert.assertNotNull; + +import java.io.IOException; +import java.util.List; + +import javax.persistence.OptimisticLockException; +import javax.persistence.PersistenceException; + +import org.hibernate.AnnotationException; +import org.hibernate.HibernateException; +import org.hibernate.MappingException; +import org.hibernate.NonUniqueObjectException; +import org.hibernate.PropertyValueException; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.StaleObjectStateException; +import org.hibernate.StaleStateException; +import org.hibernate.Transaction; +import org.hibernate.TransactionException; +import org.hibernate.cfg.AvailableSettings; +import org.hibernate.cfg.Configuration; +import org.hibernate.exception.ConstraintViolationException; +import org.hibernate.exception.DataException; +import org.hibernate.exception.SQLGrammarException; +import org.hibernate.query.NativeQuery; +import org.hibernate.tool.schema.spi.CommandAcceptanceException; +import org.hibernate.tool.schema.spi.SchemaManagementException; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class HibernateExceptionUnitTest { + + private static final Logger logger = LoggerFactory + .getLogger(HibernateExceptionUnitTest.class); + private SessionFactory sessionFactory; + + @Before + public void setUp() throws IOException { + sessionFactory = HibernateUtil.getSessionFactory(); + } + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + private Configuration getConfiguration() { + Configuration cfg = new Configuration(); + cfg.setProperty(AvailableSettings.DIALECT, + "org.hibernate.dialect.H2Dialect"); + cfg.setProperty(AvailableSettings.HBM2DDL_AUTO, "none"); + cfg.setProperty(AvailableSettings.DRIVER, "org.h2.Driver"); + cfg.setProperty(AvailableSettings.URL, + "jdbc:h2:mem:myexceptiondb2;DB_CLOSE_DELAY=-1"); + cfg.setProperty(AvailableSettings.USER, "sa"); + cfg.setProperty(AvailableSettings.PASS, ""); + return cfg; + } + + @Test + public void whenQueryExecutedWithUnmappedEntity_thenMappingException() { + thrown.expectCause(isA(MappingException.class)); + thrown.expectMessage("Unknown entity: java.lang.String"); + + Session session = sessionFactory.openSession(); + NativeQuery query = session + .createNativeQuery("select name from PRODUCT", String.class); + query.getResultList(); + } + + @Test + @SuppressWarnings("rawtypes") + public void whenQueryExecuted_thenOK() { + Session session = sessionFactory.openSession(); + NativeQuery query = session + .createNativeQuery("select name from PRODUCT"); + List results = query.getResultList(); + assertNotNull(results); + } + + @Test + public void givenEntityWithoutId_whenSessionFactoryCreated_thenAnnotationException() { + thrown.expect(AnnotationException.class); + thrown.expectMessage("No identifier specified for entity"); + + Configuration cfg = getConfiguration(); + cfg.addAnnotatedClass(EntityWithNoId.class); + cfg.buildSessionFactory(); + } + + @Test + public void givenMissingTable_whenSchemaValidated_thenSchemaManagementException() { + thrown.expect(SchemaManagementException.class); + thrown.expectMessage("Schema-validation: missing table"); + + Configuration cfg = getConfiguration(); + cfg.setProperty(AvailableSettings.HBM2DDL_AUTO, "validate"); + cfg.addAnnotatedClass(Product.class); + cfg.buildSessionFactory(); + } + + @Test + public void whenWrongDialectSpecified_thenCommandAcceptanceException() { + thrown.expect(SchemaManagementException.class); + thrown.expectCause(isA(CommandAcceptanceException.class)); + thrown.expectMessage("Halting on error : Error executing DDL"); + + Configuration cfg = getConfiguration(); + cfg.setProperty(AvailableSettings.DIALECT, + "org.hibernate.dialect.MySQLDialect"); + cfg.setProperty(AvailableSettings.HBM2DDL_AUTO, "update"); + + // This does not work due to hibernate bug + // cfg.setProperty(AvailableSettings.HBM2DDL_HALT_ON_ERROR,"true"); + cfg.getProperties() + .put(AvailableSettings.HBM2DDL_HALT_ON_ERROR, true); + + cfg.addAnnotatedClass(Product.class); + cfg.buildSessionFactory(); + } + + @Test + public void givenMissingTable_whenEntitySaved_thenSQLGrammarException() { + thrown.expect(isA(PersistenceException.class)); + thrown.expectCause(isA(SQLGrammarException.class)); + thrown + .expectMessage("SQLGrammarException: could not prepare statement"); + + Configuration cfg = getConfiguration(); + cfg.addAnnotatedClass(Product.class); + + SessionFactory sessionFactory = cfg.buildSessionFactory(); + Session session = null; + Transaction transaction = null; + try { + + session = sessionFactory.openSession(); + transaction = session.beginTransaction(); + Product product = new Product(); + product.setId(1); + product.setName("Product 1"); + session.save(product); + transaction.commit(); + } catch (Exception e) { + rollbackTransactionQuietly(transaction); + throw (e); + } finally { + closeSessionQuietly(session); + closeSessionFactoryQuietly(sessionFactory); + } + } + + @Test + public void givenMissingTable_whenQueryExecuted_thenSQLGrammarException() { + thrown.expect(isA(PersistenceException.class)); + thrown.expectCause(isA(SQLGrammarException.class)); + thrown + .expectMessage("SQLGrammarException: could not prepare statement"); + + Session session = sessionFactory.openSession(); + NativeQuery query = session.createNativeQuery( + "select * from NON_EXISTING_TABLE", Product.class); + query.getResultList(); + } + + @Test + public void whenDuplicateIdSaved_thenConstraintViolationException() { + thrown.expect(isA(PersistenceException.class)); + thrown.expectCause(isA(ConstraintViolationException.class)); + thrown.expectMessage( + "ConstraintViolationException: could not execute statement"); + + Session session = null; + Transaction transaction = null; + + for (int i = 1; i <= 2; i++) { + try { + session = sessionFactory.openSession(); + transaction = session.beginTransaction(); + Product product = new Product(); + product.setId(1); + product.setName("Product " + i); + session.save(product); + transaction.commit(); + } catch (Exception e) { + rollbackTransactionQuietly(transaction); + throw (e); + } finally { + closeSessionQuietly(session); + } + } + } + + @Test + public void givenNotNullPropertyNotSet_whenEntityIdSaved_thenPropertyValueException() { + thrown.expect(isA(PropertyValueException.class)); + thrown.expectMessage( + "not-null property references a null or transient value"); + + Session session = null; + Transaction transaction = null; + + try { + session = sessionFactory.openSession(); + transaction = session.beginTransaction(); + + Product product = new Product(); + product.setId(1); + session.save(product); + transaction.commit(); + } catch (Exception e) { + rollbackTransactionQuietly(transaction); + throw (e); + } finally { + closeSessionQuietly(session); + } + + } + + @Test + public void givenQueryWithDataTypeMismatch_WhenQueryExecuted_thenDataException() { + thrown.expectCause(isA(DataException.class)); + thrown.expectMessage( + "org.hibernate.exception.DataException: could not prepare statement"); + + Session session = sessionFactory.openSession(); + NativeQuery query = session.createNativeQuery( + "select * from PRODUCT where id='wrongTypeId'", Product.class); + query.getResultList(); + } + + @Test + public void givenSessionContainingAnId_whenIdAssociatedAgain_thenNonUniqueObjectException() { + thrown.expect(isA(NonUniqueObjectException.class)); + thrown.expectMessage( + "A different object with the same identifier value was already associated with the session"); + + Session session = null; + Transaction transaction = null; + + try { + session = sessionFactory.openSession(); + transaction = session.beginTransaction(); + + Product product1 = new Product(); + product1.setId(1); + product1.setName("Product 1"); + session.save(product1); + + Product product2 = new Product(); + product2.setId(1); + product2.setName("Product 2"); + session.save(product2); + + transaction.commit(); + } catch (Exception e) { + rollbackTransactionQuietly(transaction); + throw (e); + } finally { + closeSessionQuietly(session); + } + } + + @Test + public void whenDeletingADeletedObject_thenOptimisticLockException() { + thrown.expect(isA(OptimisticLockException.class)); + thrown.expectMessage( + "Batch update returned unexpected row count from update"); + thrown.expectCause(isA(StaleStateException.class)); + + Session session = null; + Transaction transaction = null; + + try { + session = sessionFactory.openSession(); + transaction = session.beginTransaction(); + + Product product1 = new Product(); + product1.setId(12); + product1.setName("Product 12"); + session.save(product1); + transaction.commit(); + session.close(); + + session = sessionFactory.openSession(); + transaction = session.beginTransaction(); + Product product2 = session.get(Product.class, 12); + session.createNativeQuery("delete from Product where id=12") + .executeUpdate(); + // We need to refresh to fix the error. + // session.refresh(product2); + session.delete(product2); + transaction.commit(); + } catch (Exception e) { + rollbackTransactionQuietly(transaction); + throw (e); + } finally { + closeSessionQuietly(session); + } + } + + @Test + public void whenUpdatingNonExistingObject_thenStaleStateException() { + thrown.expect(isA(OptimisticLockException.class)); + thrown + .expectMessage("Row was updated or deleted by another transaction"); + thrown.expectCause(isA(StaleObjectStateException.class)); + + Session session = null; + Transaction transaction = null; + + try { + session = sessionFactory.openSession(); + transaction = session.beginTransaction(); + + Product product1 = new Product(); + product1.setId(15); + product1.setName("Product1"); + session.update(product1); + transaction.commit(); + } catch (Exception e) { + rollbackTransactionQuietly(transaction); + throw (e); + } finally { + closeSessionQuietly(session); + } + } + + @Test + public void givenTxnMarkedRollbackOnly_whenCommitted_thenTransactionException() { + thrown.expect(isA(TransactionException.class)); + + Session session = null; + Transaction transaction = null; + try { + session = sessionFactory.openSession(); + transaction = session.beginTransaction(); + + Product product1 = new Product(); + product1.setId(15); + product1.setName("Product1"); + session.save(product1); + transaction.setRollbackOnly(); + + transaction.commit(); + } catch (Exception e) { + rollbackTransactionQuietly(transaction); + throw (e); + } finally { + closeSessionQuietly(session); + } + } + + private void rollbackTransactionQuietly(Transaction transaction) { + if (transaction != null && transaction.isActive()) { + try { + transaction.rollback(); + } catch (Exception e) { + logger.error("Exception while rolling back transaction", e); + } + } + } + + private void closeSessionQuietly(Session session) { + if (session != null) { + try { + session.close(); + } catch (Exception e) { + logger.error("Exception while closing session", e); + } + } + } + + private void closeSessionFactoryQuietly(SessionFactory sessionFactory) { + if (sessionFactory != null) { + try { + sessionFactory.close(); + } catch (Exception e) { + logger.error("Exception while closing sessionFactory", e); + } + } + } + + @Test + public void givenExistingEntity_whenIdUpdated_thenHibernateException() { + thrown.expect(isA(PersistenceException.class)); + thrown.expectCause(isA(HibernateException.class)); + thrown.expectMessage( + "identifier of an instance of com.baeldung.hibernate.exception.Product was altered"); + + Session session = null; + Transaction transaction = null; + + try { + session = sessionFactory.openSession(); + transaction = session.beginTransaction(); + + Product product1 = new Product(); + product1.setId(222); + product1.setName("Product 222"); + session.save(product1); + transaction.commit(); + closeSessionQuietly(session); + + session = sessionFactory.openSession(); + transaction = session.beginTransaction(); + + Product product2 = session.get(Product.class, 222); + product2.setId(333); + session.save(product2); + + transaction.commit(); + } catch (Exception e) { + rollbackTransactionQuietly(transaction); + throw (e); + } finally { + closeSessionQuietly(session); + } + } +} diff --git a/persistence-modules/hibernate5/src/test/resources/hibernate-exception.properties b/persistence-modules/hibernate5/src/test/resources/hibernate-exception.properties new file mode 100644 index 0000000000..e08a23166d --- /dev/null +++ b/persistence-modules/hibernate5/src/test/resources/hibernate-exception.properties @@ -0,0 +1,16 @@ +hibernate.connection.driver_class=org.h2.Driver +hibernate.connection.url=jdbc:h2:mem:myexceptiondb1;DB_CLOSE_DELAY=-1 +hibernate.connection.username=sa +hibernate.connection.autocommit=true +jdbc.password= + +hibernate.dialect=org.hibernate.dialect.H2Dialect +hibernate.show_sql=true +hibernate.hbm2ddl.auto=create-drop + +hibernate.c3p0.min_size=5 +hibernate.c3p0.max_size=20 +hibernate.c3p0.acquire_increment=5 +hibernate.c3p0.timeout=1800 + +hibernate.transaction.factory_class=org.hibernate.transaction.JTATransactionFactory diff --git a/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/util/LocalDateConverter.java b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/util/LocalDateConverter.java new file mode 100644 index 0000000000..00fd378b05 --- /dev/null +++ b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/util/LocalDateConverter.java @@ -0,0 +1,25 @@ +package com.baeldung.util; + +import javax.persistence.AttributeConverter; +import javax.persistence.Converter; +import java.sql.Date; +import java.time.LocalDate; +import java.util.Optional; + +@Converter(autoApply = true) +public class LocalDateConverter implements AttributeConverter { + + @Override + public Date convertToDatabaseColumn(LocalDate localDate) { + return Optional.ofNullable(localDate) + .map(Date::valueOf) + .orElse(null); + } + + @Override + public LocalDate convertToEntityAttribute(Date date) { + return Optional.ofNullable(date) + .map(Date::toLocalDate) + .orElse(null); + } +} \ No newline at end of file diff --git a/persistence-modules/spring-data-elasticsearch/src/test/java/com/baeldung/elasticsearch/ElasticSearchManualTest.java b/persistence-modules/spring-data-elasticsearch/src/test/java/com/baeldung/elasticsearch/ElasticSearchManualTest.java index fbf4e5ab99..e43dcdf43e 100644 --- a/persistence-modules/spring-data-elasticsearch/src/test/java/com/baeldung/elasticsearch/ElasticSearchManualTest.java +++ b/persistence-modules/spring-data-elasticsearch/src/test/java/com/baeldung/elasticsearch/ElasticSearchManualTest.java @@ -30,6 +30,13 @@ import org.junit.Test; import com.alibaba.fastjson.JSON; +/** + * + * This Manual test requires: + * * Elasticsearch instance running on host + * * with cluster name = elasticsearch + * + */ public class ElasticSearchManualTest { private List listOfPersons = new ArrayList<>(); private Client client = null; diff --git a/persistence-modules/spring-data-elasticsearch/src/test/java/com/baeldung/elasticsearch/GeoQueriesIntegrationTest.java b/persistence-modules/spring-data-elasticsearch/src/test/java/com/baeldung/elasticsearch/GeoQueriesManualTest.java similarity index 97% rename from persistence-modules/spring-data-elasticsearch/src/test/java/com/baeldung/elasticsearch/GeoQueriesIntegrationTest.java rename to persistence-modules/spring-data-elasticsearch/src/test/java/com/baeldung/elasticsearch/GeoQueriesManualTest.java index 1f55379418..f9a42050b6 100644 --- a/persistence-modules/spring-data-elasticsearch/src/test/java/com/baeldung/elasticsearch/GeoQueriesIntegrationTest.java +++ b/persistence-modules/spring-data-elasticsearch/src/test/java/com/baeldung/elasticsearch/GeoQueriesManualTest.java @@ -31,9 +31,17 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.baeldung.spring.data.es.config.Config; import com.vividsolutions.jts.geom.Coordinate; +/** + * + * This Manual test requires: + * * Elasticsearch instance running on host + * * with cluster name = elasticsearch + * * and further configurations + * + */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = Config.class) -public class GeoQueriesIntegrationTest { +public class GeoQueriesManualTest { private static final String WONDERS_OF_WORLD = "wonders-of-world"; private static final String WONDERS = "Wonders"; diff --git a/persistence-modules/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchIntegrationTest.java b/persistence-modules/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchManualTest.java similarity index 97% rename from persistence-modules/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchIntegrationTest.java rename to persistence-modules/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchManualTest.java index 6ecb11cdbe..bed2e2ff25 100644 --- a/persistence-modules/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchIntegrationTest.java +++ b/persistence-modules/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchManualTest.java @@ -27,9 +27,16 @@ import com.baeldung.spring.data.es.model.Article; import com.baeldung.spring.data.es.model.Author; import com.baeldung.spring.data.es.service.ArticleService; +/** + * + * This Manual test requires: + * * Elasticsearch instance running on host + * * with cluster name = elasticsearch + * + */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = Config.class) -public class ElasticSearchIntegrationTest { +public class ElasticSearchManualTest { @Autowired private ElasticsearchTemplate elasticsearchTemplate; diff --git a/persistence-modules/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchQueryIntegrationTest.java b/persistence-modules/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchQueryManualTest.java similarity index 98% rename from persistence-modules/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchQueryIntegrationTest.java rename to persistence-modules/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchQueryManualTest.java index 2348c49830..5e24d8398c 100644 --- a/persistence-modules/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchQueryIntegrationTest.java +++ b/persistence-modules/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchQueryManualTest.java @@ -41,9 +41,16 @@ import com.baeldung.spring.data.es.model.Article; import com.baeldung.spring.data.es.model.Author; import com.baeldung.spring.data.es.service.ArticleService; +/** + * + * This Manual test requires: + * * Elasticsearch instance running on host + * * with cluster name = elasticsearch + * + */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = Config.class) -public class ElasticSearchQueryIntegrationTest { +public class ElasticSearchQueryManualTest { @Autowired private ElasticsearchTemplate elasticsearchTemplate; diff --git a/persistence-modules/spring-data-elasticsearch/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/persistence-modules/spring-data-elasticsearch/src/test/java/org/baeldung/SpringContextManualTest.java similarity index 77% rename from persistence-modules/spring-data-elasticsearch/src/test/java/org/baeldung/SpringContextIntegrationTest.java rename to persistence-modules/spring-data-elasticsearch/src/test/java/org/baeldung/SpringContextManualTest.java index 6f45039c96..c6f095eae9 100644 --- a/persistence-modules/spring-data-elasticsearch/src/test/java/org/baeldung/SpringContextIntegrationTest.java +++ b/persistence-modules/spring-data-elasticsearch/src/test/java/org/baeldung/SpringContextManualTest.java @@ -7,9 +7,15 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.baeldung.spring.data.es.config.Config; +/** + * + * This Manual test requires: + * * Elasticsearch instance running on host + * + */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = Config.class) -public class SpringContextIntegrationTest { +public class SpringContextManualTest { @Test public void whenSpringContextIsBootstrapped_thenNoExceptions() { diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/user/UserRepository.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/user/UserRepository.java index 5bb0232e4a..7f54254832 100644 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/user/UserRepository.java +++ b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/user/UserRepository.java @@ -1,6 +1,7 @@ package com.baeldung.dao.repositories.user; import com.baeldung.domain.user.User; + import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; @@ -13,7 +14,7 @@ import java.util.Collection; import java.util.List; import java.util.stream.Stream; -public interface UserRepository extends JpaRepository { +public interface UserRepository extends JpaRepository , UserRepositoryCustom{ Stream findAllByName(String name); diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/user/UserRepositoryCustom.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/user/UserRepositoryCustom.java new file mode 100644 index 0000000000..72c1fd5d00 --- /dev/null +++ b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/user/UserRepositoryCustom.java @@ -0,0 +1,10 @@ +package com.baeldung.dao.repositories.user; + +import java.util.List; +import java.util.Set; + +import com.baeldung.domain.user.User; + +public interface UserRepositoryCustom { + List findUserByEmails(Set emails); +} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/user/UserRepositoryCustomImpl.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/user/UserRepositoryCustomImpl.java new file mode 100644 index 0000000000..9f841caf68 --- /dev/null +++ b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/user/UserRepositoryCustomImpl.java @@ -0,0 +1,43 @@ +package com.baeldung.dao.repositories.user; + +import java.util.ArrayList; +import java.util.List; +import java.util.Set; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.CriteriaQuery; +import javax.persistence.criteria.Path; +import javax.persistence.criteria.Predicate; +import javax.persistence.criteria.Root; + +import com.baeldung.domain.user.User; + +public class UserRepositoryCustomImpl implements UserRepositoryCustom { + + @PersistenceContext + private EntityManager entityManager; + + @Override + public List findUserByEmails(Set emails) { + CriteriaBuilder cb = entityManager.getCriteriaBuilder(); + CriteriaQuery query = cb.createQuery(User.class); + Root user = query.from(User.class); + + Path emailPath = user.get("email"); + + List predicates = new ArrayList<>(); + for (String email : emails) { + + predicates.add(cb.like(emailPath, email)); + + } + query.select(user) + .where(cb.or(predicates.toArray(new Predicate[predicates.size()]))); + + return entityManager.createQuery(query) + .getResultList(); + } + +} diff --git a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/UserRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/UserRepositoryIntegrationTest.java index e29161394b..b05086d00e 100644 --- a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/UserRepositoryIntegrationTest.java +++ b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/UserRepositoryIntegrationTest.java @@ -18,7 +18,9 @@ import org.springframework.test.context.junit4.SpringRunner; import org.springframework.transaction.annotation.Transactional; import java.util.Collection; +import java.util.HashSet; import java.util.List; +import java.util.Set; import java.util.stream.Stream; import static org.assertj.core.api.Assertions.assertThat; @@ -274,9 +276,8 @@ public class UserRepositoryIntegrationTest { List usersSortByName = userRepository.findAll(new Sort(Sort.Direction.ASC, "name")); - assertThat(usersSortByName - .get(0) - .getName()).isEqualTo(USER_NAME_ADAM); + assertThat(usersSortByName.get(0) + .getName()).isEqualTo(USER_NAME_ADAM); } @Test(expected = PropertyReferenceException.class) @@ -289,9 +290,8 @@ public class UserRepositoryIntegrationTest { List usersSortByNameLength = userRepository.findAll(new Sort("LENGTH(name)")); - assertThat(usersSortByNameLength - .get(0) - .getName()).isEqualTo(USER_NAME_ADAM); + assertThat(usersSortByNameLength.get(0) + .getName()).isEqualTo(USER_NAME_ADAM); } @Test @@ -304,9 +304,8 @@ public class UserRepositoryIntegrationTest { List usersSortByNameLength = userRepository.findAllUsers(JpaSort.unsafe("LENGTH(name)")); - assertThat(usersSortByNameLength - .get(0) - .getName()).isEqualTo(USER_NAME_ADAM); + assertThat(usersSortByNameLength.get(0) + .getName()).isEqualTo(USER_NAME_ADAM); } @Test @@ -320,10 +319,9 @@ public class UserRepositoryIntegrationTest { Page usersPage = userRepository.findAllUsersWithPagination(new PageRequest(1, 3)); - assertThat(usersPage - .getContent() - .get(0) - .getName()).isEqualTo("SAMPLE1"); + assertThat(usersPage.getContent() + .get(0) + .getName()).isEqualTo("SAMPLE1"); } @Test @@ -337,10 +335,9 @@ public class UserRepositoryIntegrationTest { Page usersSortByNameLength = userRepository.findAllUsersWithPaginationNative(new PageRequest(1, 3)); - assertThat(usersSortByNameLength - .getContent() - .get(0) - .getName()).isEqualTo("SAMPLE1"); + assertThat(usersSortByNameLength.getContent() + .get(0) + .getName()).isEqualTo("SAMPLE1"); } @Test @@ -370,6 +367,30 @@ public class UserRepositoryIntegrationTest { assertThat(updatedUsersSize).isEqualTo(2); } + @Test + public void givenUsersInDBWhenFindByEmailsWithDynamicQueryThenReturnCollection() { + + User user1 = new User(); + user1.setEmail(USER_EMAIL); + userRepository.save(user1); + + User user2 = new User(); + user2.setEmail(USER_EMAIL2); + userRepository.save(user2); + + User user3 = new User(); + user3.setEmail(USER_EMAIL3); + userRepository.save(user3); + + Set emails = new HashSet<>(); + emails.add(USER_EMAIL2); + emails.add(USER_EMAIL3); + + Collection usersWithEmails = userRepository.findUserByEmails(emails); + + assertThat(usersWithEmails.size()).isEqualTo(2); + } + @After public void cleanUp() { userRepository.deleteAll(); diff --git a/persistence-modules/spring-data-mongodb/pom.xml b/persistence-modules/spring-data-mongodb/pom.xml index 63b9c3c1b0..c1faf72103 100644 --- a/persistence-modules/spring-data-mongodb/pom.xml +++ b/persistence-modules/spring-data-mongodb/pom.xml @@ -99,7 +99,6 @@ 2.1.2.RELEASE 4.1.4 1.1.3 - 5.1.0.RELEASE 1.9.2 3.2.0.RELEASE diff --git a/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/aggregation/ZipsAggregationLiveTest.java b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/aggregation/ZipsAggregationLiveTest.java index 1da50d7cb4..1002dc79eb 100644 --- a/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/aggregation/ZipsAggregationLiveTest.java +++ b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/aggregation/ZipsAggregationLiveTest.java @@ -44,6 +44,12 @@ import com.mongodb.MongoClient; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; +/** + * + * This test requires: + * * mongodb instance running on the environment + * + */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = MongoConfig.class) public class ZipsAggregationLiveTest { diff --git a/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/gridfs/GridFSLiveTest.java b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/gridfs/GridFSLiveTest.java index 3a88a1e654..d25b9ece4f 100644 --- a/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/gridfs/GridFSLiveTest.java +++ b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/gridfs/GridFSLiveTest.java @@ -31,6 +31,12 @@ import com.mongodb.BasicDBObject; import com.mongodb.DBObject; import com.mongodb.client.gridfs.model.GridFSFile; +/** + * + * This test requires: + * * mongodb instance running on the environment + * + */ @ContextConfiguration("file:src/main/resources/mongoConfig.xml") @RunWith(SpringJUnit4ClassRunner.class) public class GridFSLiveTest { diff --git a/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/mongotemplate/DocumentQueryLiveTest.java b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/mongotemplate/DocumentQueryLiveTest.java index d05bde0f1b..e5e4a188ec 100644 --- a/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/mongotemplate/DocumentQueryLiveTest.java +++ b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/mongotemplate/DocumentQueryLiveTest.java @@ -24,6 +24,12 @@ import com.baeldung.config.MongoConfig; import com.baeldung.model.EmailAddress; import com.baeldung.model.User; +/** + * + * This test requires: + * * mongodb instance running on the environment + * + */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = MongoConfig.class) public class DocumentQueryLiveTest { diff --git a/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/mongotemplate/MongoTemplateProjectionLiveTest.java b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/mongotemplate/MongoTemplateProjectionLiveTest.java index 309f14e995..9e12997c67 100644 --- a/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/mongotemplate/MongoTemplateProjectionLiveTest.java +++ b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/mongotemplate/MongoTemplateProjectionLiveTest.java @@ -16,6 +16,12 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; +/** + * + * This test requires: + * * mongodb instance running on the environment + * + */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = SimpleMongoConfig.class) public class MongoTemplateProjectionLiveTest { diff --git a/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/mongotemplate/MongoTemplateQueryLiveTest.java b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/mongotemplate/MongoTemplateQueryLiveTest.java index fc78921b75..4f62f0d7a7 100644 --- a/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/mongotemplate/MongoTemplateQueryLiveTest.java +++ b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/mongotemplate/MongoTemplateQueryLiveTest.java @@ -27,6 +27,12 @@ import com.baeldung.config.MongoConfig; import com.baeldung.model.EmailAddress; import com.baeldung.model.User; +/** + * + * This test requires: + * * mongodb instance running on the environment + * + */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = MongoConfig.class) public class MongoTemplateQueryLiveTest { diff --git a/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/repository/ActionRepositoryLiveTest.java b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/repository/ActionRepositoryLiveTest.java index 096015ca0a..79648f1a20 100644 --- a/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/repository/ActionRepositoryLiveTest.java +++ b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/repository/ActionRepositoryLiveTest.java @@ -15,6 +15,12 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.time.ZoneOffset; import java.time.ZonedDateTime; +/** + * + * This test requires: + * * mongodb instance running on the environment + * + */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = MongoConfig.class) public class ActionRepositoryLiveTest { diff --git a/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/repository/BaseQueryLiveTest.java b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/repository/BaseQueryLiveTest.java index e4849181e5..c94bb2ae4c 100644 --- a/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/repository/BaseQueryLiveTest.java +++ b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/repository/BaseQueryLiveTest.java @@ -7,6 +7,12 @@ import org.junit.Before; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.mongodb.core.MongoOperations; +/** + * + * This test requires: + * * mongodb instance running on the environment + * + */ public class BaseQueryLiveTest { @Autowired diff --git a/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/repository/DSLQueryLiveTest.java b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/repository/DSLQueryLiveTest.java index f87ca5cbb5..0ccf677b3e 100644 --- a/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/repository/DSLQueryLiveTest.java +++ b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/repository/DSLQueryLiveTest.java @@ -15,8 +15,12 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.querydsl.core.types.Predicate; - - +/** + * + * This test requires: + * * mongodb instance running on the environment + * + */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = MongoConfig.class) public class DSLQueryLiveTest extends BaseQueryLiveTest { diff --git a/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/repository/JSONQueryLiveTest.java b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/repository/JSONQueryLiveTest.java index 4e99c0b140..3a99407350 100644 --- a/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/repository/JSONQueryLiveTest.java +++ b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/repository/JSONQueryLiveTest.java @@ -12,6 +12,12 @@ import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +/** + * + * This test requires: + * * mongodb instance running on the environment + * + */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = MongoConfig.class) public class JSONQueryLiveTest extends BaseQueryLiveTest { diff --git a/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/repository/QueryMethodsLiveTest.java b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/repository/QueryMethodsLiveTest.java index 47e67a6b4c..ef8ce10dd1 100644 --- a/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/repository/QueryMethodsLiveTest.java +++ b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/repository/QueryMethodsLiveTest.java @@ -12,6 +12,12 @@ import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +/** + * + * This test requires: + * * mongodb instance running on the environment + * + */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = MongoConfig.class) public class QueryMethodsLiveTest extends BaseQueryLiveTest { diff --git a/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/repository/UserRepositoryLiveTest.java b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/repository/UserRepositoryLiveTest.java index 901610e42d..dd7215af7e 100644 --- a/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/repository/UserRepositoryLiveTest.java +++ b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/repository/UserRepositoryLiveTest.java @@ -23,6 +23,12 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.baeldung.config.MongoConfig; import com.baeldung.model.User; +/** + * + * This test requires: + * * mongodb instance running on the environment + * + */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = MongoConfig.class) public class UserRepositoryLiveTest { diff --git a/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/repository/UserRepositoryProjectionLiveTest.java b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/repository/UserRepositoryProjectionLiveTest.java index 80f4275794..8972246041 100644 --- a/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/repository/UserRepositoryProjectionLiveTest.java +++ b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/repository/UserRepositoryProjectionLiveTest.java @@ -13,6 +13,12 @@ import org.springframework.data.mongodb.core.MongoOperations; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +/** + * + * This test requires: + * * mongodb instance running on the environment + * + */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = MongoConfig.class) public class UserRepositoryProjectionLiveTest { diff --git a/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/transaction/MongoTransactionReactiveLiveTest.java b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/transaction/MongoTransactionReactiveLiveTest.java index 70908552fe..3fc8dcf977 100644 --- a/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/transaction/MongoTransactionReactiveLiveTest.java +++ b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/transaction/MongoTransactionReactiveLiveTest.java @@ -12,6 +12,12 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.baeldung.config.MongoReactiveConfig; import com.baeldung.model.User; +/** + * + * This test requires: + * * mongodb instance running on the environment + * + */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = MongoReactiveConfig.class) public class MongoTransactionReactiveLiveTest { diff --git a/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/transaction/MongoTransactionTemplateLiveTest.java b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/transaction/MongoTransactionTemplateLiveTest.java index 20ac6974bc..53b2c7a0e7 100644 --- a/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/transaction/MongoTransactionTemplateLiveTest.java +++ b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/transaction/MongoTransactionTemplateLiveTest.java @@ -24,6 +24,12 @@ import org.springframework.transaction.support.TransactionTemplate; import com.baeldung.config.MongoConfig; import com.baeldung.model.User; +/** + * + * This test requires: + * * mongodb instance running on the environment + * + */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = MongoConfig.class) public class MongoTransactionTemplateLiveTest { diff --git a/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/transaction/MongoTransactionalLiveTest.java b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/transaction/MongoTransactionalLiveTest.java index 0cf86aa43e..bafcd770ec 100644 --- a/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/transaction/MongoTransactionalLiveTest.java +++ b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/transaction/MongoTransactionalLiveTest.java @@ -24,6 +24,12 @@ import com.baeldung.model.User; import com.baeldung.repository.UserRepository; import com.mongodb.MongoCommandException; +/** + * + * This test requires: + * * mongodb instance running on the environment + * + */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = MongoConfig.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) diff --git a/pom.xml b/pom.xml index 4dba0da173..1c0738cafb 100644 --- a/pom.xml +++ b/pom.xml @@ -232,6 +232,7 @@ ${maven-war-plugin.version} + com.vackosar.gitflowincrementalbuilder @@ -390,6 +391,7 @@ core-java-networking core-java-perf core-java-sun + core-java core-scala couchbase custom-pmd @@ -436,7 +438,7 @@ java-collections-conversions java-collections-maps - java-ee-8-security-api + java-lite java-numbers java-rmi @@ -644,6 +646,7 @@ spring-boot-logging-log4j2 spring-boot-mvc spring-boot-ops + spring-boot-rest spring-boot-property-exp spring-boot-security spring-boot-testing @@ -994,8 +997,7 @@ parent-spring-5 parent-java parent-kotlin - - core-java + core-java-concurrency-advanced core-kotlin @@ -1355,6 +1357,7 @@ spring-boot-logging-log4j2 spring-boot-mvc spring-boot-ops + spring-boot-rest spring-boot-property-exp spring-boot-security spring-boot-vue diff --git a/spring-4/README.md b/spring-4/README.md index 402557eb41..57cb8c3eeb 100644 --- a/spring-4/README.md +++ b/spring-4/README.md @@ -1,3 +1,4 @@ ### Relevant Articles: - [A Guide to Flips for Spring](http://www.baeldung.com/flips-spring) - [Configuring a Hikari Connection Pool with Spring Boot](https://www.baeldung.com/spring-boot-hikari) +- [Spring JSON-P with Jackson](http://www.baeldung.com/spring-jackson-jsonp) diff --git a/spring-4/pom.xml b/spring-4/pom.xml index 78939bba95..60f1555d8f 100644 --- a/spring-4/pom.xml +++ b/spring-4/pom.xml @@ -52,6 +52,21 @@ provided + + javax.servlet + jstl + + + + org.springframework.boot + spring-boot-starter-tomcat + provided + + + org.apache.tomcat.embed + tomcat-embed-jasper + provided + @@ -71,6 +86,7 @@ + com.baeldung.flips.ApplicationConfig 1.0.1 1.16.18 1.4.197 diff --git a/spring-4/src/main/java/com/baeldung/flips/ApplicationConfig.java b/spring-4/src/main/java/com/baeldung/flips/ApplicationConfig.java index 7001aeb991..1bd6ffa336 100644 --- a/spring-4/src/main/java/com/baeldung/flips/ApplicationConfig.java +++ b/spring-4/src/main/java/com/baeldung/flips/ApplicationConfig.java @@ -3,9 +3,15 @@ package com.baeldung.flips; import org.flips.describe.config.FlipWebContextConfiguration; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; +import org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration; +import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration; import org.springframework.context.annotation.Import; -@SpringBootApplication +@SpringBootApplication(exclude = { + DataSourceAutoConfiguration.class, + DataSourceTransactionManagerAutoConfiguration.class, + HibernateJpaAutoConfiguration.class }) @Import(FlipWebContextConfiguration.class) public class ApplicationConfig { diff --git a/spring-4/src/main/java/com/baeldung/jsonp/JsonPApplication.java b/spring-4/src/main/java/com/baeldung/jsonp/JsonPApplication.java new file mode 100644 index 0000000000..a8f3c0e102 --- /dev/null +++ b/spring-4/src/main/java/com/baeldung/jsonp/JsonPApplication.java @@ -0,0 +1,27 @@ +package com.baeldung.jsonp; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; +import org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration; +import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.boot.web.support.SpringBootServletInitializer; +import org.springframework.context.annotation.PropertySource; + +@SpringBootApplication(exclude = { + DataSourceAutoConfiguration.class, + DataSourceTransactionManagerAutoConfiguration.class, + HibernateJpaAutoConfiguration.class }) +@PropertySource("classpath:jsonp-application.properties") +public class JsonPApplication extends SpringBootServletInitializer { + + @Override + protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { + return application.sources(JsonPApplication.class); + } + + public static void main(String[] args) throws Exception { + SpringApplication.run(JsonPApplication.class, args); + } +} diff --git a/spring-4/src/main/java/com/baeldung/jsonp/model/Company.java b/spring-4/src/main/java/com/baeldung/jsonp/model/Company.java new file mode 100644 index 0000000000..b11a216e52 --- /dev/null +++ b/spring-4/src/main/java/com/baeldung/jsonp/model/Company.java @@ -0,0 +1,38 @@ +package com.baeldung.jsonp.model; + +public class Company { + + private long id; + private String name; + + public Company() { + super(); + } + + public Company(final long id, final String name) { + this.id = id; + this.name = name; + } + + public String getName() { + return name; + } + + public void setName(final String name) { + this.name = name; + } + + public long getId() { + return id; + } + + public void setId(final long id) { + this.id = id; + } + + @Override + public String toString() { + return "Company [id=" + id + ", name=" + name + "]"; + } + +} diff --git a/spring-4/src/main/java/com/baeldung/jsonp/web/controller/CompanyController.java b/spring-4/src/main/java/com/baeldung/jsonp/web/controller/CompanyController.java new file mode 100644 index 0000000000..8710359365 --- /dev/null +++ b/spring-4/src/main/java/com/baeldung/jsonp/web/controller/CompanyController.java @@ -0,0 +1,27 @@ +package com.baeldung.jsonp.web.controller; + +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; + +import com.baeldung.jsonp.model.Company; + +@Controller +public class CompanyController { + + @RequestMapping(value = "/companyResponseBody", produces = MediaType.APPLICATION_JSON_VALUE) + @ResponseBody + public Company getCompanyResponseBody() { + final Company company = new Company(2, "ABC"); + return company; + } + + @RequestMapping(value = "/companyResponseEntity", produces = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity getCompanyResponseEntity() { + final Company company = new Company(3, "123"); + return new ResponseEntity(company, HttpStatus.OK); + } +} diff --git a/spring-4/src/main/java/com/baeldung/jsonp/web/controller/IndexController.java b/spring-4/src/main/java/com/baeldung/jsonp/web/controller/IndexController.java new file mode 100644 index 0000000000..8469e19458 --- /dev/null +++ b/spring-4/src/main/java/com/baeldung/jsonp/web/controller/IndexController.java @@ -0,0 +1,13 @@ +package com.baeldung.jsonp.web.controller; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; + +@Controller +public class IndexController { + + @RequestMapping() + public String retrieveIndex() { + return "index"; + } +} diff --git a/spring-mvc-java/src/main/java/com/baeldung/web/controller/advice/JsonpControllerAdvice.java b/spring-4/src/main/java/com/baeldung/jsonp/web/controller/advice/JsonpControllerAdvice.java similarity index 53% rename from spring-mvc-java/src/main/java/com/baeldung/web/controller/advice/JsonpControllerAdvice.java rename to spring-4/src/main/java/com/baeldung/jsonp/web/controller/advice/JsonpControllerAdvice.java index 7b2c6870df..be7c65cb1e 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/web/controller/advice/JsonpControllerAdvice.java +++ b/spring-4/src/main/java/com/baeldung/jsonp/web/controller/advice/JsonpControllerAdvice.java @@ -1,8 +1,11 @@ -package com.baeldung.web.controller.advice; +package com.baeldung.jsonp.web.controller.advice; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.servlet.mvc.method.annotation.AbstractJsonpResponseBodyAdvice; +// AbstractJsonpResponseBodyAdvice was deprecated in favor of configuring CORS properly +// We still want to cover the usage of JSON-P in our articles, therefore we don't care that it was deprecated. +@SuppressWarnings("deprecation") @ControllerAdvice public class JsonpControllerAdvice extends AbstractJsonpResponseBodyAdvice { diff --git a/spring-4/src/main/resources/application.properties b/spring-4/src/main/resources/application.properties index 274896be15..e67700b7be 100644 --- a/spring-4/src/main/resources/application.properties +++ b/spring-4/src/main/resources/application.properties @@ -2,4 +2,4 @@ feature.foo.by.id=Y feature.new.foo=Y last.active.after=2018-03-14T00:00:00Z first.active.after=2999-03-15T00:00:00Z -logging.level.org.flips=info \ No newline at end of file +logging.level.org.flips=info diff --git a/spring-4/src/main/resources/jsonp-application.properties b/spring-4/src/main/resources/jsonp-application.properties new file mode 100644 index 0000000000..94e7fcc026 --- /dev/null +++ b/spring-4/src/main/resources/jsonp-application.properties @@ -0,0 +1,2 @@ +spring.mvc.view.prefix=/WEB-INF/jsp/ +spring.mvc.view.suffix=.jsp diff --git a/spring-4/src/main/webapp/WEB-INF/jsp/index.jsp b/spring-4/src/main/webapp/WEB-INF/jsp/index.jsp new file mode 100644 index 0000000000..fa5498c966 --- /dev/null +++ b/spring-4/src/main/webapp/WEB-INF/jsp/index.jsp @@ -0,0 +1,66 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1" %> + + + + + Company Data + + + + + + + + +
+ + + + \ No newline at end of file diff --git a/spring-5-reactive-oauth/src/main/java/com/baeldung/webclient/authorizationcodeclient/OauthClientApplication.java b/spring-5-reactive-oauth/src/main/java/com/baeldung/webclient/authorizationcodeclient/OauthClientApplication.java index 7bae78bb14..843d3f251f 100644 --- a/spring-5-reactive-oauth/src/main/java/com/baeldung/webclient/authorizationcodeclient/OauthClientApplication.java +++ b/spring-5-reactive-oauth/src/main/java/com/baeldung/webclient/authorizationcodeclient/OauthClientApplication.java @@ -6,9 +6,9 @@ import org.springframework.context.annotation.PropertySource; /** * - * Note: This app is configured to use the authorization service and the resource service located in module spring-5-security-oauth + * Note: This app is configured to use the authorization service and the resource service located in Baeldung/spring-security-oauth repo * - * As we usually do with other well-known auth providers (github/facebook/...) we have to log-in using user credentials (bael-user/bael-password) and client configurations (bael-client-id/bael-secret) handled by the auth server + * As we usually do with other well-known auth providers (github/facebook/...) we have to log-in using user credentials (john/123) and client configurations handled by the auth server * * @author rozagerardo * diff --git a/spring-5-reactive-oauth/src/main/java/com/baeldung/webclient/authorizationcodeclient/web/ClientRestController.java b/spring-5-reactive-oauth/src/main/java/com/baeldung/webclient/authorizationcodeclient/web/ClientRestController.java index c36b7d1dea..9994a1255a 100644 --- a/spring-5-reactive-oauth/src/main/java/com/baeldung/webclient/authorizationcodeclient/web/ClientRestController.java +++ b/spring-5-reactive-oauth/src/main/java/com/baeldung/webclient/authorizationcodeclient/web/ClientRestController.java @@ -15,7 +15,7 @@ import reactor.core.publisher.Mono; @RestController public class ClientRestController { - private static final String RESOURCE_URI = "http://localhost:8084/retrieve-resource"; + private static final String RESOURCE_URI = "http://localhost:8082/spring-security-oauth-resource/foos/1"; @Autowired WebClient webClient; diff --git a/spring-5-reactive-oauth/src/main/java/com/baeldung/webclient/authorizationcodelogin/OauthClientApplication.java b/spring-5-reactive-oauth/src/main/java/com/baeldung/webclient/authorizationcodelogin/OauthClientLoginApplication.java similarity index 62% rename from spring-5-reactive-oauth/src/main/java/com/baeldung/webclient/authorizationcodelogin/OauthClientApplication.java rename to spring-5-reactive-oauth/src/main/java/com/baeldung/webclient/authorizationcodelogin/OauthClientLoginApplication.java index 9dd6dd1bde..e71e549ea4 100644 --- a/spring-5-reactive-oauth/src/main/java/com/baeldung/webclient/authorizationcodelogin/OauthClientApplication.java +++ b/spring-5-reactive-oauth/src/main/java/com/baeldung/webclient/authorizationcodelogin/OauthClientLoginApplication.java @@ -6,19 +6,19 @@ import org.springframework.context.annotation.PropertySource; /** * - * Note: This app is configured to use the authorization service and the resource service located in module spring-5-security-oauth + * Note: This app is configured to use the authorization service and the resource service located in Baeldung/spring-security-oauth repo * - * As we usually do with other well-known auth providers (github/facebook/...) we have to log-in using user credentials (bael-user/bael-password) and client configurations (bael-client-id/bael-secret) handled by the auth server + * As we usually do with other well-known auth providers (github/facebook/...) we have to log-in using user credentials (john/123) and client configurations handled by the auth server * * @author rozagerardo * */ @PropertySource("classpath:webclient-auth-code-login-application.properties") @SpringBootApplication -public class OauthClientApplication { +public class OauthClientLoginApplication { public static void main(String[] args) { - SpringApplication.run(OauthClientApplication.class, args); + SpringApplication.run(OauthClientLoginApplication.class, args); } } diff --git a/spring-5-reactive-oauth/src/main/java/com/baeldung/webclient/authorizationcodelogin/web/ClientRestController.java b/spring-5-reactive-oauth/src/main/java/com/baeldung/webclient/authorizationcodelogin/web/ClientRestController.java index 55e0096525..24e5377f36 100644 --- a/spring-5-reactive-oauth/src/main/java/com/baeldung/webclient/authorizationcodelogin/web/ClientRestController.java +++ b/spring-5-reactive-oauth/src/main/java/com/baeldung/webclient/authorizationcodelogin/web/ClientRestController.java @@ -16,7 +16,7 @@ import reactor.core.publisher.Mono; @RestController public class ClientRestController { - private static final String RESOURCE_URI = "http://localhost:8084/retrieve-resource"; + private static final String RESOURCE_URI = "http://localhost:8082/spring-security-oauth-resource/foos/1"; @Autowired WebClient webClient; diff --git a/spring-5-reactive-oauth/src/main/java/com/baeldung/webclient/clientcredentials/ClientCredentialsOauthApplication.java b/spring-5-reactive-oauth/src/main/java/com/baeldung/webclient/clientcredentials/ClientCredentialsOauthApplication.java index d1b9f7f744..4356581819 100644 --- a/spring-5-reactive-oauth/src/main/java/com/baeldung/webclient/clientcredentials/ClientCredentialsOauthApplication.java +++ b/spring-5-reactive-oauth/src/main/java/com/baeldung/webclient/clientcredentials/ClientCredentialsOauthApplication.java @@ -7,9 +7,7 @@ import org.springframework.scheduling.annotation.EnableScheduling; /** * - * Note: This app is configured to use the authorization service and the resource service located in module spring-5-security-oauth - * - * As we usually do with other well-known auth providers (github/facebook/...) we have to log-in using credentials handled by the auth server (bael-user/bael-password) + * Note: This app is configured to use the authorization service and the resource service located in Baeldung/spring-security-oauth repo * * @author rozagerardo * diff --git a/spring-5-reactive-oauth/src/main/java/com/baeldung/webclient/clientcredentials/service/WebClientChonJob.java b/spring-5-reactive-oauth/src/main/java/com/baeldung/webclient/clientcredentials/service/WebClientChonJob.java index dc38ce3f9e..ef39222933 100644 --- a/spring-5-reactive-oauth/src/main/java/com/baeldung/webclient/clientcredentials/service/WebClientChonJob.java +++ b/spring-5-reactive-oauth/src/main/java/com/baeldung/webclient/clientcredentials/service/WebClientChonJob.java @@ -4,8 +4,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Scheduled; -import org.springframework.security.oauth2.client.OAuth2AuthorizedClient; -import org.springframework.security.oauth2.client.annotation.RegisteredOAuth2AuthorizedClient; import org.springframework.stereotype.Component; import org.springframework.web.reactive.function.client.WebClient; @@ -14,12 +12,12 @@ public class WebClientChonJob { Logger logger = LoggerFactory.getLogger(WebClientChonJob.class); - private static final String RESOURCE_URI = "http://localhost:8084/retrieve-resource"; + private static final String RESOURCE_URI = "localhost:8082/spring-security-oauth-resource/foos/1"; @Autowired private WebClient webClient; - @Scheduled(fixedRate = 1000) + @Scheduled(fixedRate = 5000) public void logResourceServiceResponse() { webClient.get() diff --git a/spring-5-reactive-oauth/src/main/java/com/baeldung/webclient/manualrequest/ManualRequestApplication.java b/spring-5-reactive-oauth/src/main/java/com/baeldung/webclient/manualrequest/ManualRequestApplication.java index c2762ad559..59a63355f7 100644 --- a/spring-5-reactive-oauth/src/main/java/com/baeldung/webclient/manualrequest/ManualRequestApplication.java +++ b/spring-5-reactive-oauth/src/main/java/com/baeldung/webclient/manualrequest/ManualRequestApplication.java @@ -6,13 +6,12 @@ import org.springframework.context.annotation.PropertySource; /** * - * Note: This app is configured to use the authorization service and the resource service located in module spring-5-security-oauth - * - * As we usually do with other well-known auth providers (github/facebook/...) we have to log-in using user credentials (bael-user/bael-password) and client configurations (bael-client-id/bael-secret) handled by the auth server + * Note: This app is configured to use the authorization service and the resource service located in Baeldung/spring-security-oauth repo * * @author rozagerardo * */ +@PropertySource("classpath:webclient-manual-request-oauth-application.properties") @SpringBootApplication public class ManualRequestApplication { diff --git a/spring-5-reactive-oauth/src/main/java/com/baeldung/webclient/manualrequest/web/ManualOauthRequestController.java b/spring-5-reactive-oauth/src/main/java/com/baeldung/webclient/manualrequest/web/ManualOauthRequestController.java index 9f9d6d3167..d54d811032 100644 --- a/spring-5-reactive-oauth/src/main/java/com/baeldung/webclient/manualrequest/web/ManualOauthRequestController.java +++ b/spring-5-reactive-oauth/src/main/java/com/baeldung/webclient/manualrequest/web/ManualOauthRequestController.java @@ -3,8 +3,8 @@ package com.baeldung.webclient.manualrequest.web; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpHeaders; -import org.springframework.http.MediaType; import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames; import org.springframework.util.Base64Utils; import org.springframework.web.bind.annotation.GetMapping; @@ -22,10 +22,16 @@ public class ManualOauthRequestController { private static Logger logger = LoggerFactory.getLogger(ManualOauthRequestController.class); - private static final String TOKEN_ENDPOINT = "localhost:8085/oauth/token"; - private static final String RESOURCE_ENDPOINT = "localhost:8084/retrieve-resource"; - private static final String CLIENT_ID = "bael-client-id"; - private static final String CLIENT_SECRET = "bael-secret"; + private static final String RESOURCE_ENDPOINT = "localhost:8082/spring-security-oauth-resource/foos/1"; + + @Value("${the.authorization.client-id}") + private String clientId; + + @Value("${the.authorization.client-secret}") + private String clientSecret; + + @Value("${the.authorization.token-uri}") + private String tokenUri; @Autowired WebClient client; @@ -34,8 +40,8 @@ public class ManualOauthRequestController { public Mono obtainSecuredResource() { logger.info("Creating web client..."); Mono resource = client.post() - .uri(TOKEN_ENDPOINT) - .header(HttpHeaders.AUTHORIZATION, "Basic " + Base64Utils.encodeToString((CLIENT_ID + ":" + CLIENT_SECRET).getBytes())) + .uri(tokenUri) + .header(HttpHeaders.AUTHORIZATION, "Basic " + Base64Utils.encodeToString((clientId + ":" + clientSecret).getBytes())) .body(BodyInserters.fromFormData(OAuth2ParameterNames.GRANT_TYPE, GrantType.CLIENT_CREDENTIALS.getValue())) .retrieve() .bodyToMono(JsonNode.class) diff --git a/spring-5-reactive-oauth/src/main/resources/webclient-auth-code-client-application.properties b/spring-5-reactive-oauth/src/main/resources/webclient-auth-code-client-application.properties index 612777a06d..ac96aae6d6 100644 --- a/spring-5-reactive-oauth/src/main/resources/webclient-auth-code-client-application.properties +++ b/spring-5-reactive-oauth/src/main/resources/webclient-auth-code-client-application.properties @@ -1,10 +1,10 @@ spring.security.oauth2.client.registration.bael.client-name=bael -spring.security.oauth2.client.registration.bael.client-id=bael-client-id -spring.security.oauth2.client.registration.bael.client-secret=bael-secret +spring.security.oauth2.client.registration.bael.client-id=fooClientIdPassword +spring.security.oauth2.client.registration.bael.client-secret=secret spring.security.oauth2.client.registration.bael.authorization-grant-type=authorization_code spring.security.oauth2.client.registration.bael.redirect-uri=http://localhost:8080/authorize/oauth2/code/bael -spring.security.oauth2.client.provider.bael.token-uri=http://localhost:8085/oauth/token -spring.security.oauth2.client.provider.bael.authorization-uri=http://localhost:8085/oauth/authorize +spring.security.oauth2.client.provider.bael.token-uri=http://localhost:8081/spring-security-oauth-server/oauth/token +spring.security.oauth2.client.provider.bael.authorization-uri=http://localhost:8081/spring-security-oauth-server/oauth/authorize spring.security.user.password=pass diff --git a/spring-5-reactive-oauth/src/main/resources/webclient-auth-code-login-application.properties b/spring-5-reactive-oauth/src/main/resources/webclient-auth-code-login-application.properties index edd5b80b13..e4dd0a532d 100644 --- a/spring-5-reactive-oauth/src/main/resources/webclient-auth-code-login-application.properties +++ b/spring-5-reactive-oauth/src/main/resources/webclient-auth-code-login-application.properties @@ -1,10 +1,10 @@ spring.security.oauth2.client.registration.bael.client-name=bael -spring.security.oauth2.client.registration.bael.client-id=bael-client-id -spring.security.oauth2.client.registration.bael.client-secret=bael-secret +spring.security.oauth2.client.registration.bael.client-id=fooClientIdPassword +spring.security.oauth2.client.registration.bael.client-secret=secret spring.security.oauth2.client.registration.bael.authorization-grant-type=authorization_code spring.security.oauth2.client.registration.bael.redirect-uri=http://localhost:8080/login/oauth2/code/bael -spring.security.oauth2.client.provider.bael.token-uri=http://localhost:8085/oauth/token -spring.security.oauth2.client.provider.bael.authorization-uri=http://localhost:8085/oauth/authorize -spring.security.oauth2.client.provider.bael.user-info-uri=http://localhost:8084/user -spring.security.oauth2.client.provider.bael.user-name-attribute=name +spring.security.oauth2.client.provider.bael.token-uri=http://localhost:8081/spring-security-oauth-server/oauth/token +spring.security.oauth2.client.provider.bael.authorization-uri=http://localhost:8081/spring-security-oauth-server/oauth/authorize +spring.security.oauth2.client.provider.bael.user-info-uri=http://localhost:8082/spring-security-oauth-resource/users/extra +spring.security.oauth2.client.provider.bael.user-name-attribute=user_name diff --git a/spring-5-reactive-oauth/src/main/resources/webclient-client-credentials-oauth-application.properties b/spring-5-reactive-oauth/src/main/resources/webclient-client-credentials-oauth-application.properties index f82f74ec48..14c5b97605 100644 --- a/spring-5-reactive-oauth/src/main/resources/webclient-client-credentials-oauth-application.properties +++ b/spring-5-reactive-oauth/src/main/resources/webclient-client-credentials-oauth-application.properties @@ -1,4 +1,4 @@ spring.security.oauth2.client.registration.bael.authorization-grant-type=client_credentials -spring.security.oauth2.client.registration.bael.client-id=bael-client-id -spring.security.oauth2.client.registration.bael.client-secret=bael-secret -spring.security.oauth2.client.provider.bael.token-uri=http://localhost:8085/oauth/token +spring.security.oauth2.client.registration.bael.client-id=fooClientIdPassword +spring.security.oauth2.client.registration.bael.client-secret=secret +spring.security.oauth2.client.provider.bael.token-uri=http://localhost:8081/spring-security-oauth-server/oauth/token diff --git a/spring-5-reactive-oauth/src/main/resources/webclient-manual-request-oauth-application.properties b/spring-5-reactive-oauth/src/main/resources/webclient-manual-request-oauth-application.properties new file mode 100644 index 0000000000..36ec3defd1 --- /dev/null +++ b/spring-5-reactive-oauth/src/main/resources/webclient-manual-request-oauth-application.properties @@ -0,0 +1,3 @@ +the.authorization.client-id=fooClientIdPassword +the.authorization.client-secret=secret +the.authorization.token-uri=http://localhost:8081/spring-security-oauth-server/oauth/token diff --git a/spring-5-reactive-oauth/src/test/java/com/baeldung/webclient/clientcredentials/OAuth2ClientCredentialsLiveTest.java b/spring-5-reactive-oauth/src/test/java/com/baeldung/webclient/clientcredentials/OAuth2ClientCredentialsLiveTest.java index e31815c3f8..ef913ba055 100644 --- a/spring-5-reactive-oauth/src/test/java/com/baeldung/webclient/clientcredentials/OAuth2ClientCredentialsLiveTest.java +++ b/spring-5-reactive-oauth/src/test/java/com/baeldung/webclient/clientcredentials/OAuth2ClientCredentialsLiveTest.java @@ -19,9 +19,9 @@ import ch.qos.logback.classic.spi.ILoggingEvent; /** * - * Note: this Live test requires the Authorization Service and the Resource service located in the spring-5-security-oauth module + * Note: this Live test requires the Authorization Service and the Resource service located in the Baeldung/spring-security-oauth repo * - * @author ger + * @author rozagerardo * */ @RunWith(SpringRunner.class) @@ -46,7 +46,7 @@ public class OAuth2ClientCredentialsLiveTest { .stream() .map(ILoggingEvent::getFormattedMessage) .collect(Collectors.toList()); - assertThat(allLoggedEntries).anyMatch(entry -> entry.contains("We retrieved the following resource using Client Credentials Grant Type: This is the resource!")); + assertThat(allLoggedEntries).anyMatch(entry -> entry.contains("We retrieved the following resource using Client Credentials Grant Type: {\"id\"")); } } diff --git a/spring-5-reactive-oauth/src/test/java/com/baeldung/webclient/manualrequest/OAuth2ManualRequestLiveTest.java b/spring-5-reactive-oauth/src/test/java/com/baeldung/webclient/manualrequest/OAuth2ManualRequestLiveTest.java index 94aa580f0a..2381264926 100644 --- a/spring-5-reactive-oauth/src/test/java/com/baeldung/webclient/manualrequest/OAuth2ManualRequestLiveTest.java +++ b/spring-5-reactive-oauth/src/test/java/com/baeldung/webclient/manualrequest/OAuth2ManualRequestLiveTest.java @@ -1,5 +1,6 @@ package com.baeldung.webclient.manualrequest; +import org.hamcrest.Matchers; import org.junit.Before; import org.junit.Test; import org.springframework.test.web.reactive.server.WebTestClient; @@ -8,7 +9,7 @@ import org.springframework.test.web.reactive.server.WebTestClient.ResponseSpec; /** * * Note: this Live test requires not only the corresponding application running, - * but also the Authorization Service and the Resource service located in the spring-5-security-oauth module. + * but also the Authorization Service and the Resource service located in the Baeldung/spring-security-oauth repo * * * @author ger @@ -37,7 +38,7 @@ public class OAuth2ManualRequestLiveTest { response.expectStatus() .isOk() .expectBody(String.class) - .isEqualTo("Retrieved the resource using a manual approach: This is the resource!"); + .value(Matchers.containsString("Retrieved the resource using a manual approach: {\"id\"")); } } diff --git a/spring-5-security-oauth/src/main/java/com/baeldung/webclient/authorizationserver/AuthorizationServerApplication.java b/spring-5-security-oauth/src/main/java/com/baeldung/webclient/authorizationserver/AuthorizationServerApplication.java deleted file mode 100644 index d72704386c..0000000000 --- a/spring-5-security-oauth/src/main/java/com/baeldung/webclient/authorizationserver/AuthorizationServerApplication.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.baeldung.webclient.authorizationserver; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.annotation.PropertySource; -import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; - -@EnableAuthorizationServer -@PropertySource("classpath:webclient-authorization-application.properties") -@SpringBootApplication -public class AuthorizationServerApplication { - - public static void main(String[] args) { - SpringApplication.run(AuthorizationServerApplication.class, args); - } - -} diff --git a/spring-5-security-oauth/src/main/java/com/baeldung/webclient/authorizationserver/configuration/WebSecurityConfig.java b/spring-5-security-oauth/src/main/java/com/baeldung/webclient/authorizationserver/configuration/WebSecurityConfig.java deleted file mode 100644 index 5dd15f1b8c..0000000000 --- a/spring-5-security-oauth/src/main/java/com/baeldung/webclient/authorizationserver/configuration/WebSecurityConfig.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.baeldung.webclient.authorizationserver.configuration; - -import org.springframework.context.annotation.Configuration; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; - -@EnableWebSecurity -@Configuration -public class WebSecurityConfig extends WebSecurityConfigurerAdapter { - - @Override - protected void configure(HttpSecurity http) throws Exception { - http.authorizeRequests() - .antMatchers("/login", "/user") - .permitAll() - .and() - .authorizeRequests() - .anyRequest() - .authenticated() - .and() - .formLogin() - .and() - .httpBasic(); - } -} diff --git a/spring-5-security-oauth/src/main/java/com/baeldung/webclient/resourceserver/ResourceServerApplication.java b/spring-5-security-oauth/src/main/java/com/baeldung/webclient/resourceserver/ResourceServerApplication.java deleted file mode 100644 index 50ad293ef8..0000000000 --- a/spring-5-security-oauth/src/main/java/com/baeldung/webclient/resourceserver/ResourceServerApplication.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.baeldung.webclient.resourceserver; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.annotation.PropertySource; -import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; - -@EnableResourceServer -@PropertySource("webclient-resources-application.properties") -@SpringBootApplication -public class ResourceServerApplication { - - public static void main(String[] args) { - SpringApplication.run(ResourceServerApplication.class, args); - } - -} diff --git a/spring-5-security-oauth/src/main/java/com/baeldung/webclient/resourceserver/configuration/AuthorizationConfigs.java b/spring-5-security-oauth/src/main/java/com/baeldung/webclient/resourceserver/configuration/AuthorizationConfigs.java deleted file mode 100644 index 5aea1983db..0000000000 --- a/spring-5-security-oauth/src/main/java/com/baeldung/webclient/resourceserver/configuration/AuthorizationConfigs.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.baeldung.webclient.resourceserver.configuration; - -import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.security.oauth2.provider.token.RemoteTokenServices; -import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices; - -@Configuration -public class AuthorizationConfigs { - - @Value("${oauth.authserver.client-id}") - String clientId; - - @Value("${oauth.authserver.client-secret}") - String clientSecret; - - @Value("${oauth.authserver.check-token-endpoint}") - String checkTokenEndpoint; - - @Bean - public ResourceServerTokenServices tokenSvc() { - RemoteTokenServices remoteService = new RemoteTokenServices(); - remoteService.setCheckTokenEndpointUrl(checkTokenEndpoint); - remoteService.setClientId(clientId); - remoteService.setClientSecret(clientSecret); - return remoteService; - } -} diff --git a/spring-5-security-oauth/src/main/java/com/baeldung/webclient/resourceserver/web/ResourceRestController.java b/spring-5-security-oauth/src/main/java/com/baeldung/webclient/resourceserver/web/ResourceRestController.java deleted file mode 100644 index aef0fb4d7d..0000000000 --- a/spring-5-security-oauth/src/main/java/com/baeldung/webclient/resourceserver/web/ResourceRestController.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.baeldung.webclient.resourceserver.web; - -import java.security.Principal; - -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.ResponseBody; -import org.springframework.web.bind.annotation.RestController; - -@RestController -public class ResourceRestController { - - @GetMapping("/retrieve-resource") - public String retrieveResource() { - return "This is the resource!"; - } - - @GetMapping("/user") - @ResponseBody - public Principal user(Principal user) { - return user; - } - -} diff --git a/spring-5-security-oauth/src/main/resources/webclient-authorization-application.properties b/spring-5-security-oauth/src/main/resources/webclient-authorization-application.properties deleted file mode 100644 index 9531045359..0000000000 --- a/spring-5-security-oauth/src/main/resources/webclient-authorization-application.properties +++ /dev/null @@ -1,13 +0,0 @@ -server.port=8085 - -security.oauth2.client.client-id=bael-client-id -security.oauth2.client.client-secret=bael-secret -security.oauth2.client.scope=read,write - -security.oauth2.authorization.check-token-access=isAuthenticated() - -spring.security.user.name=bael-user -spring.security.user.password=bael-password - -security.oauth2.client.registered-redirect-uri=http://localhost:8080/login/oauth2/code/bael, http://localhost:8080/authorize/oauth2/code/bael -security.oauth2.client.use-current-uri=false \ No newline at end of file diff --git a/spring-5-security-oauth/src/main/resources/webclient-resources-application.properties b/spring-5-security-oauth/src/main/resources/webclient-resources-application.properties deleted file mode 100644 index 1cfb9ca12d..0000000000 --- a/spring-5-security-oauth/src/main/resources/webclient-resources-application.properties +++ /dev/null @@ -1,6 +0,0 @@ -server.port=8084 - -#spring.security.oauth2.resourceserver.jwt.issuer-uri=localhost:8085 -oauth.authserver.client-id=bael-client-id -oauth.authserver.client-secret=bael-secret -oauth.authserver.check-token-endpoint=http://localhost:8085/oauth/check_token diff --git a/spring-boot-bootstrap/pom.xml b/spring-boot-bootstrap/pom.xml index 7cafc5aa24..0ffc1820b8 100644 --- a/spring-boot-bootstrap/pom.xml +++ b/spring-boot-bootstrap/pom.xml @@ -57,6 +57,27 @@ + + beanstalk + + ${project.name}-eb + + + org.springframework.boot + spring-boot-maven-plugin + + + org.apache.maven.plugins + maven-compiler-plugin + + + **/cloud/config/*.java + + + + + + openshift diff --git a/spring-boot-bootstrap/src/main/resources/application-beanstalk.properties b/spring-boot-bootstrap/src/main/resources/application-beanstalk.properties new file mode 100644 index 0000000000..de03a3b5bb --- /dev/null +++ b/spring-boot-bootstrap/src/main/resources/application-beanstalk.properties @@ -0,0 +1,3 @@ +spring.datasource.url=jdbc:mysql://${rds.hostname}:${rds.port}/${rds.db.name} +spring.datasource.username=${rds.username} +spring.datasource.password=${rds.password} \ No newline at end of file diff --git a/spring-boot-rest/README.md b/spring-boot-rest/README.md new file mode 100644 index 0000000000..0a8d13cf76 --- /dev/null +++ b/spring-boot-rest/README.md @@ -0,0 +1,3 @@ +Module for the articles that are part of the Spring REST E-book: + +1. [Bootstrap a Web Application with Spring 5](https://www.baeldung.com/bootstraping-a-web-application-with-spring-and-java-based-configuration) diff --git a/spring-boot-rest/pom.xml b/spring-boot-rest/pom.xml new file mode 100644 index 0000000000..baf9d35a09 --- /dev/null +++ b/spring-boot-rest/pom.xml @@ -0,0 +1,43 @@ + + + 4.0.0 + com.baeldung.web + spring-boot-rest + spring-boot-rest + Spring Boot Rest Module + war + + + parent-boot-2 + com.baeldung + 0.0.1-SNAPSHOT + ../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + com.baeldung.SpringBootRestApplication + + diff --git a/spring-boot-rest/src/main/java/com/baeldung/web/SpringBootRestApplication.java b/spring-boot-rest/src/main/java/com/baeldung/web/SpringBootRestApplication.java new file mode 100644 index 0000000000..62aae7619d --- /dev/null +++ b/spring-boot-rest/src/main/java/com/baeldung/web/SpringBootRestApplication.java @@ -0,0 +1,13 @@ +package com.baeldung; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringBootRestApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringBootRestApplication.class, args); + } + +} diff --git a/spring-boot-rest/src/main/java/com/baeldung/web/config/WebConfig.java b/spring-boot-rest/src/main/java/com/baeldung/web/config/WebConfig.java new file mode 100644 index 0000000000..808e946218 --- /dev/null +++ b/spring-boot-rest/src/main/java/com/baeldung/web/config/WebConfig.java @@ -0,0 +1,8 @@ +package com.baeldung.web.config; + +import org.springframework.context.annotation.Configuration; + +@Configuration +public class WebConfig { + +} \ No newline at end of file diff --git a/spring-boot-rest/src/main/resources/application.properties b/spring-boot-rest/src/main/resources/application.properties new file mode 100644 index 0000000000..e69de29bb2 diff --git a/spring-boot-rest/src/test/java/com/baeldung/web/SpringContextIntegrationTest.java b/spring-boot-rest/src/test/java/com/baeldung/web/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..0c1fdf372b --- /dev/null +++ b/spring-boot-rest/src/test/java/com/baeldung/web/SpringContextIntegrationTest.java @@ -0,0 +1,16 @@ +package com.baeldung.spring.boot.rest; + +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 SpringContextIntegrationTest { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-kafka/pom.xml b/spring-kafka/pom.xml index 5c370880b4..b76d4f10c0 100644 --- a/spring-kafka/pom.xml +++ b/spring-kafka/pom.xml @@ -33,7 +33,7 @@ - 1.1.3.RELEASE + 2.2.2.RELEASE 2.9.7 diff --git a/spring-kafka/src/main/java/com/baeldung/spring/kafka/KafkaApplication.java b/spring-kafka/src/main/java/com/baeldung/spring/kafka/KafkaApplication.java index 4ee7f40335..b313eafdb9 100644 --- a/spring-kafka/src/main/java/com/baeldung/spring/kafka/KafkaApplication.java +++ b/spring-kafka/src/main/java/com/baeldung/spring/kafka/KafkaApplication.java @@ -13,8 +13,11 @@ import org.springframework.kafka.annotation.KafkaListener; import org.springframework.kafka.annotation.TopicPartition; import org.springframework.kafka.core.KafkaTemplate; import org.springframework.kafka.support.KafkaHeaders; +import org.springframework.kafka.support.SendResult; import org.springframework.messaging.handler.annotation.Header; import org.springframework.messaging.handler.annotation.Payload; +import org.springframework.util.concurrent.ListenableFuture; +import org.springframework.util.concurrent.ListenableFutureCallback; @SpringBootApplication public class KafkaApplication { @@ -98,7 +101,20 @@ public class KafkaApplication { private String greetingTopicName; public void sendMessage(String message) { - kafkaTemplate.send(topicName, message); + + ListenableFuture> future = kafkaTemplate.send(topicName, message); + + future.addCallback(new ListenableFutureCallback>() { + + @Override + public void onSuccess(SendResult result) { + System.out.println("Sent message=[" + message + "] with offset=[" + result.getRecordMetadata().offset() + "]"); + } + @Override + public void onFailure(Throwable ex) { + System.out.println("Unable to send message=[" + message + "] due to : " + ex.getMessage()); + } + }); } public void sendMessageToPartion(String message, int partition) { diff --git a/spring-kafka/src/main/java/com/baeldung/spring/kafka/KafkaTopicConfig.java b/spring-kafka/src/main/java/com/baeldung/spring/kafka/KafkaTopicConfig.java new file mode 100644 index 0000000000..a3426e78a3 --- /dev/null +++ b/spring-kafka/src/main/java/com/baeldung/spring/kafka/KafkaTopicConfig.java @@ -0,0 +1,57 @@ +package com.baeldung.spring.kafka; + +import java.util.HashMap; +import java.util.Map; + +import org.apache.kafka.clients.admin.AdminClientConfig; +import org.apache.kafka.clients.admin.NewTopic; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.kafka.core.KafkaAdmin; + +@Configuration +public class KafkaTopicConfig { + + @Value(value = "${kafka.bootstrapAddress}") + private String bootstrapAddress; + + @Value(value = "${message.topic.name}") + private String topicName; + + @Value(value = "${partitioned.topic.name}") + private String partionedTopicName; + + @Value(value = "${filtered.topic.name}") + private String filteredTopicName; + + @Value(value = "${greeting.topic.name}") + private String greetingTopicName; + + @Bean + public KafkaAdmin kafkaAdmin() { + Map configs = new HashMap<>(); + configs.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapAddress); + return new KafkaAdmin(configs); + } + + @Bean + public NewTopic topic1() { + return new NewTopic(topicName, 1, (short) 1); + } + + @Bean + public NewTopic topic2() { + return new NewTopic(partionedTopicName, 6, (short) 1); + } + + @Bean + public NewTopic topic3() { + return new NewTopic(filteredTopicName, 1, (short) 1); + } + + @Bean + public NewTopic topic4() { + return new NewTopic(greetingTopicName, 1, (short) 1); + } +} diff --git a/spring-kafka/src/test/java/org/baeldung/SpringContextLiveTest.java b/spring-kafka/src/test/java/org/baeldung/SpringContextLiveTest.java new file mode 100644 index 0000000000..d8fb3131f5 --- /dev/null +++ b/spring-kafka/src/test/java/org/baeldung/SpringContextLiveTest.java @@ -0,0 +1,17 @@ +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; + +import com.baeldung.spring.kafka.KafkaApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = KafkaApplication.class) +public class SpringContextLiveTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-mvc-java/README.md b/spring-mvc-java/README.md index c7fcbd400b..851a3689ab 100644 --- a/spring-mvc-java/README.md +++ b/spring-mvc-java/README.md @@ -11,7 +11,6 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Introduction to Advice Types in Spring](http://www.baeldung.com/spring-aop-advice-tutorial) - [A Guide to the ViewResolver in Spring MVC](http://www.baeldung.com/spring-mvc-view-resolver-tutorial) - [Integration Testing in Spring](http://www.baeldung.com/integration-testing-in-spring) -- [Spring JSON-P with Jackson](http://www.baeldung.com/spring-jackson-jsonp) - [A Quick Guide to Spring MVC Matrix Variables](http://www.baeldung.com/spring-mvc-matrix-variables) - [Intro to WebSockets with Spring](http://www.baeldung.com/websockets-spring) - [File Upload with Spring MVC](http://www.baeldung.com/spring-file-upload) diff --git a/spring-mvc-java/pom.xml b/spring-mvc-java/pom.xml index 9d3e0ca1b2..562df30318 100644 --- a/spring-mvc-java/pom.xml +++ b/spring-mvc-java/pom.xml @@ -60,6 +60,12 @@ commons-fileupload commons-fileupload ${commons-fileupload.version} + + + commons-io + commons-io + + net.sourceforge.htmlunit @@ -70,8 +76,17 @@ commons-logging commons-logging + + commons-io + commons-io + + + commons-io + commons-io + ${commons-io.version} + @@ -255,6 +270,7 @@ 19.0 3.5 1.3.2 + 2.5 2.2.0 diff --git a/spring-mvc-java/src/main/java/com/baeldung/web/controller/CompanyController.java b/spring-mvc-java/src/main/java/com/baeldung/web/controller/CompanyController.java index e92abfdc47..af1e729c13 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/web/controller/CompanyController.java +++ b/spring-mvc-java/src/main/java/com/baeldung/web/controller/CompanyController.java @@ -60,17 +60,4 @@ public class CompanyController { result.put("name", name); return new ResponseEntity<>(result, HttpStatus.OK); } - - @RequestMapping(value = "/companyResponseBody", produces = MediaType.APPLICATION_JSON_VALUE) - @ResponseBody - public Company getCompanyResponseBody() { - final Company company = new Company(2, "ABC"); - return company; - } - - @RequestMapping(value = "/companyResponseEntity", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity getCompanyResponseEntity() { - final Company company = new Company(3, "123"); - return new ResponseEntity(company, HttpStatus.OK); - } } diff --git a/spring-mvc-java/src/test/java/com/baeldung/config/HandlerMappingDefaultConfig.java b/spring-mvc-java/src/test/java/com/baeldung/config/HandlerMappingDefaultConfig.java index 9190d07d6b..d3a329a387 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/config/HandlerMappingDefaultConfig.java +++ b/spring-mvc-java/src/test/java/com/baeldung/config/HandlerMappingDefaultConfig.java @@ -1,15 +1,10 @@ package com.baeldung.config; -import com.baeldung.web.controller.handlermapping.BeanNameHandlerMappingController; -import com.baeldung.web.controller.handlermapping.SimpleUrlMappingController; -import com.baeldung.web.controller.handlermapping.WelcomeController; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping; -import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping; -import java.util.HashMap; -import java.util.Map; +import com.baeldung.web.controller.handlermapping.BeanNameHandlerMappingController; +import com.baeldung.web.controller.handlermapping.WelcomeController; @Configuration diff --git a/spring-mvc-java/src/test/java/com/baeldung/htmlunit/TestConfig.java b/spring-mvc-java/src/test/java/com/baeldung/htmlunit/TestConfig.java index 5b86b59095..529879fada 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/htmlunit/TestConfig.java +++ b/spring-mvc-java/src/test/java/com/baeldung/htmlunit/TestConfig.java @@ -9,7 +9,6 @@ import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.thymeleaf.spring4.SpringTemplateEngine; import org.thymeleaf.spring4.view.ThymeleafViewResolver; import org.thymeleaf.templateresolver.ServletContextTemplateResolver; diff --git a/spring-mvc-java/src/test/java/com/baeldung/web/controller/ClassValidationMvcIntegrationTest.java b/spring-mvc-java/src/test/java/com/baeldung/web/controller/ClassValidationMvcIntegrationTest.java index a86f71011c..2cd225a775 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/web/controller/ClassValidationMvcIntegrationTest.java +++ b/spring-mvc-java/src/test/java/com/baeldung/web/controller/ClassValidationMvcIntegrationTest.java @@ -1,6 +1,5 @@ package com.baeldung.web.controller; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; diff --git a/spring-mvc-java/src/test/java/com/baeldung/web/controller/GreetControllerIntegrationTest.java b/spring-mvc-java/src/test/java/com/baeldung/web/controller/GreetControllerIntegrationTest.java index 384bd85ec6..bce5ab0a8c 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/web/controller/GreetControllerIntegrationTest.java +++ b/spring-mvc-java/src/test/java/com/baeldung/web/controller/GreetControllerIntegrationTest.java @@ -20,7 +20,6 @@ import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; -import com.baeldung.spring.web.config.WebConfig; import com.baeldung.spring.web.config.WebConfig; @RunWith(SpringJUnit4ClassRunner.class) diff --git a/spring-mvc-simple/pom.xml b/spring-mvc-simple/pom.xml index 65fa4339d6..087ffea46d 100644 --- a/spring-mvc-simple/pom.xml +++ b/spring-mvc-simple/pom.xml @@ -154,25 +154,6 @@ ${deploy-path} - - maven-surefire-plugin - ${maven-surefire-plugin.version} - - - default-test - - true - - - - - - org.junit.platform - junit-platform-surefire-provider - ${junit.platform.version} - - - spring-mvc-simple diff --git a/spring-security-mvc-login/src/main/java/com/baeldung/spring/MvcConfig.java b/spring-security-mvc-login/src/main/java/com/baeldung/spring/MvcConfig.java index a9c7e0cf15..082477c98c 100644 --- a/spring-security-mvc-login/src/main/java/com/baeldung/spring/MvcConfig.java +++ b/spring-security-mvc-login/src/main/java/com/baeldung/spring/MvcConfig.java @@ -1,7 +1,6 @@ package com.baeldung.spring; import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.EnableWebMvc; diff --git a/spring-security-rest-basic-auth/src/main/java/org/baeldung/client/RestTemplateFactory.java b/spring-security-rest-basic-auth/src/main/java/org/baeldung/client/RestTemplateFactory.java index 5e15648e9b..3ed0bc82b7 100644 --- a/spring-security-rest-basic-auth/src/main/java/org/baeldung/client/RestTemplateFactory.java +++ b/spring-security-rest-basic-auth/src/main/java/org/baeldung/client/RestTemplateFactory.java @@ -4,7 +4,7 @@ import org.apache.http.HttpHost; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.InitializingBean; import org.springframework.http.client.ClientHttpRequestFactory; -import org.springframework.http.client.support.BasicAuthorizationInterceptor; +import org.springframework.http.client.support.BasicAuthenticationInterceptor; import org.springframework.stereotype.Component; import org.springframework.web.client.RestTemplate; @@ -38,7 +38,7 @@ public class RestTemplateFactory implements FactoryBean, Initializ HttpHost host = new HttpHost("localhost", 8082, "http"); final ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactoryBasicAuth(host); restTemplate = new RestTemplate(requestFactory); - restTemplate.getInterceptors().add(new BasicAuthorizationInterceptor("user1", "user1Pass")); + restTemplate.getInterceptors().add(new BasicAuthenticationInterceptor("user1", "user1Pass")); } } \ No newline at end of file diff --git a/spring-security-rest-basic-auth/src/main/java/org/baeldung/spring/WebConfig.java b/spring-security-rest-basic-auth/src/main/java/org/baeldung/spring/WebConfig.java index 2305a7b6c2..5876e1307b 100644 --- a/spring-security-rest-basic-auth/src/main/java/org/baeldung/spring/WebConfig.java +++ b/spring-security-rest-basic-auth/src/main/java/org/baeldung/spring/WebConfig.java @@ -8,7 +8,6 @@ import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Configuration @EnableWebMvc diff --git a/spring-security-rest-basic-auth/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-security-rest-basic-auth/src/test/java/org/baeldung/SpringContextIntegrationTest.java index 6cf624c179..31b3f2be87 100644 --- a/spring-security-rest-basic-auth/src/test/java/org/baeldung/SpringContextIntegrationTest.java +++ b/spring-security-rest-basic-auth/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -6,7 +6,7 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration({ "/WebSecurityConfig.xml" }) +@ContextConfiguration({ "/webSecurityConfig.xml" }) public class SpringContextIntegrationTest { @Test diff --git a/spring-security-rest/src/test/java/org/baeldung/web/FooLiveTest.java b/spring-security-rest/src/test/java/org/baeldung/web/FooLiveTest.java index 0a53da674a..86beeb46a9 100644 --- a/spring-security-rest/src/test/java/org/baeldung/web/FooLiveTest.java +++ b/spring-security-rest/src/test/java/org/baeldung/web/FooLiveTest.java @@ -29,7 +29,7 @@ public class FooLiveTest { // } // return RestAssured.given().cookie("JSESSIONID", cookie); return RestAssured.given() - .auth() + .auth().preemptive() .basic("user", "userPass"); } diff --git a/spring-static-resources/src/main/java/org/baeldung/spring/MvcConfig.java b/spring-static-resources/src/main/java/org/baeldung/spring/MvcConfig.java index dbc548e028..7bd03617be 100644 --- a/spring-static-resources/src/main/java/org/baeldung/spring/MvcConfig.java +++ b/spring-static-resources/src/main/java/org/baeldung/spring/MvcConfig.java @@ -18,7 +18,7 @@ import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.i18n.CookieLocaleResolver; import org.springframework.web.servlet.i18n.LocaleChangeInterceptor; -import org.springframework.web.servlet.resource.GzipResourceResolver; +import org.springframework.web.servlet.resource.EncodedResourceResolver; import org.springframework.web.servlet.resource.PathResourceResolver; import org.springframework.web.servlet.resource.ResourceUrlEncodingFilter; import org.springframework.web.servlet.view.InternalResourceViewResolver; @@ -57,10 +57,10 @@ public class MvcConfig implements WebMvcConfigurer { public void addResourceHandlers(ResourceHandlerRegistry registry) { // For examples using Spring 4.1.0 if ((env.getProperty("resource.handler.conf")).equals("4.1.0")) { - registry.addResourceHandler("/js/**").addResourceLocations("/js/").setCachePeriod(3600).resourceChain(true).addResolver(new GzipResourceResolver()).addResolver(new PathResourceResolver()); + registry.addResourceHandler("/js/**").addResourceLocations("/js/").setCachePeriod(3600).resourceChain(true).addResolver(new EncodedResourceResolver()).addResolver(new PathResourceResolver()); registry.addResourceHandler("/resources/**").addResourceLocations("/resources/", "classpath:/other-resources/").setCachePeriod(3600).resourceChain(true).addResolver(new PathResourceResolver()); registry.addResourceHandler("/files/**").addResourceLocations("file:/Users/Elena/").setCachePeriod(3600).resourceChain(true).addResolver(new PathResourceResolver()); - registry.addResourceHandler("/other-files/**").addResourceLocations("file:/Users/Elena/").setCachePeriod(3600).resourceChain(true).addResolver(new GzipResourceResolver()); + registry.addResourceHandler("/other-files/**").addResourceLocations("file:/Users/Elena/").setCachePeriod(3600).resourceChain(true).addResolver(new EncodedResourceResolver()); } // For examples using Spring 4.0.7 else if ((env.getProperty("resource.handler.conf")).equals("4.0.7")) {