diff --git a/JGit/pom.xml b/JGit/pom.xml index 176d55d321..deae1e45e3 100644 --- a/JGit/pom.xml +++ b/JGit/pom.xml @@ -5,9 +5,9 @@ com.baeldung JGit 1.0-SNAPSHOT + JGit jar http://maven.apache.org - JGit com.baeldung diff --git a/Twitter4J/pom.xml b/Twitter4J/pom.xml index 982c1adc23..b82b9f6778 100644 --- a/Twitter4J/pom.xml +++ b/Twitter4J/pom.xml @@ -2,8 +2,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 Twitter4J - jar Twitter4J + jar com.baeldung diff --git a/akka-http/pom.xml b/akka-http/pom.xml index 51e70fb583..05e50d2229 100644 --- a/akka-http/pom.xml +++ b/akka-http/pom.xml @@ -23,7 +23,7 @@ com.typesafe.akka akka-stream_2.12 - 2.5.11 + ${akka.stream.version} com.typesafe.akka diff --git a/algorithms-miscellaneous-1/README.md b/algorithms-miscellaneous-1/README.md index 6f18396005..7ed805f7c4 100644 --- a/algorithms-miscellaneous-1/README.md +++ b/algorithms-miscellaneous-1/README.md @@ -15,3 +15,5 @@ - [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) +- [Permutations of an Array in Java](https://www.baeldung.com/java-array-permutations) +- [Implementing Simple State Machines with Java Enums](https://www.baeldung.com/java-enum-simple-state-machine) diff --git a/algorithms-miscellaneous-2/pom.xml b/algorithms-miscellaneous-2/pom.xml index 5461f4ebe1..d5f3172eaa 100644 --- a/algorithms-miscellaneous-2/pom.xml +++ b/algorithms-miscellaneous-2/pom.xml @@ -68,7 +68,7 @@ org.codehaus.mojo cobertura-maven-plugin - 2.7 + ${cobertura-maven-plugin.version} @@ -91,6 +91,7 @@ 1.0.1 3.9.0 1.11 + 2.7 \ No newline at end of file diff --git a/algorithms-miscellaneous-2/src/test/resources/graph.png b/algorithms-miscellaneous-2/src/test/resources/graph.png index 56995b8dd9..7165a51782 100644 Binary files a/algorithms-miscellaneous-2/src/test/resources/graph.png and b/algorithms-miscellaneous-2/src/test/resources/graph.png differ diff --git a/animal-sniffer-mvn-plugin/pom.xml b/animal-sniffer-mvn-plugin/pom.xml index cdfb1fb2a3..55e37e2ec4 100644 --- a/animal-sniffer-mvn-plugin/pom.xml +++ b/animal-sniffer-mvn-plugin/pom.xml @@ -3,9 +3,9 @@ 4.0.0 com.baeldung animal-sniffer-mvn-plugin - jar 1.0-SNAPSHOT animal-sniffer-mvn-plugin + jar http://maven.apache.org diff --git a/annotations/pom.xml b/annotations/pom.xml index 6d83f5b057..5fe89adf0a 100644 --- a/annotations/pom.xml +++ b/annotations/pom.xml @@ -3,8 +3,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 annotations - pom annotations + pom parent-modules diff --git a/apache-avro/pom.xml b/apache-avro/pom.xml index 18f9c34d64..b98e52be75 100644 --- a/apache-avro/pom.xml +++ b/apache-avro/pom.xml @@ -7,14 +7,6 @@ 0.0.1-SNAPSHOT apache-avro - - UTF-8 - 3.5 - 1.8.2 - 1.8 - 1.7.25 - - com.baeldung parent-modules @@ -85,4 +77,13 @@ + + + UTF-8 + 3.5 + 1.8.2 + 1.8 + 1.7.25 + + diff --git a/apache-curator/pom.xml b/apache-curator/pom.xml index e6be32277d..3306c0613f 100644 --- a/apache-curator/pom.xml +++ b/apache-curator/pom.xml @@ -3,8 +3,8 @@ 4.0.0 apache-curator 0.0.1-SNAPSHOT - jar apache-curator + jar com.baeldung diff --git a/apache-geode/pom.xml b/apache-geode/pom.xml index 738accdcb8..a39e4a811e 100644 --- a/apache-geode/pom.xml +++ b/apache-geode/pom.xml @@ -12,22 +12,6 @@ parent-modules 1.0.0-SNAPSHOT - - - 1.6.0 - - - - - org.apache.maven.plugins - maven-compiler-plugin - - 1.8 - 1.8 - - - - @@ -38,8 +22,26 @@ junit junit - RELEASE + ${junit.version} + + + + org.apache.maven.plugins + maven-compiler-plugin + + ${maven.compiler.source} + ${maven.compiler.target} + + + + + + + 1.6.0 + 1.8 + 1.8 + \ No newline at end of file diff --git a/apache-meecrowave/pom.xml b/apache-meecrowave/pom.xml index cf13aa1c1b..fb5af69f9b 100644 --- a/apache-meecrowave/pom.xml +++ b/apache-meecrowave/pom.xml @@ -7,51 +7,58 @@ apache-meecrowave A sample REST API application with Meecrowave - - 1.8 - 1.8 - org.apache.meecrowave meecrowave-core - 1.2.1 + ${meecrowave-core.version} org.apache.meecrowave meecrowave-jpa - 1.2.1 + ${meecrowave-jpa.version} com.squareup.okhttp3 okhttp - 3.10.0 + ${okhttp.version} org.apache.meecrowave meecrowave-junit - 1.2.0 + ${meecrowave-junit.version} test junit junit - 4.10 + ${junit.version} test - + org.apache.meecrowave meecrowave-maven-plugin - 1.2.1 + ${meecrowave-maven-plugin.version} + + + 1.8 + 1.8 + 4.10 + 1.2.0 + 3.10.0 + 1.2.1 + 1.2.1 + 1.2.1 + \ No newline at end of file diff --git a/apache-pulsar/pom.xml b/apache-pulsar/pom.xml index a4c09586eb..11df6d0b87 100644 --- a/apache-pulsar/pom.xml +++ b/apache-pulsar/pom.xml @@ -11,12 +11,14 @@ org.apache.pulsar pulsar-client - 2.1.1-incubating + ${pulsar-client.version} compile + 1.8 1.8 + 2.1.1-incubating diff --git a/apache-solrj/pom.xml b/apache-solrj/pom.xml index 9a807c2f26..1227fdca46 100644 --- a/apache-solrj/pom.xml +++ b/apache-solrj/pom.xml @@ -4,8 +4,8 @@ com.baeldung apache-solrj 0.0.1-SNAPSHOT - jar apache-solrj + jar com.baeldung diff --git a/apache-spark/README.md b/apache-spark/README.md index fb8059eb27..a4dce212b4 100644 --- a/apache-spark/README.md +++ b/apache-spark/README.md @@ -1,3 +1,4 @@ ### Relevant articles - [Introduction to Apache Spark](http://www.baeldung.com/apache-spark) +- [Building a Data Pipeline with Kafka, Spark Streaming and Cassandra](https://www.baeldung.com/kafka-spark-data-pipeline) diff --git a/apache-spark/pom.xml b/apache-spark/pom.xml index b05b97198d..1aed5b1db9 100644 --- a/apache-spark/pom.xml +++ b/apache-spark/pom.xml @@ -4,8 +4,8 @@ com.baeldung apache-spark 1.0-SNAPSHOT - jar apache-spark + jar http://maven.apache.org @@ -54,10 +54,10 @@ org.apache.maven.plugins maven-compiler-plugin - 3.2 + ${maven-compiler-plugin.version} - 1.8 - 1.8 + ${maven.compiler.source} + ${maven.compiler.target} @@ -85,6 +85,9 @@ 2.3.0 2.3.0 1.5.2 + 1.8 + 1.8 + 3.2 diff --git a/apache-velocity/pom.xml b/apache-velocity/pom.xml index 19cf77d945..a0a8389f7d 100644 --- a/apache-velocity/pom.xml +++ b/apache-velocity/pom.xml @@ -4,8 +4,8 @@ com.baeldung 0.1-SNAPSHOT apache-velocity - war apache-velocity + war com.baeldung diff --git a/aws-lambda/pom.xml b/aws-lambda/pom.xml index c47c3cd86f..c799718e61 100644 --- a/aws-lambda/pom.xml +++ b/aws-lambda/pom.xml @@ -5,8 +5,8 @@ com.baeldung aws-lambda 0.1.0-SNAPSHOT - jar aws-lambda + jar parent-modules diff --git a/aws/pom.xml b/aws/pom.xml index ab63f6afa1..560f9145f9 100644 --- a/aws/pom.xml +++ b/aws/pom.xml @@ -4,8 +4,8 @@ com.baeldung aws 0.1.0-SNAPSHOT - jar aws + jar com.baeldung diff --git a/axon/pom.xml b/axon/pom.xml index 598dc820e5..2b9ac1fcdd 100644 --- a/axon/pom.xml +++ b/axon/pom.xml @@ -36,7 +36,7 @@ org.springframework.boot spring-boot-autoconfigure - 2.1.1.RELEASE + ${spring-boot.version} compile diff --git a/azure/pom.xml b/azure/pom.xml index 555efeef70..e2a05796d6 100644 --- a/azure/pom.xml +++ b/azure/pom.xml @@ -5,9 +5,9 @@ com.baeldung azure 0.1 - war azure Demo project for Spring Boot on Azure + war parent-boot-2 diff --git a/blade/pom.xml b/blade/pom.xml index 6bad505f4a..37615bed01 100644 --- a/blade/pom.xml +++ b/blade/pom.xml @@ -3,12 +3,12 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 - blade - blade - com.baeldung + blade 1.0.0-SNAPSHOT + blade + @@ -17,35 +17,30 @@ - - 1.8 - 1.8 - - com.bladejava blade-mvc - 2.0.14.RELEASE + ${blade-mvc.version} org.webjars bootstrap - 4.2.1 + ${bootstrap.version} org.apache.commons commons-lang3 - 3.8.1 + ${commons-lang3.version} org.projectlombok lombok - 1.18.4 + ${lombok.version} provided @@ -53,31 +48,31 @@ junit junit - 4.12 + ${junit.version} test org.assertj assertj-core - 3.11.1 + ${assertj-core.version} test org.apache.httpcomponents httpclient - 4.5.6 + ${httpclient.version} test org.apache.httpcomponents httpmime - 4.5.6 + ${httpmime.version} test org.apache.httpcomponents httpcore - 4.4.10 + ${httpcore.version} test @@ -88,6 +83,7 @@ org.apache.maven.plugins maven-surefire-plugin + ${maven-surefire-plugin.version} 3 true @@ -100,7 +96,7 @@ org.apache.maven.plugins maven-failsafe-plugin - 3.0.0-M3 + ${maven-failsafe-plugin.version} **/*LiveTest.java @@ -119,7 +115,7 @@ com.bazaarvoice.maven.plugins process-exec-maven-plugin - 0.7 + ${process-exec-maven-plugin.version} @@ -177,13 +173,33 @@ + org.apache.maven.plugins maven-compiler-plugin + ${maven-compiler-plugin.version} - 1.8 - 1.8 + ${maven.compiler.source} + ${maven.compiler.target} UTF-8 + + + 1.8 + 1.8 + 2.0.14.RELEASE + 4.2.1 + 3.8.1 + 1.18.4 + 4.12 + 4.5.6 + 4.5.6 + 4.4.10 + 3.11.1 + 3.0.0-M3 + 0.7 + 2.21.0 + 3.7.0 + diff --git a/bootique/pom.xml b/bootique/pom.xml index 880b9a516f..4ae8703074 100644 --- a/bootique/pom.xml +++ b/bootique/pom.xml @@ -3,9 +3,9 @@ 4.0.0 com.baeldung.bootique bootique - jar 1.0-SNAPSHOT bootique + jar http://maven.apache.org diff --git a/cas/cas-secured-app/pom.xml b/cas/cas-secured-app/pom.xml index 2291da9084..338a9e5653 100644 --- a/cas/cas-secured-app/pom.xml +++ b/cas/cas-secured-app/pom.xml @@ -3,9 +3,9 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 cas-secured-app - jar cas-secured-app Demo project for CAS + jar parent-boot-1 diff --git a/cdi/pom.xml b/cdi/pom.xml index 0cf5062ccc..ba649127a0 100644 --- a/cdi/pom.xml +++ b/cdi/pom.xml @@ -59,6 +59,7 @@ test + 2.0.SP1 3.0.5.Final diff --git a/checker-plugin/pom.xml b/checker-plugin/pom.xml index 45f0939e77..08408366a4 100644 --- a/checker-plugin/pom.xml +++ b/checker-plugin/pom.xml @@ -3,9 +3,9 @@ 4.0.0 com.baeldung checker-plugin - jar 1.0-SNAPSHOT checker-plugin + jar http://maven.apache.org diff --git a/core-groovy/src/main/groovy/com/baeldung/file/ReadFile.groovy b/core-groovy/src/main/groovy/com/baeldung/file/ReadFile.groovy new file mode 100644 index 0000000000..4239fa534c --- /dev/null +++ b/core-groovy/src/main/groovy/com/baeldung/file/ReadFile.groovy @@ -0,0 +1,107 @@ +package com.baeldung.file + +class ReadFile { + + /** + * reads file content line by line using withReader and reader.readLine + * @param filePath + * @return + */ + int readFileLineByLine(String filePath) { + File file = new File(filePath) + def line, noOfLines = 0; + file.withReader { reader -> + while ((line = reader.readLine())!=null) + { + println "${line}" + noOfLines++ + } + } + return noOfLines + } + + /** + * reads file content in list of lines + * @param filePath + * @return + */ + List readFileInList(String filePath) { + File file = new File(filePath) + def lines = file.readLines() + return lines + } + + /** + * reads file content in string using File.text + * @param filePath + * @return + */ + String readFileString(String filePath) { + File file = new File(filePath) + String fileContent = file.text + return fileContent + } + + /** + * reads file content in string with encoding using File.getText + * @param filePath + * @return + */ + String readFileStringWithCharset(String filePath) { + File file = new File(filePath) + String utf8Content = file.getText("UTF-8") + return utf8Content + } + + /** + * reads content of binary file and returns byte array + * @param filePath + * @return + */ + byte[] readBinaryFile(String filePath) { + File file = new File(filePath) + byte[] binaryContent = file.bytes + return binaryContent + } + + /** + * More Examples of reading a file + * @return + */ + def moreExamples() { + + //with reader with utf-8 + new File("src/main/resources/utf8Content.html").withReader('UTF-8') { reader -> + def line + while ((line = reader.readLine())!=null) { + println "${line}" + } + } + + //collect api + def list = new File("src/main/resources/fileContent.txt").collect {it} + + //as operator + def array = new File("src/main/resources/fileContent.txt") as String[] + + //eachline + new File("src/main/resources/fileContent.txt").eachLine { line -> + println line + } + + //newInputStream with eachLine + def is = new File("src/main/resources/fileContent.txt").newInputStream() + is.eachLine { + println it + } + is.close() + + //withInputStream + new File("src/main/resources/fileContent.txt").withInputStream { stream -> + stream.eachLine { line -> + println line + } + } + } + +} \ No newline at end of file diff --git a/core-groovy/src/main/groovy/com/baeldung/strings/Concatenate.groovy b/core-groovy/src/main/groovy/com/baeldung/strings/Concatenate.groovy new file mode 100644 index 0000000000..b3a0852a0b --- /dev/null +++ b/core-groovy/src/main/groovy/com/baeldung/strings/Concatenate.groovy @@ -0,0 +1,43 @@ +package com.baeldung.strings; + +class Concatenate { + String first = 'Hello' + String last = 'Groovy' + + String doSimpleConcat() { + return 'My name is ' + first + ' ' + last + } + + String doConcatUsingGString() { + return "My name is $first $last" + } + + String doConcatUsingGStringClosures() { + return "My name is ${-> first} ${-> last}" + } + + String doConcatUsingStringConcatMethod() { + return 'My name is '.concat(first).concat(' ').concat(last) + } + + String doConcatUsingLeftShiftOperator() { + return 'My name is ' << first << ' ' << last + } + + String doConcatUsingArrayJoinMethod() { + return ['My name is', first, last].join(' ') + } + + String doConcatUsingArrayInjectMethod() { + return [first,' ', last] + .inject(new StringBuffer('My name is '), { initial, name -> initial.append(name); return initial }).toString() + } + + String doConcatUsingStringBuilder() { + return new StringBuilder().append('My name is ').append(first).append(' ').append(last) + } + + String doConcatUsingStringBuffer() { + return new StringBuffer().append('My name is ').append(first).append(' ').append(last) + } +} \ No newline at end of file diff --git a/core-groovy/src/main/groovy/com/baeldung/traits/AnimalTrait.groovy b/core-groovy/src/main/groovy/com/baeldung/traits/AnimalTrait.groovy new file mode 100644 index 0000000000..6ec5cda571 --- /dev/null +++ b/core-groovy/src/main/groovy/com/baeldung/traits/AnimalTrait.groovy @@ -0,0 +1,8 @@ +package com.baeldung.traits + +trait AnimalTrait { + + String basicBehavior() { + return "Animalistic!!" + } +} \ No newline at end of file diff --git a/core-groovy/src/main/groovy/com/baeldung/traits/Dog.groovy b/core-groovy/src/main/groovy/com/baeldung/traits/Dog.groovy new file mode 100644 index 0000000000..3e0677ba18 --- /dev/null +++ b/core-groovy/src/main/groovy/com/baeldung/traits/Dog.groovy @@ -0,0 +1,9 @@ +package com.baeldung.traits + +class Dog implements WalkingTrait, SpeakingTrait { + + String speakAndWalk() { + WalkingTrait.super.speakAndWalk() + } + +} \ No newline at end of file diff --git a/core-groovy/src/main/groovy/com/baeldung/traits/Employee.groovy b/core-groovy/src/main/groovy/com/baeldung/traits/Employee.groovy new file mode 100644 index 0000000000..b3e4285476 --- /dev/null +++ b/core-groovy/src/main/groovy/com/baeldung/traits/Employee.groovy @@ -0,0 +1,12 @@ +package com.baeldung.traits + +class Employee implements UserTrait { + + String name() { + return 'Bob' + } + + String lastName() { + return "Marley" + } +} \ No newline at end of file diff --git a/core-groovy/src/main/groovy/com/baeldung/traits/Human.groovy b/core-groovy/src/main/groovy/com/baeldung/traits/Human.groovy new file mode 100644 index 0000000000..e78d59bbfd --- /dev/null +++ b/core-groovy/src/main/groovy/com/baeldung/traits/Human.groovy @@ -0,0 +1,6 @@ +package com.baeldung.traits + +interface Human { + + String lastName() +} \ No newline at end of file diff --git a/core-groovy/src/main/groovy/com/baeldung/traits/SpeakingTrait.groovy b/core-groovy/src/main/groovy/com/baeldung/traits/SpeakingTrait.groovy new file mode 100644 index 0000000000..f437a94bd9 --- /dev/null +++ b/core-groovy/src/main/groovy/com/baeldung/traits/SpeakingTrait.groovy @@ -0,0 +1,13 @@ +package com.baeldung.traits + +trait SpeakingTrait { + + String basicAbility() { + return "Speaking!!" + } + + String speakAndWalk() { + return "Speak and walk!!" + } + +} \ No newline at end of file diff --git a/core-groovy/src/main/groovy/com/baeldung/traits/UserTrait.groovy b/core-groovy/src/main/groovy/com/baeldung/traits/UserTrait.groovy new file mode 100644 index 0000000000..3f1e694f17 --- /dev/null +++ b/core-groovy/src/main/groovy/com/baeldung/traits/UserTrait.groovy @@ -0,0 +1,36 @@ +package com.baeldung.traits + +trait UserTrait implements Human { + + String sayHello() { + return "Hello!" + } + + abstract String name() + + String showName() { + return "Hello, ${name()}!" + } + + private String greetingMessage() { + return 'Hello, from a private method!' + } + + String greet() { + def msg = greetingMessage() + println msg + msg + } + + def whoAmI() { + return this + } + + String showLastName() { + return "Hello, ${lastName()}!" + } + + String email + String address +} + \ No newline at end of file diff --git a/core-groovy/src/main/groovy/com/baeldung/traits/WalkingTrait.groovy b/core-groovy/src/main/groovy/com/baeldung/traits/WalkingTrait.groovy new file mode 100644 index 0000000000..66cff8809f --- /dev/null +++ b/core-groovy/src/main/groovy/com/baeldung/traits/WalkingTrait.groovy @@ -0,0 +1,13 @@ +package com.baeldung.traits + +trait WalkingTrait { + + String basicAbility() { + return "Walking!!" + } + + String speakAndWalk() { + return "Walk and speak!!" + } + +} \ No newline at end of file diff --git a/core-groovy/src/main/resources/fileContent.txt b/core-groovy/src/main/resources/fileContent.txt new file mode 100644 index 0000000000..643e4af3de --- /dev/null +++ b/core-groovy/src/main/resources/fileContent.txt @@ -0,0 +1,3 @@ +Line 1 : Hello World!!! +Line 2 : This is a file content. +Line 3 : String content diff --git a/core-groovy/src/main/resources/sample.png b/core-groovy/src/main/resources/sample.png new file mode 100644 index 0000000000..7d473430b7 Binary files /dev/null and b/core-groovy/src/main/resources/sample.png differ diff --git a/core-groovy/src/main/resources/utf8Content.html b/core-groovy/src/main/resources/utf8Content.html new file mode 100644 index 0000000000..61ff338f6c --- /dev/null +++ b/core-groovy/src/main/resources/utf8Content.html @@ -0,0 +1,12 @@ + + + + +
+ᚠᛇᚻ᛫ᛒᛦᚦ᛫ᚠᚱᚩᚠᚢᚱ᛫ᚠᛁᚱᚪ᛫ᚷᛖᚻᚹᛦᛚᚳᚢᛗ
+ᛋᚳᛖᚪᛚ᛫ᚦᛖᚪᚻ᛫ᛗᚪᚾᚾᚪ᛫ᚷᛖᚻᚹᛦᛚᚳ᛫ᛗᛁᚳᛚᚢᚾ᛫ᚻᛦᛏ᛫ᛞᚫᛚᚪᚾ
+ᚷᛁᚠ᛫ᚻᛖ᛫ᚹᛁᛚᛖ᛫ᚠᚩᚱ᛫ᛞᚱᛁᚻᛏᚾᛖ᛫ᛞᚩᛗᛖᛋ᛫ᚻᛚᛇᛏᚪᚾ
+
+ + \ No newline at end of file diff --git a/core-groovy/src/test/groovy/com/baeldung/file/ReadFileUnitTest.groovy b/core-groovy/src/test/groovy/com/baeldung/file/ReadFileUnitTest.groovy new file mode 100644 index 0000000000..a479c265c4 --- /dev/null +++ b/core-groovy/src/test/groovy/com/baeldung/file/ReadFileUnitTest.groovy @@ -0,0 +1,70 @@ +package com.baeldung.file + +import spock.lang.Specification + +class ReadFileUnitTest extends Specification { + + ReadFile readFile + + void setup () { + readFile = new ReadFile() + } + + def 'Should return number of lines in File using ReadFile.readFileLineByLine given filePath' () { + given: + def filePath = "src/main/resources/fileContent.txt" + when: + def noOfLines = readFile.readFileLineByLine(filePath) + then: + noOfLines + noOfLines instanceof Integer + assert noOfLines, 3 + } + + def 'Should return File Content in list of lines using ReadFile.readFileInList given filePath' () { + given: + def filePath = "src/main/resources/fileContent.txt" + when: + def lines = readFile.readFileInList(filePath) + then: + lines + lines instanceof List + assert lines.size(), 3 + } + + def 'Should return file content in string using ReadFile.readFileString given filePath' () { + given: + def filePath = "src/main/resources/fileContent.txt" + when: + def fileContent = readFile.readFileString(filePath) + then: + fileContent + fileContent instanceof String + fileContent.contains("""Line 1 : Hello World!!! +Line 2 : This is a file content. +Line 3 : String content""") + + } + + def 'Should return UTF-8 encoded file content in string using ReadFile.readFileStringWithCharset given filePath' () { + given: + def filePath = "src/main/resources/utf8Content.html" + when: + def encodedContent = readFile.readFileStringWithCharset(filePath) + then: + encodedContent + encodedContent instanceof String + } + + def 'Should return binary file content in byte array using ReadFile.readBinaryFile given filePath' () { + given: + def filePath = "src/main/resources/sample.png" + when: + def binaryContent = readFile.readBinaryFile(filePath) + then: + binaryContent + binaryContent instanceof byte[] + binaryContent.length == 329 + } + +} \ No newline at end of file diff --git a/core-groovy/src/test/groovy/com/baeldung/strings/ConcatenateTest.groovy b/core-groovy/src/test/groovy/com/baeldung/strings/ConcatenateTest.groovy new file mode 100644 index 0000000000..3ef4a5d460 --- /dev/null +++ b/core-groovy/src/test/groovy/com/baeldung/strings/ConcatenateTest.groovy @@ -0,0 +1,101 @@ +import com.baeldung.strings.Concatenate; + +class ConcatenateTest extends GroovyTestCase { + + void testSimpleConcat() { + def name = new Concatenate() + name.first = 'Joe'; + name.last = 'Smith'; + def expected = 'My name is Joe Smith' + assertToString(name.doSimpleConcat(), expected) + } + + void testConcatUsingGString() { + def name = new Concatenate() + name.first = "Joe"; + name.last = "Smith"; + def expected = "My name is Joe Smith" + assertToString(name.doConcatUsingGString(), expected) + } + + void testConcatUsingGStringClosures() { + def name = new Concatenate() + name.first = "Joe"; + name.last = "Smith"; + def expected = "My name is Joe Smith" + assertToString(name.doConcatUsingGStringClosures(), expected) + } + + void testConcatUsingStringConcatMethod() { + def name = new Concatenate() + name.first = "Joe"; + name.last = "Smith"; + def expected = "My name is Joe Smith" + assertToString(name.doConcatUsingStringConcatMethod(), expected) + } + + void testConcatUsingLeftShiftOperator() { + def name = new Concatenate() + name.first = "Joe"; + name.last = "Smith"; + def expected = "My name is Joe Smith" + assertToString(name.doConcatUsingLeftShiftOperator(), expected) + } + + void testConcatUsingArrayJoinMethod() { + def name = new Concatenate() + name.first = "Joe"; + name.last = "Smith"; + def expected = "My name is Joe Smith" + assertToString(name.doConcatUsingArrayJoinMethod(), expected) + } + + void testConcatUsingArrayInjectMethod() { + def name = new Concatenate() + name.first = "Joe"; + name.last = "Smith"; + def expected = "My name is Joe Smith" + assertToString(name.doConcatUsingArrayInjectMethod(), expected) + } + + void testConcatUsingStringBuilder() { + def name = new Concatenate() + name.first = "Joe"; + name.last = "Smith"; + def expected = "My name is Joe Smith" + assertToString(name.doConcatUsingStringBuilder(), expected) + } + + void testConcatUsingStringBuffer() { + def name = new Concatenate() + name.first = "Joe"; + name.last = "Smith"; + def expected = "My name is Joe Smith" + assertToString(name.doConcatUsingStringBuffer(), expected) + } + + void testConcatMultilineUsingStringConcatMethod() { + def name = new Concatenate() + name.first = '''Joe + Smith + '''; + name.last = 'Junior'; + def expected = '''My name is Joe + Smith + Junior'''; + assertToString(name.doConcatUsingStringConcatMethod(), expected) + } + + void testGStringvsClosure(){ + def first = "Joe"; + def last = "Smith"; + def eagerGString = "My name is $first $last" + def lazyGString = "My name is ${-> first} ${-> last}" + + assert eagerGString == "My name is Joe Smith" + assert lazyGString == "My name is Joe Smith" + first = "David"; + assert eagerGString == "My name is Joe Smith" + assert lazyGString == "My name is David Smith" + } +} diff --git a/core-groovy/src/test/groovy/com/baeldung/stringtypes/CharacterInGroovy.groovy b/core-groovy/src/test/groovy/com/baeldung/stringtypes/CharacterInGroovy.groovy new file mode 100644 index 0000000000..c043723d95 --- /dev/null +++ b/core-groovy/src/test/groovy/com/baeldung/stringtypes/CharacterInGroovy.groovy @@ -0,0 +1,19 @@ +package groovy.com.baeldung.stringtypes + +import org.junit.Assert +import org.junit.Test + +class CharacterInGroovy { + + @Test + void 'character'() { + char a = 'A' as char + char b = 'B' as char + char c = (char) 'C' + + Assert.assertTrue(a instanceof Character) + Assert.assertTrue(b instanceof Character) + Assert.assertTrue(c instanceof Character) + } + +} diff --git a/core-groovy/src/test/groovy/com/baeldung/stringtypes/DollarSlashyString.groovy b/core-groovy/src/test/groovy/com/baeldung/stringtypes/DollarSlashyString.groovy new file mode 100644 index 0000000000..db8ba68c8f --- /dev/null +++ b/core-groovy/src/test/groovy/com/baeldung/stringtypes/DollarSlashyString.groovy @@ -0,0 +1,24 @@ +package groovy.com.baeldung.stringtypes + +import org.junit.Test + +class DollarSlashyString { + + @Test + void 'dollar slashy string'() { + def name = "John" + + def dollarSlashy = $/ + Hello $name!, + + I can show you $ sign or escaped dollar sign: $$ + Both slashes works: \ or /, but we can still escape it: $/ + + We have to escape opening and closing delimiter: + - $$$/ + - $/$$ + /$ + + print(dollarSlashy) + } +} diff --git a/core-groovy/src/test/groovy/com/baeldung/stringtypes/DoubleQuotedString.groovy b/core-groovy/src/test/groovy/com/baeldung/stringtypes/DoubleQuotedString.groovy new file mode 100644 index 0000000000..a730244d0a --- /dev/null +++ b/core-groovy/src/test/groovy/com/baeldung/stringtypes/DoubleQuotedString.groovy @@ -0,0 +1,67 @@ +package groovy.com.baeldung.stringtypes + +import org.junit.Assert +import org.junit.Test + +class DoubleQuotedString { + + @Test + void 'escape double quoted string'() { + def example = "Hello \"world\"!" + + println(example) + } + + @Test + void 'String ang GString'() { + def string = "example" + def stringWithExpression = "example${2}" + + Assert.assertTrue(string instanceof String) + Assert.assertTrue(stringWithExpression instanceof GString) + Assert.assertTrue(stringWithExpression.toString() instanceof String) + } + + @Test + void 'placeholder with variable'() { + def name = "John" + def helloName = "Hello $name!".toString() + + Assert.assertEquals("Hello John!", helloName) + } + + @Test + void 'placeholder with expression'() { + def result = "result is ${2 * 2}".toString() + + Assert.assertEquals("result is 4", result) + } + + @Test + void 'placeholder with dotted access'() { + def person = [name: 'John'] + + def myNameIs = "I'm $person.name, and you?".toString() + + Assert.assertEquals("I'm John, and you?", myNameIs) + } + + @Test + void 'placeholder with method call'() { + def name = 'John' + + def result = "Uppercase name: ${name.toUpperCase()}".toString() + + Assert.assertEquals("Uppercase name: JOHN", result) + } + + + @Test + void 'GString and String hashcode'() { + def string = "2+2 is 4" + def gstring = "2+2 is ${4}" + + Assert.assertTrue(string.hashCode() != gstring.hashCode()) + } + +} diff --git a/core-groovy/src/test/groovy/com/baeldung/stringtypes/SingleQuotedString.groovy b/core-groovy/src/test/groovy/com/baeldung/stringtypes/SingleQuotedString.groovy new file mode 100644 index 0000000000..569991b788 --- /dev/null +++ b/core-groovy/src/test/groovy/com/baeldung/stringtypes/SingleQuotedString.groovy @@ -0,0 +1,15 @@ +package groovy.com.baeldung.stringtypes + +import org.junit.Assert +import org.junit.Test + +class SingleQuotedString { + + @Test + void 'single quoted string'() { + def example = 'Hello world' + + Assert.assertEquals('Hello world!', 'Hello' + ' world!') + } + +} diff --git a/core-groovy/src/test/groovy/com/baeldung/stringtypes/SlashyString.groovy b/core-groovy/src/test/groovy/com/baeldung/stringtypes/SlashyString.groovy new file mode 100644 index 0000000000..09ba35e17e --- /dev/null +++ b/core-groovy/src/test/groovy/com/baeldung/stringtypes/SlashyString.groovy @@ -0,0 +1,31 @@ +package groovy.com.baeldung.stringtypes + +import org.junit.Assert +import org.junit.Test + +class SlashyString { + + @Test + void 'slashy string'() { + def pattern = /.*foobar.*\/hello.*/ + + Assert.assertTrue("I'm matching foobar /hello regexp pattern".matches(pattern)) + } + + void 'wont compile'() { +// if ('' == //) { +// println("I can't compile") +// } + } + + @Test + void 'interpolate and multiline'() { + def name = 'John' + + def example = / + Hello $name + second line + / + } + +} diff --git a/core-groovy/src/test/groovy/com/baeldung/stringtypes/Strings.groovy b/core-groovy/src/test/groovy/com/baeldung/stringtypes/Strings.groovy new file mode 100644 index 0000000000..e45f352285 --- /dev/null +++ b/core-groovy/src/test/groovy/com/baeldung/stringtypes/Strings.groovy @@ -0,0 +1,26 @@ +package groovy.com.baeldung.stringtypes + +import org.junit.Assert +import org.junit.Test + +class Strings { + + @Test + void 'string interpolation '() { + def name = "Kacper" + + def result = "Hello ${name}!" + + Assert.assertEquals("Hello Kacper!", result.toString()) + } + + @Test + void 'string concatenation'() { + def first = "first" + def second = "second" + + def concatenation = first + second + + Assert.assertEquals("firstsecond", concatenation) + } +} diff --git a/core-groovy/src/test/groovy/com/baeldung/stringtypes/TripleDoubleQuotedString.groovy b/core-groovy/src/test/groovy/com/baeldung/stringtypes/TripleDoubleQuotedString.groovy new file mode 100644 index 0000000000..cbbb1a4665 --- /dev/null +++ b/core-groovy/src/test/groovy/com/baeldung/stringtypes/TripleDoubleQuotedString.groovy @@ -0,0 +1,19 @@ +package groovy.com.baeldung.stringtypes + +import org.junit.Test + +class TripleDoubleQuotedString { + + @Test + void 'triple-quoted strings with interpolation'() { + def name = "John" + + def multiLine = """ + I'm $name. + "This is quotation" + """ + + println(multiLine) + } + +} diff --git a/core-groovy/src/test/groovy/com/baeldung/stringtypes/TripleSingleQuotedString.groovy b/core-groovy/src/test/groovy/com/baeldung/stringtypes/TripleSingleQuotedString.groovy new file mode 100644 index 0000000000..24d55b8a2a --- /dev/null +++ b/core-groovy/src/test/groovy/com/baeldung/stringtypes/TripleSingleQuotedString.groovy @@ -0,0 +1,67 @@ +package groovy.com.baeldung.stringtypes + +import org.junit.Assert +import org.junit.Test + +class TripleSingleQuotedString { + + def 'formatted json'() { + def jsonContent = ''' + { + "name": "John", + "age": 20, + "birthDate": null + } + ''' + } + + def 'triple single quoted'() { + def triple = '''im triple single quoted string''' + } + + @Test + void 'triple single quoted with multiline string'() { + def triple = ''' + firstline + secondline + ''' + + Assert.assertTrue(triple.startsWith("\n")) + } + + @Test + void 'triple single quoted with multiline string with stripIndent() and removing newline characters'() { + def triple = '''\ + firstline + secondline'''.stripIndent() + + Assert.assertEquals("firstline\nsecondline", triple) + } + + @Test + void 'triple single quoted with multiline string with last line with only whitespaces'() { + def triple = '''\ + firstline + secondline\ + '''.stripIndent() + + println(triple) + } + + @Test + void 'triple single quoted with multiline string with stripMargin(Character) and removing newline characters'() { + def triple = '''\ + |firstline + |secondline'''.stripMargin() + + println(triple) + } + + @Test + void 'striple single quoted with special characters'() { + def specialCharacters = '''hello \'John\'. This is backslash - \\. \nSecond line starts here''' + + println(specialCharacters) + } + +} diff --git a/core-groovy/src/test/groovy/com/baeldung/traits/TraitsUnitTest.groovy b/core-groovy/src/test/groovy/com/baeldung/traits/TraitsUnitTest.groovy new file mode 100644 index 0000000000..0c74a9be62 --- /dev/null +++ b/core-groovy/src/test/groovy/com/baeldung/traits/TraitsUnitTest.groovy @@ -0,0 +1,114 @@ +package com.baeldung.traits + +import spock.lang.Specification + +class TraitsUnitTest extends Specification { + + Employee employee + Dog dog + + void setup () { + employee = new Employee() + dog = new Dog() + } + + def 'Should return msg string when using Employee.sayHello method provided by UserTrait' () { + when: + def msg = employee.sayHello() + then: + msg + msg instanceof String + assert msg == "Hello!" + } + + def 'Should return displayMsg string when using Employee.showName method' () { + when: + def displayMsg = employee.showName() + then: + displayMsg + displayMsg instanceof String + assert displayMsg == "Hello, Bob!" + } + + def 'Should return greetMsg string when using Employee.greet method' () { + when: + def greetMsg = employee.greet() + then: + greetMsg + greetMsg instanceof String + assert greetMsg == "Hello, from a private method!" + } + + def 'Should return MissingMethodException when using Employee.greetingMessage method' () { + when: + def exception + try { + employee.greetingMessage() + }catch(Exception e) { + exception = e + } + + then: + exception + exception instanceof groovy.lang.MissingMethodException + assert exception.message == "No signature of method: com.baeldung.traits.Employee.greetingMessage()"+ + " is applicable for argument types: () values: []" + } + + def 'Should return employee instance when using Employee.whoAmI method' () { + when: + def emp = employee.whoAmI() + then: + emp + emp instanceof Employee + assert emp.is(employee) + } + + def 'Should display lastName when using Employee.showLastName method' () { + when: + def lastNameMsg = employee.showLastName() + then: + lastNameMsg + lastNameMsg instanceof String + assert lastNameMsg == "Hello, Marley!" + } + + def 'Should be able to define properties of UserTrait in Employee instance' () { + when: + employee = new Employee(email: "a@e.com", address: "baeldung.com") + then: + employee + employee instanceof Employee + assert employee.email == "a@e.com" + assert employee.address == "baeldung.com" + } + + def 'Should execute basicAbility method from SpeakingTrait and return msg string' () { + when: + def speakMsg = dog.basicAbility() + then: + speakMsg + speakMsg instanceof String + assert speakMsg == "Speaking!!" + } + + def 'Should verify multiple inheritance with traits and execute overridden traits method' () { + when: + def walkSpeakMsg = dog.speakAndWalk() + println walkSpeakMsg + then: + walkSpeakMsg + walkSpeakMsg instanceof String + assert walkSpeakMsg == "Walk and speak!!" + } + + def 'Should implement AnimalTrait at runtime and access basicBehavior method' () { + when: + def dogInstance = new Dog() as AnimalTrait + def basicBehaviorMsg = dogInstance.basicBehavior() + then: + basicBehaviorMsg + basicBehaviorMsg instanceof String + assert basicBehaviorMsg == "Animalistic!!" + } +} \ No newline at end of file diff --git a/core-java-10/pom.xml b/core-java-10/pom.xml index 9fcdd9a162..b15f8b5d63 100644 --- a/core-java-10/pom.xml +++ b/core-java-10/pom.xml @@ -3,9 +3,9 @@ 4.0.0 com.baeldung core-java-10 - jar 0.1.0-SNAPSHOT core-java-10 + jar http://maven.apache.org diff --git a/core-java-11/README.md b/core-java-11/README.md index c8039f4bc5..3c8b94fa28 100644 --- a/core-java-11/README.md +++ b/core-java-11/README.md @@ -3,3 +3,4 @@ - [Java 11 Single File Source Code](https://www.baeldung.com/java-single-file-source-code) - [Java 11 Local Variable Syntax for Lambda Parameters](https://www.baeldung.com/java-var-lambda-params) - [Java 11 String API Additions](https://www.baeldung.com/java-11-string-api) +- [Java 11 Nest Based Access Control](https://www.baeldung.com/java-nest-based-access-control) diff --git a/core-java-11/pom.xml b/core-java-11/pom.xml index 4dcab49867..a9776d8f3b 100644 --- a/core-java-11/pom.xml +++ b/core-java-11/pom.xml @@ -3,9 +3,9 @@ 4.0.0 com.baeldung core-java-11 - jar 0.1.0-SNAPSHOT core-java-11 + jar http://maven.apache.org diff --git a/core-java-11/src/main/java/com/baeldung/java11/httpclient/HttpClientExample.java b/core-java-11/src/main/java/com/baeldung/java11/httpclient/HttpClientExample.java new file mode 100644 index 0000000000..fb4abd3bb6 --- /dev/null +++ b/core-java-11/src/main/java/com/baeldung/java11/httpclient/HttpClientExample.java @@ -0,0 +1,132 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package com.baeldung.java11.httpclient; + +import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.http.HttpClient; +import java.net.http.HttpClient.Version; +import java.net.http.HttpRequest; +import java.net.http.HttpRequest.BodyPublishers; +import java.net.http.HttpResponse; +import java.net.http.HttpResponse.BodyHandlers; +import java.net.http.HttpResponse.PushPromiseHandler; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.function.Function; +import java.util.stream.Collectors; + +public class HttpClientExample { + + public static void main(String[] args) throws Exception { + httpGetRequest(); + httpPostRequest(); + asynchronousGetRequest(); + asynchronousMultipleRequests(); + pushRequest(); + } + + public static void httpGetRequest() throws URISyntaxException, IOException, InterruptedException { + HttpClient client = HttpClient.newHttpClient(); + HttpRequest request = HttpRequest.newBuilder() + .version(HttpClient.Version.HTTP_2) + .uri(URI.create("http://jsonplaceholder.typicode.com/posts/1")) + .headers("Accept-Enconding", "gzip, deflate") + .build(); + HttpResponse response = client.send(request, BodyHandlers.ofString()); + + String responseBody = response.body(); + int responseStatusCode = response.statusCode(); + + System.out.println("httpGetRequest: " + responseBody); + System.out.println("httpGetRequest status code: " + responseStatusCode); + } + + public static void httpPostRequest() throws URISyntaxException, IOException, InterruptedException { + HttpClient client = HttpClient.newBuilder() + .version(HttpClient.Version.HTTP_2) + .build(); + HttpRequest request = HttpRequest.newBuilder(new URI("http://jsonplaceholder.typicode.com/posts")) + .version(HttpClient.Version.HTTP_2) + .POST(BodyPublishers.ofString("Sample Post Request")) + .build(); + HttpResponse response = client.send(request, BodyHandlers.ofString()); + String responseBody = response.body(); + System.out.println("httpPostRequest : " + responseBody); + } + + public static void asynchronousGetRequest() throws URISyntaxException { + HttpClient client = HttpClient.newHttpClient(); + URI httpURI = new URI("http://jsonplaceholder.typicode.com/posts/1"); + HttpRequest request = HttpRequest.newBuilder(httpURI) + .version(HttpClient.Version.HTTP_2) + .build(); + CompletableFuture futureResponse = client.sendAsync(request, HttpResponse.BodyHandlers.ofString()) + .thenAccept(resp -> { + System.out.println("Got pushed response " + resp.uri()); + System.out.println("Response statuscode: " + resp.statusCode()); + System.out.println("Response body: " + resp.body()); + }); + System.out.println("futureResponse" + futureResponse); + + } + + public static void asynchronousMultipleRequests() throws URISyntaxException { + HttpClient client = HttpClient.newHttpClient(); + List uris = Arrays.asList(new URI("http://jsonplaceholder.typicode.com/posts/1"), new URI("http://jsonplaceholder.typicode.com/posts/2")); + List requests = uris.stream() + .map(HttpRequest::newBuilder) + .map(reqBuilder -> reqBuilder.build()) + .collect(Collectors.toList()); + System.out.println("Got pushed response1 " + requests); + CompletableFuture.allOf(requests.stream() + .map(request -> client.sendAsync(request, BodyHandlers.ofString())) + .toArray(CompletableFuture[]::new)) + .thenAccept(System.out::println) + .join(); + } + + public static void pushRequest() throws URISyntaxException, InterruptedException { + System.out.println("Running HTTP/2 Server Push example..."); + + HttpClient httpClient = HttpClient.newBuilder() + .version(Version.HTTP_2) + .build(); + + HttpRequest pageRequest = HttpRequest.newBuilder() + .uri(URI.create("https://http2.golang.org/serverpush")) + .build(); + + // Interface HttpResponse.PushPromiseHandler + // void applyPushPromise​(HttpRequest initiatingRequest, HttpRequest pushPromiseRequest, Function,​CompletableFuture>> acceptor) + httpClient.sendAsync(pageRequest, BodyHandlers.ofString(), pushPromiseHandler()) + .thenAccept(pageResponse -> { + System.out.println("Page response status code: " + pageResponse.statusCode()); + System.out.println("Page response headers: " + pageResponse.headers()); + String responseBody = pageResponse.body(); + System.out.println(responseBody); + }).join(); + + Thread.sleep(1000); // waiting for full response + } + + private static PushPromiseHandler pushPromiseHandler() { + return (HttpRequest initiatingRequest, + HttpRequest pushPromiseRequest, + Function, + CompletableFuture>> acceptor) -> { + acceptor.apply(BodyHandlers.ofString()) + .thenAccept(resp -> { + System.out.println(" Pushed response: " + resp.uri() + ", headers: " + resp.headers()); + }); + System.out.println("Promise request: " + pushPromiseRequest.uri()); + System.out.println("Promise request: " + pushPromiseRequest.headers()); + }; + } + +} diff --git a/core-java-11/src/test/java/com/baeldung/java11/httpclient/test/HttpClientTest.java b/core-java-11/src/test/java/com/baeldung/java11/httpclient/test/HttpClientTest.java new file mode 100644 index 0000000000..bade666636 --- /dev/null +++ b/core-java-11/src/test/java/com/baeldung/java11/httpclient/test/HttpClientTest.java @@ -0,0 +1,240 @@ +package com.baeldung.java11.httpclient.test; + +import static org.hamcrest.CoreMatchers.containsString; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.io.IOException; +import java.net.Authenticator; +import java.net.CookieManager; +import java.net.CookiePolicy; +import java.net.HttpURLConnection; +import java.net.PasswordAuthentication; +import java.net.ProxySelector; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.net.http.HttpResponse.BodyHandlers; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionException; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; + +import org.junit.jupiter.api.Test; + +public class HttpClientTest { + + @Test + public void shouldReturnSampleDataContentWhenConnectViaSystemProxy() throws IOException, InterruptedException, URISyntaxException { + HttpRequest request = HttpRequest.newBuilder() + .uri(new URI("https://postman-echo.com/post")) + .headers("Content-Type", "text/plain;charset=UTF-8") + .POST(HttpRequest.BodyPublishers.ofString("Sample body")) + .build(); + + + HttpResponse response = HttpClient.newBuilder() + .proxy(ProxySelector.getDefault()) + .build() + .send(request, HttpResponse.BodyHandlers.ofString()); + + assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK)); + assertThat(response.body(), containsString("Sample body")); + } + + @Test + public void shouldNotFollowRedirectWhenSetToDefaultNever() throws IOException, InterruptedException, URISyntaxException { + HttpRequest request = HttpRequest.newBuilder() + .uri(new URI("http://stackoverflow.com")) + .version(HttpClient.Version.HTTP_1_1) + .GET() + .build(); + HttpResponse response = HttpClient.newBuilder() + .build() + .send(request, HttpResponse.BodyHandlers.ofString()); + + assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_MOVED_PERM)); + assertThat(response.body(), containsString("https://stackoverflow.com/")); + } + + @Test + public void shouldFollowRedirectWhenSetToAlways() throws IOException, InterruptedException, URISyntaxException { + HttpRequest request = HttpRequest.newBuilder() + .uri(new URI("http://stackoverflow.com")) + .version(HttpClient.Version.HTTP_1_1) + .GET() + .build(); + HttpResponse response = HttpClient.newBuilder() + .followRedirects(HttpClient.Redirect.ALWAYS) + .build() + .send(request, HttpResponse.BodyHandlers.ofString()); + + assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK)); + assertThat(response.request() + .uri() + .toString(), equalTo("https://stackoverflow.com/")); + } + + @Test + public void shouldReturnOKStatusForAuthenticatedAccess() throws URISyntaxException, IOException, InterruptedException { + HttpRequest request = HttpRequest.newBuilder() + .uri(new URI("https://postman-echo.com/basic-auth")) + .GET() + .build(); + HttpResponse response = HttpClient.newBuilder() + .authenticator(new Authenticator() { + @Override + protected PasswordAuthentication getPasswordAuthentication() { + return new PasswordAuthentication("postman", "password".toCharArray()); + } + }) + .build() + .send(request, HttpResponse.BodyHandlers.ofString()); + + assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK)); + } + + @Test + public void shouldSendRequestAsync() throws URISyntaxException, InterruptedException, ExecutionException { + HttpRequest request = HttpRequest.newBuilder() + .uri(new URI("https://postman-echo.com/post")) + .headers("Content-Type", "text/plain;charset=UTF-8") + .POST(HttpRequest.BodyPublishers.ofString("Sample body")) + .build(); + CompletableFuture> response = HttpClient.newBuilder() + .build() + .sendAsync(request, HttpResponse.BodyHandlers.ofString()); + + assertThat(response.get() + .statusCode(), equalTo(HttpURLConnection.HTTP_OK)); + } + + @Test + public void shouldUseJustTwoThreadWhenProcessingSendAsyncRequest() throws URISyntaxException, InterruptedException, ExecutionException { + HttpRequest request = HttpRequest.newBuilder() + .uri(new URI("https://postman-echo.com/get")) + .GET() + .build(); + + ExecutorService executorService = Executors.newFixedThreadPool(2); + + CompletableFuture> response1 = HttpClient.newBuilder() + .executor(executorService) + .build() + .sendAsync(request, HttpResponse.BodyHandlers.ofString()); + + CompletableFuture> response2 = HttpClient.newBuilder() + .executor(executorService) + .build() + .sendAsync(request, HttpResponse.BodyHandlers.ofString()); + + CompletableFuture> response3 = HttpClient.newBuilder() + .executor(executorService) + .build() + .sendAsync(request, HttpResponse.BodyHandlers.ofString()); + + CompletableFuture.allOf(response1, response2, response3) + .join(); + + assertThat(response1.get() + .statusCode(), equalTo(HttpURLConnection.HTTP_OK)); + assertThat(response2.get() + .statusCode(), equalTo(HttpURLConnection.HTTP_OK)); + assertThat(response3.get() + .statusCode(), equalTo(HttpURLConnection.HTTP_OK)); + } + + @Test + public void shouldNotStoreCookieWhenPolicyAcceptNone() throws URISyntaxException, IOException, InterruptedException { + HttpRequest request = HttpRequest.newBuilder() + .uri(new URI("https://postman-echo.com/get")) + .GET() + .build(); + + HttpClient httpClient = HttpClient.newBuilder() + .cookieHandler(new CookieManager(null, CookiePolicy.ACCEPT_NONE)) + .build(); + + httpClient.send(request, HttpResponse.BodyHandlers.ofString()); + + assertTrue(httpClient.cookieHandler() + .isPresent()); + } + + @Test + public void shouldStoreCookieWhenPolicyAcceptAll() throws URISyntaxException, IOException, InterruptedException { + HttpRequest request = HttpRequest.newBuilder() + .uri(new URI("https://postman-echo.com/get")) + .GET() + .build(); + + HttpClient httpClient = HttpClient.newBuilder() + .cookieHandler(new CookieManager(null, CookiePolicy.ACCEPT_ALL)) + .build(); + + httpClient.send(request, HttpResponse.BodyHandlers.ofString()); + + assertTrue(httpClient.cookieHandler() + .isPresent()); + } + + @Test + public void shouldProcessMultipleRequestViaStream() throws URISyntaxException, ExecutionException, InterruptedException { + List targets = Arrays.asList(new URI("https://postman-echo.com/get?foo1=bar1"), new URI("https://postman-echo.com/get?foo2=bar2")); + + HttpClient client = HttpClient.newHttpClient(); + + List> futures = targets.stream() + .map(target -> client.sendAsync(HttpRequest.newBuilder(target) + .GET() + .build(), HttpResponse.BodyHandlers.ofString()) + .thenApply(response -> response.body())) + .collect(Collectors.toList()); + + CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])) + .join(); + + if (futures.get(0) + .get() + .contains("foo1")) { + assertThat(futures.get(0) + .get(), containsString("bar1")); + assertThat(futures.get(1) + .get(), containsString("bar2")); + } else { + assertThat(futures.get(1) + .get(), containsString("bar2")); + assertThat(futures.get(1) + .get(), containsString("bar1")); + } + + } + + @Test + public void completeExceptionallyExample() { + CompletableFuture cf = CompletableFuture.completedFuture("message").thenApplyAsync(String::toUpperCase, + CompletableFuture.delayedExecutor(1, TimeUnit.SECONDS)); + CompletableFuture exceptionHandler = cf.handle((s, th) -> { return (th != null) ? "message upon cancel" : ""; }); + cf.completeExceptionally(new RuntimeException("completed exceptionally")); + assertTrue("Was not completed exceptionally", cf.isCompletedExceptionally()); + try { + cf.join(); + fail("Should have thrown an exception"); + } catch (CompletionException ex) { // just for testing + assertEquals("completed exceptionally", ex.getCause().getMessage()); + } + + assertEquals("message upon cancel", exceptionHandler.join()); + } + +} diff --git a/core-java-11/src/test/java/com/baeldung/java11/httpclient/test/HttpRequestTest.java b/core-java-11/src/test/java/com/baeldung/java11/httpclient/test/HttpRequestTest.java new file mode 100644 index 0000000000..7d138bd8d5 --- /dev/null +++ b/core-java-11/src/test/java/com/baeldung/java11/httpclient/test/HttpRequestTest.java @@ -0,0 +1,168 @@ +package com.baeldung.java11.httpclient.test; + +import static java.time.temporal.ChronoUnit.SECONDS; +import static org.hamcrest.CoreMatchers.containsString; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.junit.Assert.assertThat; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.net.HttpURLConnection; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.nio.file.Paths; +import java.security.NoSuchAlgorithmException; +import java.time.Duration; + +import org.junit.Test; + +public class HttpRequestTest { + + @Test + public void shouldReturnStatusOKWhenSendGetRequest() throws IOException, InterruptedException, URISyntaxException { + HttpRequest request = HttpRequest.newBuilder() + .uri(new URI("https://postman-echo.com/get")) + .GET() + .build(); + + HttpResponse response = HttpClient.newHttpClient() + .send(request, HttpResponse.BodyHandlers.ofString()); + + assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK)); + } + + @Test + public void shouldUseHttp2WhenWebsiteUsesHttp2() throws IOException, InterruptedException, URISyntaxException { + HttpRequest request = HttpRequest.newBuilder() + .uri(new URI("https://stackoverflow.com")) + .version(HttpClient.Version.HTTP_2) + .GET() + .build(); + HttpResponse response = HttpClient.newHttpClient() + .send(request, HttpResponse.BodyHandlers.ofString()); + + assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK)); + assertThat(response.version(), equalTo(HttpClient.Version.HTTP_2)); + } + + @Test + public void shouldFallbackToHttp1_1WhenWebsiteDoesNotUseHttp2() throws IOException, InterruptedException, URISyntaxException, NoSuchAlgorithmException { + HttpRequest request = HttpRequest.newBuilder() + .uri(new URI("https://postman-echo.com/get")) + .version(HttpClient.Version.HTTP_2) + .GET() + .build(); + + HttpResponse response = HttpClient.newHttpClient() + .send(request, HttpResponse.BodyHandlers.ofString()); + + assertThat(response.version(), equalTo(HttpClient.Version.HTTP_1_1)); + } + + @Test + public void shouldReturnStatusOKWhenSendGetRequestWithDummyHeaders() throws IOException, InterruptedException, URISyntaxException { + HttpRequest request = HttpRequest.newBuilder() + .uri(new URI("https://postman-echo.com/get")) + .headers("key1", "value1", "key2", "value2") + .GET() + .build(); + + HttpResponse response = HttpClient.newHttpClient() + .send(request, HttpResponse.BodyHandlers.ofString()); + + assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK)); + } + + @Test + public void shouldReturnStatusOKWhenSendGetRequestTimeoutSet() throws IOException, InterruptedException, URISyntaxException { + HttpRequest request = HttpRequest.newBuilder() + .uri(new URI("https://postman-echo.com/get")) + .timeout(Duration.of(10, SECONDS)) + .GET() + .build(); + + HttpResponse response = HttpClient.newHttpClient() + .send(request, HttpResponse.BodyHandlers.ofString()); + + assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK)); + } + + @Test + public void shouldReturnNoContentWhenPostWithNoBody() throws IOException, InterruptedException, URISyntaxException { + HttpRequest request = HttpRequest.newBuilder() + .uri(new URI("https://postman-echo.com/post")) + .POST(HttpRequest.BodyPublishers.noBody()) + .build(); + + HttpResponse response = HttpClient.newHttpClient() + .send(request, HttpResponse.BodyHandlers.ofString()); + + assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK)); + } + + @Test + public void shouldReturnSampleDataContentWhenPostWithBodyText() throws IOException, InterruptedException, URISyntaxException { + HttpRequest request = HttpRequest.newBuilder() + .uri(new URI("https://postman-echo.com/post")) + .headers("Content-Type", "text/plain;charset=UTF-8") + .POST(HttpRequest.BodyPublishers.ofString("Sample request body")) + .build(); + + HttpResponse response = HttpClient.newHttpClient() + .send(request, HttpResponse.BodyHandlers.ofString()); + + assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK)); + assertThat(response.body(), containsString("Sample request body")); + } + + @Test + public void shouldReturnSampleDataContentWhenPostWithInputStream() throws IOException, InterruptedException, URISyntaxException { + byte[] sampleData = "Sample request body".getBytes(); + HttpRequest request = HttpRequest.newBuilder() + .uri(new URI("https://postman-echo.com/post")) + .headers("Content-Type", "text/plain;charset=UTF-8") + .POST(HttpRequest.BodyPublishers.ofInputStream(() -> new ByteArrayInputStream(sampleData))) + .build(); + + HttpResponse response = HttpClient.newHttpClient() + .send(request, HttpResponse.BodyHandlers.ofString()); + + assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK)); + assertThat(response.body(), containsString("Sample request body")); + } + + @Test + public void shouldReturnSampleDataContentWhenPostWithByteArrayProcessorStream() throws IOException, InterruptedException, URISyntaxException { + byte[] sampleData = "Sample request body".getBytes(); + HttpRequest request = HttpRequest.newBuilder() + .uri(new URI("https://postman-echo.com/post")) + .headers("Content-Type", "text/plain;charset=UTF-8") + .POST(HttpRequest.BodyPublishers.ofByteArray(sampleData)) + .build(); + + HttpResponse response = HttpClient.newHttpClient() + .send(request, HttpResponse.BodyHandlers.ofString()); + + assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK)); + assertThat(response.body(), containsString("Sample request body")); + } + + @Test + public void shouldReturnSampleDataContentWhenPostWithFileProcessorStream() throws IOException, InterruptedException, URISyntaxException { + HttpRequest request = HttpRequest.newBuilder() + .uri(new URI("https://postman-echo.com/post")) + .headers("Content-Type", "text/plain;charset=UTF-8") + .POST(HttpRequest.BodyPublishers.ofFile(Paths.get("src/test/resources/sample.txt"))) + .build(); + + HttpResponse response = HttpClient.newHttpClient() + .send(request, HttpResponse.BodyHandlers.ofString()); + + assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK)); + assertThat(response.body(), containsString("Sample file content")); + } + +} diff --git a/core-java-11/src/test/java/com/baeldung/java11/httpclient/test/HttpResponseTest.java b/core-java-11/src/test/java/com/baeldung/java11/httpclient/test/HttpResponseTest.java new file mode 100644 index 0000000000..78d86fbf4e --- /dev/null +++ b/core-java-11/src/test/java/com/baeldung/java11/httpclient/test/HttpResponseTest.java @@ -0,0 +1,54 @@ +package com.baeldung.java11.httpclient.test; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertThat; + +import java.io.IOException; +import java.net.HttpURLConnection; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; + +import org.junit.Test; + +public class HttpResponseTest { + + @Test + public void shouldReturnStatusOKWhenSendGetRequest() throws IOException, InterruptedException, URISyntaxException { + HttpRequest request = HttpRequest.newBuilder() + .uri(new URI("https://postman-echo.com/get")) + .version(HttpClient.Version.HTTP_2) + .GET() + .build(); + + HttpResponse response = HttpClient.newBuilder() + .followRedirects(HttpClient.Redirect.NORMAL) + .build() + .send(request, HttpResponse.BodyHandlers.ofString()); + + assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK)); + assertNotNull(response.body()); + } + + @Test + public void shouldResponseURIDifferentThanRequestUIRWhenRedirect() throws IOException, InterruptedException, URISyntaxException { + HttpRequest request = HttpRequest.newBuilder() + .uri(new URI("http://stackoverflow.com")) + .version(HttpClient.Version.HTTP_2) + .GET() + .build(); + HttpResponse response = HttpClient.newBuilder() + .followRedirects(HttpClient.Redirect.NORMAL) + .build() + .send(request, HttpResponse.BodyHandlers.ofString()); + + assertThat(request.uri() + .toString(), equalTo("http://stackoverflow.com")); + assertThat(response.uri() + .toString(), equalTo("https://stackoverflow.com/")); + } + +} diff --git a/core-java-8/pom.xml b/core-java-8/pom.xml index 112e8b764d..b4519a8161 100644 --- a/core-java-8/pom.xml +++ b/core-java-8/pom.xml @@ -4,8 +4,8 @@ com.baeldung core-java-8 0.1.0-SNAPSHOT - jar core-java-8 + jar com.baeldung diff --git a/core-java-8/src/main/java/com/baeldung/customannotations/Init.java b/core-java-8/src/main/java/com/baeldung/customannotations/Init.java new file mode 100644 index 0000000000..265e7ba1d6 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/customannotations/Init.java @@ -0,0 +1,13 @@ +package com.baeldung.customannotations; + +import static java.lang.annotation.ElementType.METHOD; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +@Retention(RUNTIME) +@Target(METHOD) +public @interface Init { + +} diff --git a/core-java-8/src/main/java/com/baeldung/customannotations/JsonElement.java b/core-java-8/src/main/java/com/baeldung/customannotations/JsonElement.java new file mode 100644 index 0000000000..e41a5b1e30 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/customannotations/JsonElement.java @@ -0,0 +1,13 @@ +package com.baeldung.customannotations; + +import static java.lang.annotation.ElementType.FIELD; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +@Retention(RUNTIME) +@Target({ FIELD }) +public @interface JsonElement { + public String key() default ""; +} diff --git a/core-java-8/src/main/java/com/baeldung/customannotations/JsonSerializable.java b/core-java-8/src/main/java/com/baeldung/customannotations/JsonSerializable.java new file mode 100644 index 0000000000..48eeb09a1b --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/customannotations/JsonSerializable.java @@ -0,0 +1,13 @@ +package com.baeldung.customannotations; + +import static java.lang.annotation.ElementType.TYPE; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +@Retention(RUNTIME) +@Target(TYPE) +public @interface JsonSerializable { + +} diff --git a/core-java-8/src/main/java/com/baeldung/customannotations/JsonSerializationException.java b/core-java-8/src/main/java/com/baeldung/customannotations/JsonSerializationException.java new file mode 100644 index 0000000000..f2c29855ac --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/customannotations/JsonSerializationException.java @@ -0,0 +1,10 @@ +package com.baeldung.customannotations; + +public class JsonSerializationException extends RuntimeException { + + private static final long serialVersionUID = 1L; + + public JsonSerializationException(String message) { + super(message); + } +} diff --git a/core-java-8/src/main/java/com/baeldung/customannotations/ObjectToJsonConverter.java b/core-java-8/src/main/java/com/baeldung/customannotations/ObjectToJsonConverter.java new file mode 100644 index 0000000000..dd126be8ed --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/customannotations/ObjectToJsonConverter.java @@ -0,0 +1,67 @@ +package com.baeldung.customannotations; + +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.stream.Collectors; + +public class ObjectToJsonConverter { + public String convertToJson(Object object) throws JsonSerializationException { + try { + + checkIfSerializable(object); + initializeObject(object); + return getJsonString(object); + + } catch (Exception e) { + throw new JsonSerializationException(e.getMessage()); + } + } + + private void checkIfSerializable(Object object) { + if (Objects.isNull(object)) { + throw new JsonSerializationException("Can't serialize a null object"); + } + + Class clazz = object.getClass(); + if (!clazz.isAnnotationPresent(JsonSerializable.class)) { + throw new JsonSerializationException("The class " + clazz.getSimpleName() + " is not annotated with JsonSerializable"); + } + } + + private void initializeObject(Object object) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException { + Class clazz = object.getClass(); + for (Method method : clazz.getDeclaredMethods()) { + if (method.isAnnotationPresent(Init.class)) { + method.setAccessible(true); + method.invoke(object); + } + } + } + + private String getJsonString(Object object) throws IllegalArgumentException, IllegalAccessException { + Class clazz = object.getClass(); + Map jsonElementsMap = new HashMap<>(); + for (Field field : clazz.getDeclaredFields()) { + field.setAccessible(true); + if (field.isAnnotationPresent(JsonElement.class)) { + jsonElementsMap.put(getKey(field), (String) field.get(object)); + } + } + + String jsonString = jsonElementsMap.entrySet() + .stream() + .map(entry -> "\"" + entry.getKey() + "\":\"" + entry.getValue() + "\"") + .collect(Collectors.joining(",")); + return "{" + jsonString + "}"; + } + + private String getKey(Field field) { + String value = field.getAnnotation(JsonElement.class) + .key(); + return value.isEmpty() ? field.getName() : value; + } +} diff --git a/core-java-8/src/main/java/com/baeldung/customannotations/Person.java b/core-java-8/src/main/java/com/baeldung/customannotations/Person.java new file mode 100644 index 0000000000..5db1a7f279 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/customannotations/Person.java @@ -0,0 +1,66 @@ +package com.baeldung.customannotations; + +@JsonSerializable +public class Person { + @JsonElement + private String firstName; + @JsonElement + private String lastName; + @JsonElement(key = "personAge") + private String age; + + private String address; + + public Person(String firstName, String lastName) { + super(); + this.firstName = firstName; + this.lastName = lastName; + } + + public Person(String firstName, String lastName, String age) { + this.firstName = firstName; + this.lastName = lastName; + this.age = age; + } + + @Init + private void initNames() { + this.firstName = this.firstName.substring(0, 1) + .toUpperCase() + this.firstName.substring(1); + this.lastName = this.lastName.substring(0, 1) + .toUpperCase() + this.lastName.substring(1); + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getAge() { + return age; + } + + public void setAge(String age) { + this.age = age; + } + + public String getAddress() { + return address; + } + + public void setAddress(String address) { + this.address = address; + } + +} diff --git a/core-java-8/src/test/java/com/baeldung/collectors/Java8CollectorsUnitTest.java b/core-java-8/src/test/java/com/baeldung/collectors/Java8CollectorsUnitTest.java index bad1c32e4a..e742635758 100644 --- a/core-java-8/src/test/java/com/baeldung/collectors/Java8CollectorsUnitTest.java +++ b/core-java-8/src/test/java/com/baeldung/collectors/Java8CollectorsUnitTest.java @@ -39,6 +39,7 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; public class Java8CollectorsUnitTest { private final List givenList = Arrays.asList("a", "bb", "ccc", "dd"); + private final List listWithDuplicates = Arrays.asList("a", "bb", "c", "d", "bb"); @Test public void whenCollectingToList_shouldCollectToList() throws Exception { @@ -48,12 +49,19 @@ public class Java8CollectorsUnitTest { } @Test - public void whenCollectingToList_shouldCollectToSet() throws Exception { + public void whenCollectingToSet_shouldCollectToSet() throws Exception { final Set result = givenList.stream().collect(toSet()); assertThat(result).containsAll(givenList); } + @Test + public void givenContainsDuplicateElements_whenCollectingToSet_shouldAddDuplicateElementsOnlyOnce() throws Exception { + final Set result = listWithDuplicates.stream().collect(toSet()); + + assertThat(result).hasSize(4); + } + @Test public void whenCollectingToCollection_shouldCollectToCollection() throws Exception { final List result = givenList.stream().collect(toCollection(LinkedList::new)); @@ -77,10 +85,23 @@ public class Java8CollectorsUnitTest { } @Test - public void whenCollectingToMap_shouldCollectToMapMerging() throws Exception { - final Map result = givenList.stream().collect(toMap(Function.identity(), String::length, (i1, i2) -> i1)); + public void whenCollectingToMapwWithDuplicates_shouldCollectToMapMergingTheIdenticalItems() throws Exception { + final Map result = listWithDuplicates.stream().collect( + toMap( + Function.identity(), + String::length, + (item, identicalItem) -> item + ) + ); - assertThat(result).containsEntry("a", 1).containsEntry("bb", 2).containsEntry("ccc", 3).containsEntry("dd", 2); + assertThat(result).containsEntry("a", 1).containsEntry("bb", 2).containsEntry("c", 1).containsEntry("d", 1); + } + + @Test + public void givenContainsDuplicateElements_whenCollectingToMap_shouldThrowException() throws Exception { + assertThatThrownBy(() -> { + listWithDuplicates.stream().collect(toMap(Function.identity(), String::length)); + }).isInstanceOf(IllegalStateException.class); } @Test diff --git a/core-java-8/src/test/java/com/baeldung/customannotations/JsonSerializerUnitTest.java b/core-java-8/src/test/java/com/baeldung/customannotations/JsonSerializerUnitTest.java new file mode 100644 index 0000000000..f24b37aef7 --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/customannotations/JsonSerializerUnitTest.java @@ -0,0 +1,26 @@ +package com.baeldung.customannotations; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import org.junit.jupiter.api.Test; + +public class JsonSerializerUnitTest { + + @Test + public void givenObjectNotSerializedThenExceptionThrown() throws JsonSerializationException { + Object object = new Object(); + ObjectToJsonConverter serializer = new ObjectToJsonConverter(); + assertThrows(JsonSerializationException.class, () -> { + serializer.convertToJson(object); + }); + } + + @Test + public void givenObjectSerializedThenTrueReturned() throws JsonSerializationException { + Person person = new Person("soufiane", "cheouati", "34"); + ObjectToJsonConverter serializer = new ObjectToJsonConverter(); + String jsonString = serializer.convertToJson(person); + assertEquals("{\"personAge\":\"34\",\"firstName\":\"Soufiane\",\"lastName\":\"Cheouati\"}", jsonString); + } +} diff --git a/core-java-8/src/test/java/com/baeldung/java8/lambda/methodreference/MethodReferenceExamples.java b/core-java-8/src/test/java/com/baeldung/java8/lambda/methodreference/MethodReferenceUnitTest.java similarity index 89% rename from core-java-8/src/test/java/com/baeldung/java8/lambda/methodreference/MethodReferenceExamples.java rename to core-java-8/src/test/java/com/baeldung/java8/lambda/methodreference/MethodReferenceUnitTest.java index ede0ef9f70..835815aecd 100644 --- a/core-java-8/src/test/java/com/baeldung/java8/lambda/methodreference/MethodReferenceExamples.java +++ b/core-java-8/src/test/java/com/baeldung/java8/lambda/methodreference/MethodReferenceUnitTest.java @@ -5,22 +5,21 @@ import java.util.Arrays; import java.util.List; import java.util.function.BiFunction; +import org.apache.commons.lang3.StringUtils; import org.junit.Test; -public class MethodReferenceExamples { +public class MethodReferenceUnitTest { private static void doNothingAtAll(Object... o) { } ; - + @Test public void referenceToStaticMethod() { List messages = Arrays.asList("Hello", "Baeldung", "readers!"); - messages.forEach((word) -> { - System.out.println(word); - }); - messages.forEach(System.out::println); + messages.forEach(word -> StringUtils.capitalize(word)); + messages.forEach(StringUtils::capitalize); } @Test @@ -63,7 +62,7 @@ public class MethodReferenceExamples { @Test public void limitationsAndAdditionalExamples() { createBicyclesList().forEach(b -> System.out.printf("Bike brand is '%s' and frame size is '%d'%n", b.getBrand(), b.getFrameSize())); - createBicyclesList().forEach((o) -> MethodReferenceExamples.doNothingAtAll(o)); + createBicyclesList().forEach((o) -> MethodReferenceUnitTest.doNothingAtAll(o)); } private List createBicyclesList() { diff --git a/core-java-9/README.md b/core-java-9/README.md index c96267dc95..d9586ba684 100644 --- a/core-java-9/README.md +++ b/core-java-9/README.md @@ -26,3 +26,4 @@ - [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap) - [Java 9 Platform Logging API](https://www.baeldung.com/java-9-logging-api) - [Guide to java.lang.Process API](https://www.baeldung.com/java-process-api) +- [Immutable Set in Java](https://www.baeldung.com/java-immutable-set) diff --git a/core-java-9/compile-aot.sh b/core-java-9/compile-aot.sh new file mode 100755 index 0000000000..c3a39b0196 --- /dev/null +++ b/core-java-9/compile-aot.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +cd src/main/java +javac com/baeldung/java9/aot/JaotCompilation.java +jaotc --output jaotCompilation.so com/baeldung/java9/aot/JaotCompilation.class + diff --git a/core-java-9/run-aot.sh b/core-java-9/run-aot.sh new file mode 100755 index 0000000000..89fc616469 --- /dev/null +++ b/core-java-9/run-aot.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +cd src/main/java +java -XX:AOTLibrary=./jaotCompilation.so com/baeldung/java9/aot/JaotCompilation \ No newline at end of file diff --git a/core-java-9/src/main/java/com/baeldung/java9/aot/JaotCompilation.java b/core-java-9/src/main/java/com/baeldung/java9/aot/JaotCompilation.java new file mode 100644 index 0000000000..4d8a018d6b --- /dev/null +++ b/core-java-9/src/main/java/com/baeldung/java9/aot/JaotCompilation.java @@ -0,0 +1,12 @@ +package com.baeldung.java9.aot; + +public class JaotCompilation { + + public static void main(String[] argv) { + System.out.println(message()); + } + + public static String message() { + return "The JAOT compiler says 'Hello'"; + } +} \ No newline at end of file diff --git a/core-java-arrays/README.md b/core-java-arrays/README.md index 400dd7793c..ed8221ebe4 100644 --- a/core-java-arrays/README.md +++ b/core-java-arrays/README.md @@ -14,3 +14,4 @@ - [Array Operations in Java](http://www.baeldung.com/java-common-array-operations) - [Intersection Between two Integer Arrays](https://www.baeldung.com/java-array-intersection) - [Sorting Arrays in Java](https://www.baeldung.com/java-sorting-arrays) +- [Convert a Float to a Byte Array in Java](https://www.baeldung.com/java-convert-float-to-byte-array) diff --git a/core-java-arrays/pom.xml b/core-java-arrays/pom.xml index d2d0453e87..39ac764b27 100644 --- a/core-java-arrays/pom.xml +++ b/core-java-arrays/pom.xml @@ -4,8 +4,8 @@ com.baeldung core-java-arrays 0.1.0-SNAPSHOT - jar core-java-arrays + jar com.baeldung diff --git a/core-java-collections-list/pom.xml b/core-java-collections-list/pom.xml index a7e711088a..737be8ee34 100644 --- a/core-java-collections-list/pom.xml +++ b/core-java-collections-list/pom.xml @@ -3,8 +3,8 @@ 4.0.0 core-java-collections-list 0.1.0-SNAPSHOT - jar core-java-collections-list + jar com.baeldung @@ -40,17 +40,17 @@ net.sf.trove4j trove4j - 3.0.2 + ${trove4j.version} it.unimi.dsi fastutil - 8.1.0 + ${fastutil.version} colt colt - 1.2.0 + ${colt.version} @@ -60,5 +60,8 @@ 1.7.0 3.11.1 1.16.12 + 3.0.2 + 8.1.0 + 1.2.0
diff --git a/core-java-collections-list/src/main/java/com/baeldung/allequalelements/VerifyAllEqualListElements.java b/core-java-collections-list/src/main/java/com/baeldung/allequalelements/VerifyAllEqualListElements.java new file mode 100644 index 0000000000..936e89893c --- /dev/null +++ b/core-java-collections-list/src/main/java/com/baeldung/allequalelements/VerifyAllEqualListElements.java @@ -0,0 +1,55 @@ +package com.baeldung.allequalelements; + +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import org.apache.commons.collections4.IterableUtils; +import com.google.common.base.Predicate; +import com.google.common.collect.Iterables; + +public class VerifyAllEqualListElements { + + public boolean verifyAllEqualUsingALoop(List list) { + for (String s : list) { + if (!s.equals(list.get(0))) + return false; + } + return true; + } + + public boolean verifyAllEqualUsingHashSet(List list) { + return new HashSet(list).size() <= 1; + } + + public boolean verifyAllEqualUsingFrequency(List list) { + return list.isEmpty() || Collections.frequency(list, list.get(0)) == list.size(); + } + + public boolean verifyAllEqualUsingStream(List list) { + return list.stream() + .distinct() + .count() <= 1; + } + + public boolean verifyAllEqualAnotherUsingStream(List list) { + return list.isEmpty() || list.stream() + .allMatch(list.get(0)::equals); + } + + public boolean verifyAllEqualUsingGuava(List list) { + return Iterables.all(list, new Predicate() { + public boolean apply(String s) { + return s.equals(list.get(0)); + } + }); + } + + public boolean verifyAllEqualUsingApacheCommon(List list) { + return IterableUtils.matchesAll(list, new org.apache.commons.collections4.Predicate() { + public boolean evaluate(String s) { + return s.equals(list.get(0)); + } + }); + } + +} \ No newline at end of file diff --git a/core-java-collections-list/src/test/java/com/baeldung/allequalelements/VerifyAllEqualListElementsUnitTest.java b/core-java-collections-list/src/test/java/com/baeldung/allequalelements/VerifyAllEqualListElementsUnitTest.java new file mode 100644 index 0000000000..698725591c --- /dev/null +++ b/core-java-collections-list/src/test/java/com/baeldung/allequalelements/VerifyAllEqualListElementsUnitTest.java @@ -0,0 +1,172 @@ +package com.baeldung.allequalelements; + +import org.junit.Test; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import static org.junit.Assert.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class VerifyAllEqualListElementsUnitTest { + + private static List notAllEqualList = new ArrayList<>(); + + private static List emptyList = new ArrayList<>(); + + private static List allEqualList = new ArrayList<>(); + + static { + notAllEqualList = Arrays.asList("Jack", "James", "Sam", "James"); + emptyList = Arrays.asList(); + allEqualList = Arrays.asList("Jack", "Jack", "Jack", "Jack"); + } + + private static VerifyAllEqualListElements verifyAllEqualListElements = new VerifyAllEqualListElements(); + + @Test + public void givenNotAllEqualList_whenUsingALoop_thenReturnFalse() { + boolean allEqual = verifyAllEqualListElements.verifyAllEqualUsingALoop(notAllEqualList); + + assertFalse(allEqual); + } + + @Test + public void givenEmptyList_whenUsingALoop_thenReturnTrue() { + boolean allEqual = verifyAllEqualListElements.verifyAllEqualUsingALoop(emptyList); + + assertTrue(allEqual); + } + + @Test + public void givenAllEqualList_whenUsingALoop_thenReturnTrue() { + boolean allEqual = verifyAllEqualListElements.verifyAllEqualUsingALoop(allEqualList); + + assertTrue(allEqual); + } + + @Test + public void givenNotAllEqualList_whenUsingHashSet_thenReturnFalse() { + boolean allEqual = verifyAllEqualListElements.verifyAllEqualUsingHashSet(notAllEqualList); + + assertFalse(allEqual); + } + + @Test + public void givenEmptyList_whenUsingHashSet_thenReturnTrue() { + boolean allEqual = verifyAllEqualListElements.verifyAllEqualUsingHashSet(emptyList); + + assertTrue(allEqual); + } + + @Test + public void givenAllEqualList_whenUsingHashSet_thenReturnTrue() { + boolean allEqual = verifyAllEqualListElements.verifyAllEqualUsingHashSet(allEqualList); + + assertTrue(allEqual); + } + + @Test + public void givenNotAllEqualList_whenUsingFrequency_thenReturnFalse() { + boolean allEqual = verifyAllEqualListElements.verifyAllEqualUsingFrequency(notAllEqualList); + + assertFalse(allEqual); + } + + @Test + public void givenEmptyList_whenUsingFrequency_thenReturnTrue() { + boolean allEqual = verifyAllEqualListElements.verifyAllEqualUsingFrequency(emptyList); + + assertTrue(allEqual); + } + + @Test + public void givenAllEqualList_whenUsingFrequency_thenReturnTrue() { + boolean allEqual = verifyAllEqualListElements.verifyAllEqualUsingFrequency(allEqualList); + + assertTrue(allEqual); + } + + @Test + public void givenNotAllEqualList_whenUsingStream_thenReturnFalse() { + boolean allEqual = verifyAllEqualListElements.verifyAllEqualUsingStream(notAllEqualList); + + assertFalse(allEqual); + } + + @Test + public void givenEmptyList_whenUsingStream_thenReturnTrue() { + boolean allEqual = verifyAllEqualListElements.verifyAllEqualUsingStream(emptyList); + + assertTrue(allEqual); + } + + @Test + public void givenAllEqualList_whenUsingStream_thenReturnTrue() { + boolean allEqual = verifyAllEqualListElements.verifyAllEqualUsingStream(allEqualList); + + assertTrue(allEqual); + } + + @Test + public void givenNotAllEqualList_whenUsingAnotherStream_thenReturnFalse() { + boolean allEqual = verifyAllEqualListElements.verifyAllEqualAnotherUsingStream(notAllEqualList); + + assertFalse(allEqual); + } + + @Test + public void givenEmptyList_whenUsingAnotherStream_thenReturnTrue() { + boolean allEqual = verifyAllEqualListElements.verifyAllEqualAnotherUsingStream(emptyList); + + assertTrue(allEqual); + } + + @Test + public void givenAllEqualList_whenUsingAnotherStream_thenReturnTrue() { + boolean allEqual = verifyAllEqualListElements.verifyAllEqualAnotherUsingStream(allEqualList); + + assertTrue(allEqual); + } + + @Test + public void givenNotAllEqualList_whenUsingGuava_thenReturnFalse() { + boolean allEqual = verifyAllEqualListElements.verifyAllEqualUsingGuava(notAllEqualList); + + assertFalse(allEqual); + } + + @Test + public void givenEmptyList_whenUsingGuava_thenReturnTrue() { + boolean allEqual = verifyAllEqualListElements.verifyAllEqualUsingGuava(emptyList); + + assertTrue(allEqual); + } + + @Test + public void givenAllEqualList_whenUsingGuava_thenReturnTrue() { + boolean allEqual = verifyAllEqualListElements.verifyAllEqualUsingGuava(allEqualList); + + assertTrue(allEqual); + } + + @Test + public void givenNotAllEqualList_whenUsingApacheCommon_thenReturnFalse() { + boolean allEqual = verifyAllEqualListElements.verifyAllEqualUsingApacheCommon(notAllEqualList); + + assertFalse(allEqual); + } + + @Test + public void givenEmptyList_whenUsingApacheCommon_thenReturnTrue() { + boolean allEqual = verifyAllEqualListElements.verifyAllEqualUsingApacheCommon(emptyList); + + assertTrue(allEqual); + } + + @Test + public void givenAllEqualList_whenUsingApacheCommon_thenReturnTrue() { + boolean allEqual = verifyAllEqualListElements.verifyAllEqualUsingApacheCommon(allEqualList); + + assertTrue(allEqual); + } +} diff --git a/core-java-collections/README.md b/core-java-collections/README.md index be83621429..710be31a08 100644 --- a/core-java-collections/README.md +++ b/core-java-collections/README.md @@ -31,3 +31,4 @@ - [A Guide to EnumMap](https://www.baeldung.com/java-enum-map) - [A Guide to Iterator in Java](http://www.baeldung.com/java-iterator) - [Differences Between HashMap and Hashtable](https://www.baeldung.com/hashmap-hashtable-differences) +- [Java ArrayList vs Vector](https://www.baeldung.com/java-arraylist-vs-vector) diff --git a/core-java-collections/pom.xml b/core-java-collections/pom.xml index 2201ee8b15..261558836d 100644 --- a/core-java-collections/pom.xml +++ b/core-java-collections/pom.xml @@ -3,8 +3,8 @@ 4.0.0 core-java-collections 0.1.0-SNAPSHOT - jar core-java-collections + jar com.baeldung @@ -54,7 +54,7 @@ org.apache.commons commons-exec - 1.3 + ${commons-exec.version} org.projectlombok @@ -74,5 +74,6 @@ 3.11.1 7.1.0 1.16.12 + 1.3 diff --git a/core-java-collections/src/main/java/com/baeldung/charstack/CharStack.java b/core-java-collections/src/main/java/com/baeldung/charstack/CharStack.java new file mode 100644 index 0000000000..f789a68d90 --- /dev/null +++ b/core-java-collections/src/main/java/com/baeldung/charstack/CharStack.java @@ -0,0 +1,37 @@ +package com.baeldung.charstack; + +import java.util.Iterator; +import java.util.LinkedList; + +public class CharStack { + + private LinkedList items; + + public CharStack() { + this.items = new LinkedList(); + } + + public void push(Character item) { + items.push(item); + } + + public Character peek() { + return items.getFirst(); + } + + public Character pop() { + + Iterator iter = items.iterator(); + Character item = iter.next(); + if (item != null) { + iter.remove(); + return item; + } + return null; + } + + public int size() { + return items.size(); + } + +} diff --git a/core-java-collections/src/main/java/com/baeldung/charstack/CharStackWithArray.java b/core-java-collections/src/main/java/com/baeldung/charstack/CharStackWithArray.java new file mode 100644 index 0000000000..ed7fa3f253 --- /dev/null +++ b/core-java-collections/src/main/java/com/baeldung/charstack/CharStackWithArray.java @@ -0,0 +1,48 @@ +package com.baeldung.charstack; + +public class CharStackWithArray { + + private char[] elements; + private int size; + + public CharStackWithArray() { + size = 0; + elements = new char[4]; + } + + public int size() { + return size; + } + + public char peek() { + if (size == 0) { + throw new EmptyStackException(); + } + return elements[size - 1]; + } + + public char pop() { + if (size == 0) { + throw new EmptyStackException(); + } + + return elements[--size]; + } + + public void push(char item) { + ensureCapacity(size + 1); + elements[size] = item; + size++; + } + + private void ensureCapacity(int newSize) { + char newBiggerArray[]; + + if (elements.length < newSize) { + newBiggerArray = new char[elements.length * 2]; + System.arraycopy(elements, 0, newBiggerArray, 0, size); + elements = newBiggerArray; + } + } + +} diff --git a/core-java-collections/src/main/java/com/baeldung/charstack/EmptyStackException.java b/core-java-collections/src/main/java/com/baeldung/charstack/EmptyStackException.java new file mode 100644 index 0000000000..f005854e7f --- /dev/null +++ b/core-java-collections/src/main/java/com/baeldung/charstack/EmptyStackException.java @@ -0,0 +1,9 @@ +package com.baeldung.charstack; + +public class EmptyStackException extends RuntimeException { + + public EmptyStackException() { + super("Stack is empty"); + } + +} 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 index 6b088a5079..4fcc211812 100644 --- a/core-java-collections/src/main/java/com/baeldung/queueInterface/CustomBaeldungQueue.java +++ b/core-java-collections/src/main/java/com/baeldung/queueInterface/CustomBaeldungQueue.java @@ -1,4 +1,4 @@ -package com.baeldung.queueinterface; +package com.baeldung.queueInterface; import java.util.AbstractQueue; import java.util.Iterator; diff --git a/core-java-collections/src/test/java/com/baeldung/charstack/CharStackUnitTest.java b/core-java-collections/src/test/java/com/baeldung/charstack/CharStackUnitTest.java new file mode 100644 index 0000000000..a20526fd9d --- /dev/null +++ b/core-java-collections/src/test/java/com/baeldung/charstack/CharStackUnitTest.java @@ -0,0 +1,50 @@ +package com.baeldung.charstack; + +import static org.junit.Assert.assertEquals; + +import org.junit.jupiter.api.Test; + +public class CharStackUnitTest { + + @Test + public void whenCharStackIsCreated_thenItHasSize0() { + + CharStack charStack = new CharStack(); + + assertEquals(0, charStack.size()); + } + + @Test + public void givenEmptyCharStack_whenElementIsPushed_thenStackSizeisIncreased() { + + CharStack charStack = new CharStack(); + + charStack.push('A'); + + assertEquals(1, charStack.size()); + } + + @Test + public void givenCharStack_whenElementIsPoppedFromStack_thenElementIsRemovedAndSizeChanges() { + + CharStack charStack = new CharStack(); + charStack.push('A'); + + char element = charStack.pop(); + + assertEquals('A', element); + assertEquals(0, charStack.size()); + } + + @Test + public void givenCharStack_whenElementIsPeeked_thenElementIsNotRemovedAndSizeDoesNotChange() { + CharStack charStack = new CharStack(); + charStack.push('A'); + + char element = charStack.peek(); + + assertEquals('A', element); + assertEquals(1, charStack.size()); + } + +} diff --git a/core-java-collections/src/test/java/com/baeldung/charstack/CharStackUsingJavaUnitTest.java b/core-java-collections/src/test/java/com/baeldung/charstack/CharStackUsingJavaUnitTest.java new file mode 100644 index 0000000000..964b901ae0 --- /dev/null +++ b/core-java-collections/src/test/java/com/baeldung/charstack/CharStackUsingJavaUnitTest.java @@ -0,0 +1,53 @@ +package com.baeldung.charstack; + +import static org.junit.Assert.assertEquals; + +import java.util.Stack; + +import org.junit.jupiter.api.Test; + +public class CharStackUsingJavaUnitTest { + + @Test + public void whenCharStackIsCreated_thenItHasSize0() { + + Stack charStack = new Stack<>(); + + assertEquals(0, charStack.size()); + } + + @Test + public void givenEmptyCharStack_whenElementIsPushed_thenStackSizeisIncreased() { + + Stack charStack = new Stack<>(); + + charStack.push('A'); + + assertEquals(1, charStack.size()); + } + + @Test + public void givenCharStack_whenElementIsPoppedFromStack_thenElementIsRemovedAndSizeChanges() { + + Stack charStack = new Stack<>(); + charStack.push('A'); + + char element = charStack.pop(); + + assertEquals('A', element); + assertEquals(0, charStack.size()); + } + + @Test + public void givenCharStack_whenElementIsPeeked_thenElementIsNotRemovedAndSizeDoesNotChange() { + + Stack charStack = new Stack<>(); + charStack.push('A'); + + char element = charStack.peek(); + + assertEquals('A', element); + assertEquals(1, charStack.size()); + } + +} diff --git a/core-java-collections/src/test/java/com/baeldung/charstack/CharStackWithArrayUnitTest.java b/core-java-collections/src/test/java/com/baeldung/charstack/CharStackWithArrayUnitTest.java new file mode 100644 index 0000000000..df90b8f0a4 --- /dev/null +++ b/core-java-collections/src/test/java/com/baeldung/charstack/CharStackWithArrayUnitTest.java @@ -0,0 +1,65 @@ +package com.baeldung.charstack; + +import static org.junit.Assert.assertEquals; + +import org.junit.jupiter.api.Test; + +public class CharStackWithArrayUnitTest { + + @Test + public void whenCharStackIsCreated_thenItHasSize0() { + + CharStackWithArray charStack = new CharStackWithArray(); + + assertEquals(0, charStack.size()); + } + + @Test + public void givenEmptyCharStack_whenElementIsPushed_thenStackSizeisIncreased() { + + CharStackWithArray charStack = new CharStackWithArray(); + + charStack.push('A'); + + assertEquals(1, charStack.size()); + } + + @Test + public void givenEmptyCharStack_when5ElementIsPushed_thenStackSizeis() { + + CharStackWithArray charStack = new CharStackWithArray(); + + charStack.push('A'); + charStack.push('B'); + charStack.push('C'); + charStack.push('D'); + charStack.push('E'); + + assertEquals(5, charStack.size()); + } + + @Test + public void givenCharStack_whenElementIsPoppedFromStack_thenElementIsRemovedAndSizeChanges() { + + CharStackWithArray charStack = new CharStackWithArray(); + charStack.push('A'); + + char element = charStack.pop(); + + assertEquals('A', element); + assertEquals(0, charStack.size()); + } + + @Test + public void givenCharStack_whenElementIsPeeked_thenElementIsNotRemovedAndSizeDoesNotChange() { + + CharStackWithArray charStack = new CharStackWithArray(); + charStack.push('A'); + + char element = charStack.peek(); + + assertEquals('A', element); + assertEquals(1, charStack.size()); + } + +} 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 index 6dec768542..7471d9841d 100644 --- a/core-java-collections/src/test/java/com/baeldung/queueinterface/CustomBaeldungQueueUnitTest.java +++ b/core-java-collections/src/test/java/com/baeldung/queueinterface/CustomBaeldungQueueUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.queueinterface; +package com.baeldung.queueInterface; import org.junit.Before; import org.junit.Test; 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 similarity index 96% rename from core-java-collections/src/test/java/com/baeldung/queueInterface/PriorityQueueUnitTest.java rename to core-java-collections/src/test/java/com/baeldung/queueinterface/PriorityQueueUnitTest.java index c5b564b55b..748099e8d1 100644 --- a/core-java-collections/src/test/java/com/baeldung/queueInterface/PriorityQueueUnitTest.java +++ b/core-java-collections/src/test/java/com/baeldung/queueinterface/PriorityQueueUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.queueinterface; +package com.baeldung.queueInterface; import org.junit.Before; import org.junit.Test; diff --git a/core-java-concurrency-advanced/pom.xml b/core-java-concurrency-advanced/pom.xml index 1209cba619..23032fb2e1 100644 --- a/core-java-concurrency-advanced/pom.xml +++ b/core-java-concurrency-advanced/pom.xml @@ -4,8 +4,8 @@ com.baeldung core-java-concurrency-advanced 0.1.0-SNAPSHOT - jar core-java-concurrency-advanced + jar com.baeldung diff --git a/core-java-concurrency-basic/pom.xml b/core-java-concurrency-basic/pom.xml index 3544403aca..35c360769b 100644 --- a/core-java-concurrency-basic/pom.xml +++ b/core-java-concurrency-basic/pom.xml @@ -4,8 +4,8 @@ com.baeldung core-java-concurrency-basic 0.1.0-SNAPSHOT - jar core-java-concurrency-basic + jar com.baeldung diff --git a/core-java-concurrency-collections/pom.xml b/core-java-concurrency-collections/pom.xml index 9473de8c51..e192bbe46f 100644 --- a/core-java-concurrency-collections/pom.xml +++ b/core-java-concurrency-collections/pom.xml @@ -4,8 +4,8 @@ com.baeldung core-java-concurrency-collections 0.1.0-SNAPSHOT - jar core-java-concurrency-collections + jar com.baeldung diff --git a/core-java-io/README.md b/core-java-io/README.md index 2ad980ca6a..9a25009849 100644 --- a/core-java-io/README.md +++ b/core-java-io/README.md @@ -36,4 +36,7 @@ - [Reading a CSV File into an Array](https://www.baeldung.com/java-csv-file-array) - [Guide to BufferedReader](https://www.baeldung.com/java-buffered-reader) - [How to Get the File Extension of a File in Java](http://www.baeldung.com/java-file-extension) -- [Getting a File’s Mime Type in Java](http://www.baeldung.com/java-file-mime-type) \ No newline at end of file +- [Getting a File’s Mime Type in Java](http://www.baeldung.com/java-file-mime-type) +- [Create a Directory in Java](https://www.baeldung.com/java-create-directory) +- [How to Write to a CSV File in Java](https://www.baeldung.com/java-csv) +- [List Files in a Directory in Java](https://www.baeldung.com/java-list-directory-files) diff --git a/core-java-io/pom.xml b/core-java-io/pom.xml index 1f2d52de81..350e1a8b96 100644 --- a/core-java-io/pom.xml +++ b/core-java-io/pom.xml @@ -3,8 +3,8 @@ 4.0.0 core-java-io 0.1.0-SNAPSHOT - jar core-java-io + jar com.baeldung diff --git a/core-java-lang-oop/pom.xml b/core-java-lang-oop/pom.xml index 262408c024..8cfaf2b544 100644 --- a/core-java-lang-oop/pom.xml +++ b/core-java-lang-oop/pom.xml @@ -4,8 +4,8 @@ com.baeldung core-java-lang-oop 0.1.0-SNAPSHOT - jar core-java-lang-oop + jar com.baeldung diff --git a/core-java-lang-oop/src/main/java/com/baeldung/markerinterface/DeletableShape.java b/core-java-lang-oop/src/main/java/com/baeldung/markerinterface/DeletableShape.java new file mode 100644 index 0000000000..7674407da8 --- /dev/null +++ b/core-java-lang-oop/src/main/java/com/baeldung/markerinterface/DeletableShape.java @@ -0,0 +1,5 @@ +package com.baeldung.markerinterface; + +public interface DeletableShape extends Shape { + +} diff --git a/core-java-lang-oop/src/main/java/com/baeldung/markerinterface/Rectangle.java b/core-java-lang-oop/src/main/java/com/baeldung/markerinterface/Rectangle.java new file mode 100644 index 0000000000..d64ffad0a2 --- /dev/null +++ b/core-java-lang-oop/src/main/java/com/baeldung/markerinterface/Rectangle.java @@ -0,0 +1,22 @@ +package com.baeldung.markerinterface; + +public class Rectangle implements DeletableShape { + + private double width; + private double height; + + public Rectangle(double width, double height) { + this.width = width; + this.height = height; + } + + @Override + public double getArea() { + return width * height; + } + + @Override + public double getCircumference() { + return 2 * (width + height); + } +} diff --git a/core-java-lang-oop/src/main/java/com/baeldung/markerinterface/Shape.java b/core-java-lang-oop/src/main/java/com/baeldung/markerinterface/Shape.java new file mode 100644 index 0000000000..2e53aefc03 --- /dev/null +++ b/core-java-lang-oop/src/main/java/com/baeldung/markerinterface/Shape.java @@ -0,0 +1,6 @@ +package com.baeldung.markerinterface; + +public interface Shape { + double getArea(); + double getCircumference(); +} \ No newline at end of file diff --git a/core-java-lang-oop/src/main/java/com/baeldung/markerinterface/ShapeDao.java b/core-java-lang-oop/src/main/java/com/baeldung/markerinterface/ShapeDao.java new file mode 100644 index 0000000000..bc988a793d --- /dev/null +++ b/core-java-lang-oop/src/main/java/com/baeldung/markerinterface/ShapeDao.java @@ -0,0 +1,14 @@ +package com.baeldung.markerinterface; + +public class ShapeDao { + + public boolean delete(Object object) { + if (!(object instanceof DeletableShape)) { + return false; + } + // Calling the code that deletes the entity from the database + + return true; + } + +} diff --git a/core-java-lang-oop/src/test/java/com/baeldung/markerinterface/MarkerInterfaceUnitTest.java b/core-java-lang-oop/src/test/java/com/baeldung/markerinterface/MarkerInterfaceUnitTest.java new file mode 100644 index 0000000000..70d32ba253 --- /dev/null +++ b/core-java-lang-oop/src/test/java/com/baeldung/markerinterface/MarkerInterfaceUnitTest.java @@ -0,0 +1,26 @@ +package com.baeldung.markerinterface; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Test; + +public class MarkerInterfaceUnitTest { + + @Test + public void givenDeletableObjectThenTrueReturned() { + ShapeDao shapeDao = new ShapeDao(); + Object rectangle = new Rectangle(2, 3); + + boolean result = shapeDao.delete(rectangle); + assertEquals(true, result); + } + + @Test + public void givenNonDeletableObjectThenFalseReturned() { + ShapeDao shapeDao = new ShapeDao(); + Object object = new Object(); + + boolean result = shapeDao.delete(object); + assertEquals(false, result); + } +} diff --git a/core-java-lang-syntax/README.md b/core-java-lang-syntax/README.md index a7c1b7cc4a..99c8613929 100644 --- a/core-java-lang-syntax/README.md +++ b/core-java-lang-syntax/README.md @@ -16,4 +16,5 @@ - [Quick Guide to java.lang.System](http://www.baeldung.com/java-lang-system) - [Java Switch Statement](https://www.baeldung.com/java-switch) - [The Modulo Operator in Java](https://www.baeldung.com/modulo-java) -- [Ternary Operator In Java](https://www.baeldung.com/java-ternary-operator) \ No newline at end of file +- [Ternary Operator In Java](https://www.baeldung.com/java-ternary-operator) +- [Java instanceof Operator](https://www.baeldung.com/java-instanceof) diff --git a/core-java-lang-syntax/pom.xml b/core-java-lang-syntax/pom.xml index 9481f29459..9a9df01057 100644 --- a/core-java-lang-syntax/pom.xml +++ b/core-java-lang-syntax/pom.xml @@ -4,8 +4,8 @@ com.baeldung core-java-lang-syntax 0.1.0-SNAPSHOT - jar core-java-lang-syntax + jar com.baeldung diff --git a/core-java-lang/README.md b/core-java-lang/README.md index 7af962558d..c1c22caf6c 100644 --- a/core-java-lang/README.md +++ b/core-java-lang/README.md @@ -34,4 +34,10 @@ - [“Sneaky Throws” in Java](http://www.baeldung.com/java-sneaky-throws) - [Retrieving a Class Name in Java](https://www.baeldung.com/java-class-name) - [Java Compound Operators](https://www.baeldung.com/java-compound-operators) -- [Guide to Java Packages](https://www.baeldung.com/java-packages) \ No newline at end of file +- [Guide to Java Packages](https://www.baeldung.com/java-packages) +- [The Java Native Keyword and Methods](https://www.baeldung.com/java-native) +- [If-Else Statement in Java](https://www.baeldung.com/java-if-else) +- [Control Structures in Java](https://www.baeldung.com/java-control-structures) +- [Java Interfaces](https://www.baeldung.com/java-interfaces) +- [Attaching Values to Java Enum](https://www.baeldung.com/java-enum-values) +- [Variable Scope in Java](https://www.baeldung.com/java-variable-scope) diff --git a/core-java-lang/pom.xml b/core-java-lang/pom.xml index 283acab775..6881fd56db 100644 --- a/core-java-lang/pom.xml +++ b/core-java-lang/pom.xml @@ -4,8 +4,8 @@ com.baeldung core-java-lang 0.1.0-SNAPSHOT - jar core-java-lang + jar com.baeldung diff --git a/core-java-lang/src/main/java/com/baeldung/scope/BracketScopeExample.java b/core-java-lang/src/main/java/com/baeldung/scope/BracketScopeExample.java index 37ae211dcb..8deec35c16 100644 --- a/core-java-lang/src/main/java/com/baeldung/scope/BracketScopeExample.java +++ b/core-java-lang/src/main/java/com/baeldung/scope/BracketScopeExample.java @@ -1,4 +1,4 @@ -package org.baeldung.variable.scope.examples; +package com.baeldung.scope; public class BracketScopeExample { diff --git a/core-java-lang/src/main/java/com/baeldung/scope/ClassScopeExample.java b/core-java-lang/src/main/java/com/baeldung/scope/ClassScopeExample.java index 241c6b466e..c81fcc9550 100644 --- a/core-java-lang/src/main/java/com/baeldung/scope/ClassScopeExample.java +++ b/core-java-lang/src/main/java/com/baeldung/scope/ClassScopeExample.java @@ -1,4 +1,4 @@ -package org.baeldung.variable.scope.examples; +package com.baeldung.scope; public class ClassScopeExample { diff --git a/core-java-lang/src/main/java/com/baeldung/scope/LoopScopeExample.java b/core-java-lang/src/main/java/com/baeldung/scope/LoopScopeExample.java index 7bf92a6d26..be41252623 100644 --- a/core-java-lang/src/main/java/com/baeldung/scope/LoopScopeExample.java +++ b/core-java-lang/src/main/java/com/baeldung/scope/LoopScopeExample.java @@ -1,4 +1,4 @@ -package org.baeldung.variable.scope.examples; +package com.baeldung.scope; import java.util.Arrays; import java.util.List; diff --git a/core-java-lang/src/main/java/com/baeldung/scope/MethodScopeExample.java b/core-java-lang/src/main/java/com/baeldung/scope/MethodScopeExample.java index e62c6a2a1c..63a6a25271 100644 --- a/core-java-lang/src/main/java/com/baeldung/scope/MethodScopeExample.java +++ b/core-java-lang/src/main/java/com/baeldung/scope/MethodScopeExample.java @@ -1,4 +1,4 @@ -package org.baeldung.variable.scope.examples; +package com.baeldung.scope; public class MethodScopeExample { diff --git a/core-java-lang/src/main/java/com/baeldung/scope/NestedScopesExample.java b/core-java-lang/src/main/java/com/baeldung/scope/NestedScopesExample.java index fcd23e5ae0..c3c5bec221 100644 --- a/core-java-lang/src/main/java/com/baeldung/scope/NestedScopesExample.java +++ b/core-java-lang/src/main/java/com/baeldung/scope/NestedScopesExample.java @@ -1,4 +1,4 @@ -package org.baeldung.variable.scope.examples; +package com.baeldung.scope; public class NestedScopesExample { diff --git a/core-java-lang/src/test/java/com/baeldung/java/enumiteration/EnumIterationExamples.java b/core-java-lang/src/test/java/com/baeldung/java/enumiteration/EnumIterationExamples.java index 2d874fa650..110943e39f 100644 --- a/core-java-lang/src/test/java/com/baeldung/java/enumiteration/EnumIterationExamples.java +++ b/core-java-lang/src/test/java/com/baeldung/java/enumiteration/EnumIterationExamples.java @@ -1,18 +1,43 @@ package com.baeldung.java.enumiteration; +import java.util.ArrayList; +import java.util.Arrays; import java.util.EnumSet; +import java.util.List; + public class EnumIterationExamples { public static void main(String[] args) { - System.out.println("Enum iteration using forEach:"); + System.out.println("Enum iteration using EnumSet:"); EnumSet.allOf(DaysOfWeekEnum.class).forEach(day -> System.out.println(day)); System.out.println("Enum iteration using Stream:"); DaysOfWeekEnum.stream().filter(d -> d.getTypeOfDay().equals("off")).forEach(System.out::println); - System.out.println("Enum iteration using for loop:"); + System.out.println("Enum iteration using a for loop:"); for (DaysOfWeekEnum day : DaysOfWeekEnum.values()) { System.out.println(day); } + + System.out.println("Enum iteration using Arrays.asList():"); + Arrays.asList(DaysOfWeekEnum.values()).forEach(day -> System.out.println(day)); + + System.out.println("Add Enum values to ArrayList:"); + List days = new ArrayList<>(); + days.add(DaysOfWeekEnum.FRIDAY); + days.add(DaysOfWeekEnum.SATURDAY); + days.add(DaysOfWeekEnum.SUNDAY); + for (DaysOfWeekEnum day : days) { + System.out.println(day); + } + System.out.println("Remove SATURDAY from the list:"); + days.remove(DaysOfWeekEnum.SATURDAY); + if (!days.contains(DaysOfWeekEnum.SATURDAY)) { + System.out.println("Saturday is no longer in the list"); + } + for (DaysOfWeekEnum day : days) { + System.out.println(day); + } + } } diff --git a/core-java-networking/pom.xml b/core-java-networking/pom.xml index d9c7c691e9..12bb257fcb 100644 --- a/core-java-networking/pom.xml +++ b/core-java-networking/pom.xml @@ -3,8 +3,8 @@ 4.0.0 core-java-networking 0.1.0-SNAPSHOT - jar core-java-networking + jar com.baeldung diff --git a/core-java-perf/README.md b/core-java-perf/README.md index 252ee4cc45..1b3b590bf8 100644 --- a/core-java-perf/README.md +++ b/core-java-perf/README.md @@ -5,4 +5,5 @@ - [Different Ways to Capture Java Heap Dumps](https://www.baeldung.com/java-heap-dump-capture) - [Understanding Memory Leaks in Java](https://www.baeldung.com/java-memory-leaks) - [OutOfMemoryError: GC Overhead Limit Exceeded](http://www.baeldung.com/java-gc-overhead-limit-exceeded) -- [Basic Introduction to JMX](http://www.baeldung.com/java-management-extensions) \ No newline at end of file +- [Basic Introduction to JMX](http://www.baeldung.com/java-management-extensions) +- [Monitoring Java Applications with Flight Recorder](https://www.baeldung.com/java-flight-recorder-monitoring) diff --git a/core-java-perf/pom.xml b/core-java-perf/pom.xml index 062f76db77..0e0ec79691 100644 --- a/core-java-perf/pom.xml +++ b/core-java-perf/pom.xml @@ -4,8 +4,8 @@ com.baeldung core-java-perf 0.1.0-SNAPSHOT - jar core-java-perf + jar com.baeldung diff --git a/core-java-security/README.md b/core-java-security/README.md index 415171094b..d3343f79ca 100644 --- a/core-java-security/README.md +++ b/core-java-security/README.md @@ -8,4 +8,5 @@ - [Encrypting and Decrypting Files in Java](http://www.baeldung.com/java-cipher-input-output-stream) - [Hashing a Password in Java](https://www.baeldung.com/java-password-hashing) - [SSL Handshake Failures](https://www.baeldung.com/java-ssl-handshake-failures) -- [SHA-256 Hashing in Java](https://www.baeldung.com/sha-256-hashing-java) \ No newline at end of file +- [SHA-256 Hashing in Java](https://www.baeldung.com/sha-256-hashing-java) +- [Enabling TLS v1.2 in Java 7](https://www.baeldung.com/java-7-tls-v12) diff --git a/core-java-security/pom.xml b/core-java-security/pom.xml index cf91121465..63bc46b114 100644 --- a/core-java-security/pom.xml +++ b/core-java-security/pom.xml @@ -4,8 +4,8 @@ com.baeldung core-java-security 0.1.0-SNAPSHOT - jar core-java-security + jar com.baeldung @@ -44,8 +44,8 @@ 3.8.1 - 1.55 - 1.10 + 1.60 + 1.11 3.10.0 diff --git a/core-java-security/src/main/java/com/baeldung/hashing/DigestAlgorithms.java b/core-java-security/src/main/java/com/baeldung/hashing/DigestAlgorithms.java new file mode 100644 index 0000000000..94dd22ff4b --- /dev/null +++ b/core-java-security/src/main/java/com/baeldung/hashing/DigestAlgorithms.java @@ -0,0 +1,9 @@ +package com.baeldung.hashing; + +public class DigestAlgorithms { + + public static final String SHA3_256 = "SHA3-256"; + public static final String SHA_256 = "SHA-256"; + public static final String KECCAK_256 = "Keccak-256"; + +} diff --git a/core-java-security/src/main/java/com/baeldung/hashing/Keccak256Hashing.java b/core-java-security/src/main/java/com/baeldung/hashing/Keccak256Hashing.java new file mode 100644 index 0000000000..19fc4cf059 --- /dev/null +++ b/core-java-security/src/main/java/com/baeldung/hashing/Keccak256Hashing.java @@ -0,0 +1,30 @@ +package com.baeldung.hashing; + +import org.bouncycastle.jcajce.provider.digest.Keccak; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.util.encoders.Hex; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.Security; + +import static com.baeldung.hashing.DigestAlgorithms.KECCAK_256; +import static com.baeldung.hashing.SHACommonUtils.bytesToHex; + +public class Keccak256Hashing { + + public static String hashWithJavaMessageDigest(final String originalString) throws NoSuchAlgorithmException { + Security.addProvider(new BouncyCastleProvider()); + final MessageDigest digest = MessageDigest.getInstance(KECCAK_256); + final byte[] encodedhash = digest.digest(originalString.getBytes(StandardCharsets.UTF_8)); + return bytesToHex(encodedhash); + } + + public static String hashWithBouncyCastle(final String originalString) { + Keccak.Digest256 digest256 = new Keccak.Digest256(); + byte[] hashbytes = digest256.digest(originalString.getBytes(StandardCharsets.UTF_8)); + return new String(Hex.encode(hashbytes)); + } + +} diff --git a/core-java-security/src/main/java/com/baeldung/hashing/SHA256Hashing.java b/core-java-security/src/main/java/com/baeldung/hashing/SHA256Hashing.java index 4fa164cadc..ec008cebab 100644 --- a/core-java-security/src/main/java/com/baeldung/hashing/SHA256Hashing.java +++ b/core-java-security/src/main/java/com/baeldung/hashing/SHA256Hashing.java @@ -8,15 +8,18 @@ import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; +import static com.baeldung.hashing.DigestAlgorithms.SHA_256; +import static com.baeldung.hashing.SHACommonUtils.bytesToHex; + public class SHA256Hashing { public static String HashWithJavaMessageDigest(final String originalString) throws NoSuchAlgorithmException { - final MessageDigest digest = MessageDigest.getInstance("SHA-256"); + final MessageDigest digest = MessageDigest.getInstance(SHA_256); final byte[] encodedhash = digest.digest(originalString.getBytes(StandardCharsets.UTF_8)); return bytesToHex(encodedhash); } - public static String HashWithGuava(final String originalString) { + public static String hashWithGuava(final String originalString) { final String sha256hex = Hashing.sha256().hashString(originalString, StandardCharsets.UTF_8).toString(); return sha256hex; } @@ -27,20 +30,10 @@ public class SHA256Hashing { } public static String HashWithBouncyCastle(final String originalString) throws NoSuchAlgorithmException { - final MessageDigest digest = MessageDigest.getInstance("SHA-256"); + final MessageDigest digest = MessageDigest.getInstance(SHA_256); final byte[] hash = digest.digest(originalString.getBytes(StandardCharsets.UTF_8)); final String sha256hex = new String(Hex.encode(hash)); return sha256hex; } - private static String bytesToHex(byte[] hash) { - StringBuffer hexString = new StringBuffer(); - for (int i = 0; i < hash.length; i++) { - String hex = Integer.toHexString(0xff & hash[i]); - if (hex.length() == 1) - hexString.append('0'); - hexString.append(hex); - } - return hexString.toString(); - } } diff --git a/core-java-security/src/main/java/com/baeldung/hashing/SHA3Hashing.java b/core-java-security/src/main/java/com/baeldung/hashing/SHA3Hashing.java new file mode 100644 index 0000000000..eb363205b1 --- /dev/null +++ b/core-java-security/src/main/java/com/baeldung/hashing/SHA3Hashing.java @@ -0,0 +1,45 @@ +package com.baeldung.hashing; + +import com.google.common.hash.Hashing; +import org.apache.commons.codec.digest.DigestUtils; +import org.bouncycastle.crypto.digests.SHA3Digest; +import org.bouncycastle.jcajce.provider.digest.SHA3; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.util.encoders.Hex; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.Security; + +import static com.baeldung.hashing.DigestAlgorithms.SHA3_256; +import static com.baeldung.hashing.SHACommonUtils.bytesToHex; + +public class SHA3Hashing { + + /* works with JDK9+ only */ + public static String hashWithJavaMessageDigestJDK9(final String originalString) throws NoSuchAlgorithmException { + final MessageDigest digest = MessageDigest.getInstance(SHA3_256); + final byte[] hashbytes = digest.digest(originalString.getBytes(StandardCharsets.UTF_8)); + return bytesToHex(hashbytes); + } + + public static String hashWithJavaMessageDigest(final String originalString) throws NoSuchAlgorithmException { + Security.addProvider(new BouncyCastleProvider()); + final MessageDigest digest = MessageDigest.getInstance(SHA3_256); + final byte[] hashbytes = digest.digest(originalString.getBytes(StandardCharsets.UTF_8)); + return bytesToHex(hashbytes); + } + + /* works with JDK9+ only */ + public static String hashWithApacheCommonsJDK9(final String originalString) { + return new DigestUtils(SHA3_256).digestAsHex(originalString); + } + + public static String hashWithBouncyCastle(final String originalString) { + SHA3.Digest256 digest256 = new SHA3.Digest256(); + byte[] hashbytes = digest256.digest(originalString.getBytes(StandardCharsets.UTF_8)); + return new String(Hex.encode(hashbytes)); + } + +} diff --git a/core-java-security/src/main/java/com/baeldung/hashing/SHACommonUtils.java b/core-java-security/src/main/java/com/baeldung/hashing/SHACommonUtils.java new file mode 100644 index 0000000000..0f28408083 --- /dev/null +++ b/core-java-security/src/main/java/com/baeldung/hashing/SHACommonUtils.java @@ -0,0 +1,16 @@ +package com.baeldung.hashing; + +class SHACommonUtils { + + public static String bytesToHex(byte[] hash) { + StringBuffer hexString = new StringBuffer(); + for (byte h : hash) { + String hex = Integer.toHexString(0xff & h); + if (hex.length() == 1) + hexString.append('0'); + hexString.append(hex); + } + return hexString.toString(); + } + +} diff --git a/core-java-security/src/test/java/com/baeldung/hashing/Keccak256HashingUnitTest.java b/core-java-security/src/test/java/com/baeldung/hashing/Keccak256HashingUnitTest.java new file mode 100644 index 0000000000..9ed35c8834 --- /dev/null +++ b/core-java-security/src/test/java/com/baeldung/hashing/Keccak256HashingUnitTest.java @@ -0,0 +1,22 @@ +package com.baeldung.hashing; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class Keccak256HashingUnitTest { + + private static String originalValue = "abc123"; + private static String hashedValue = "719accc61a9cc126830e5906f9d672d06eab6f8597287095a2c55a8b775e7016"; + + @Test public void testHashWithJavaMessageDigest() throws Exception { + final String currentHashedValue = Keccak256Hashing.hashWithJavaMessageDigest(originalValue); + assertEquals(hashedValue, currentHashedValue); + } + + @Test public void testHashWithBouncyCastle() { + final String currentHashedValue = Keccak256Hashing.hashWithBouncyCastle(originalValue); + assertEquals(hashedValue, currentHashedValue); + } + +} diff --git a/core-java-security/src/test/java/com/baeldung/hashing/SHA256HashingUnitTest.java b/core-java-security/src/test/java/com/baeldung/hashing/SHA256HashingUnitTest.java index 3c34bf2c6e..6bc9ad2cc6 100644 --- a/core-java-security/src/test/java/com/baeldung/hashing/SHA256HashingUnitTest.java +++ b/core-java-security/src/test/java/com/baeldung/hashing/SHA256HashingUnitTest.java @@ -12,24 +12,24 @@ public class SHA256HashingUnitTest { @Test public void testHashWithJavaMessageDigest() throws Exception { final String currentHashedValue = SHA256Hashing.HashWithJavaMessageDigest(originalValue); - assertEquals(currentHashedValue, hashedValue); + assertEquals(hashedValue, currentHashedValue); } @Test public void testHashWithGuava() throws Exception { - final String currentHashedValue = SHA256Hashing.HashWithApacheCommons(originalValue); - assertEquals(currentHashedValue, hashedValue); + final String currentHashedValue = SHA256Hashing.hashWithGuava(originalValue); + assertEquals(hashedValue, currentHashedValue); } @Test public void testHashWithApacheCommans() throws Exception { - final String currentHashedValue = SHA256Hashing.HashWithGuava(originalValue); - assertEquals(currentHashedValue, hashedValue); + final String currentHashedValue = SHA256Hashing.HashWithApacheCommons(originalValue); + assertEquals(hashedValue, currentHashedValue); } @Test public void testHashWithBouncyCastle() throws Exception { final String currentHashedValue = SHA256Hashing.HashWithBouncyCastle(originalValue); - assertEquals(currentHashedValue, hashedValue); + assertEquals(hashedValue, currentHashedValue); } } \ No newline at end of file diff --git a/core-java-security/src/test/java/com/baeldung/hashing/SHA3HashingUnitTest.java b/core-java-security/src/test/java/com/baeldung/hashing/SHA3HashingUnitTest.java new file mode 100644 index 0000000000..fffab96405 --- /dev/null +++ b/core-java-security/src/test/java/com/baeldung/hashing/SHA3HashingUnitTest.java @@ -0,0 +1,38 @@ +package com.baeldung.hashing; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class SHA3HashingUnitTest { + + private static String originalValue = "abc123"; + private static String hashedValue = "f58fa3df820114f56e1544354379820cff464c9c41cb3ca0ad0b0843c9bb67ee"; + + /* works with JDK9+ only */ + //@Test + public void testHashWithJavaMessageDigestJDK9() throws Exception { + final String currentHashedValue = SHA3Hashing.hashWithJavaMessageDigestJDK9(originalValue); + assertEquals(hashedValue, currentHashedValue); + } + + @Test + public void testHashWithJavaMessageDigest() throws Exception { + final String currentHashedValue = SHA3Hashing.hashWithJavaMessageDigest(originalValue); + assertEquals(hashedValue, currentHashedValue); + } + + /* works with JDK9+ only */ + //@Test + public void testHashWithApacheCommonsJDK9() { + final String currentHashedValue = SHA3Hashing.hashWithApacheCommonsJDK9(originalValue); + assertEquals(hashedValue, currentHashedValue); + } + + @Test + public void testHashWithBouncyCastle() { + final String currentHashedValue = SHA3Hashing.hashWithBouncyCastle(originalValue); + assertEquals(hashedValue, currentHashedValue); + } + +} diff --git a/core-java-sun/pom.xml b/core-java-sun/pom.xml index ef68c947ce..6099e7a5ac 100644 --- a/core-java-sun/pom.xml +++ b/core-java-sun/pom.xml @@ -4,8 +4,8 @@ com.baeldung core-java-sun 0.1.0-SNAPSHOT - jar core-java-sun + jar com.baeldung diff --git a/core-java/README.md b/core-java/README.md index 5aee69d9a9..d2fd903c10 100644 --- a/core-java/README.md +++ b/core-java/README.md @@ -46,3 +46,8 @@ - [Graphs in Java](https://www.baeldung.com/java-graphs) - [Console I/O in Java](http://www.baeldung.com/java-console-input-output) - [Formatting with printf() in Java](https://www.baeldung.com/java-printstream-printf) +- [Retrieve Fields from a Java Class Using Reflection](https://www.baeldung.com/java-reflection-class-fields) +- [Introduction to Basic Syntax in Java](https://www.baeldung.com/java-syntax) +- [Using Curl in Java](https://www.baeldung.com/java-curl) +- [Finding Leap Years in Java](https://www.baeldung.com/java-leap-year) +- [Java Bitwise Operators](https://www.baeldung.com/java-bitwise-operators) diff --git a/core-java/src/main/java/com/baeldung/jar/JarExample.java b/core-java/src/main/java/com/baeldung/jar/JarExample.java new file mode 100644 index 0000000000..5f33188adf --- /dev/null +++ b/core-java/src/main/java/com/baeldung/jar/JarExample.java @@ -0,0 +1,9 @@ +package com.baeldung.jar; + +public class JarExample { + + public static void main(String[] args) { + System.out.println("Hello Baeldung Reader!"); + } + +} diff --git a/core-java/src/main/java/com/baeldung/jar/example_manifest.txt b/core-java/src/main/java/com/baeldung/jar/example_manifest.txt new file mode 100644 index 0000000000..90e83e9b42 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/jar/example_manifest.txt @@ -0,0 +1 @@ +Main-Class: com.baeldung.jar.JarExample diff --git a/core-java/src/main/java/com/baeldung/reflection/MonthEmployee.java b/core-java/src/main/java/com/baeldung/reflection/MonthEmployee.java index 697ecc1500..df2a19bbff 100644 --- a/core-java/src/main/java/com/baeldung/reflection/MonthEmployee.java +++ b/core-java/src/main/java/com/baeldung/reflection/MonthEmployee.java @@ -2,6 +2,6 @@ package com.baeldung.reflection; public class MonthEmployee extends Employee { - private double reward; + protected double reward; } diff --git a/core-java/src/main/java/com/baeldung/reflection/Person.java b/core-java/src/main/java/com/baeldung/reflection/Person.java index 23b312cdd9..e036ab5223 100644 --- a/core-java/src/main/java/com/baeldung/reflection/Person.java +++ b/core-java/src/main/java/com/baeldung/reflection/Person.java @@ -2,7 +2,7 @@ package com.baeldung.reflection; public class Person { - public String lastName; + protected String lastName; private String firstName; } diff --git a/core-java/src/test/java/com/baeldung/reflection/PersonAndEmployeeReflectionUnitTest.java b/core-java/src/test/java/com/baeldung/reflection/PersonAndEmployeeReflectionUnitTest.java index c051f165f1..b1a6a1fe57 100644 --- a/core-java/src/test/java/com/baeldung/reflection/PersonAndEmployeeReflectionUnitTest.java +++ b/core-java/src/test/java/com/baeldung/reflection/PersonAndEmployeeReflectionUnitTest.java @@ -3,10 +3,13 @@ package com.baeldung.reflection; import org.junit.Test; import java.lang.reflect.Field; +import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; import static org.junit.Assert.*; @@ -26,30 +29,14 @@ public class PersonAndEmployeeReflectionUnitTest { // Then assertEquals(2, allFields.length); - Field lastNameField = allFields[0]; - assertEquals(LAST_NAME_FIELD, lastNameField.getName()); - assertEquals(String.class, lastNameField.getType()); - - Field firstNameField = allFields[1]; - assertEquals(FIRST_NAME_FIELD, firstNameField.getName()); - assertEquals(String.class, firstNameField.getType()); - } - - @Test - public void givenEmployeeClass_whenSuperClassGetDeclaredFields_thenOneField() { - // When - Field[] allFields = Employee.class.getSuperclass().getDeclaredFields(); - - // Then - assertEquals(2, allFields.length); - - Field lastNameField = allFields[0]; - assertEquals(LAST_NAME_FIELD, lastNameField.getName()); - assertEquals(String.class, lastNameField.getType()); - - Field firstNameField = allFields[1]; - assertEquals(FIRST_NAME_FIELD, firstNameField.getName()); - assertEquals(String.class, firstNameField.getType()); + assertTrue(Arrays.stream(allFields).anyMatch(field -> + field.getName().equals(LAST_NAME_FIELD) + && field.getType().equals(String.class)) + ); + assertTrue(Arrays.stream(allFields).anyMatch(field -> + field.getName().equals(FIRST_NAME_FIELD) + && field.getType().equals(String.class)) + ); } @Test @@ -60,9 +47,28 @@ public class PersonAndEmployeeReflectionUnitTest { // Then assertEquals(1, allFields.length); - Field employeeIdField = allFields[0]; - assertEquals(EMPLOYEE_ID_FIELD, employeeIdField.getName()); - assertEquals(int.class, employeeIdField.getType()); + assertTrue(Arrays.stream(allFields).anyMatch(field -> + field.getName().equals(EMPLOYEE_ID_FIELD) + && field.getType().equals(int.class)) + ); + } + + @Test + public void givenEmployeeClass_whenSuperClassGetDeclaredFields_thenOneField() { + // When + Field[] allFields = Employee.class.getSuperclass().getDeclaredFields(); + + // Then + assertEquals(2, allFields.length); + + assertTrue(Arrays.stream(allFields).anyMatch(field -> + field.getName().equals(LAST_NAME_FIELD) + && field.getType().equals(String.class)) + ); + assertTrue(Arrays.stream(allFields).anyMatch(field -> + field.getName().equals(FIRST_NAME_FIELD) + && field.getType().equals(String.class)) + ); } @Test @@ -76,42 +82,56 @@ public class PersonAndEmployeeReflectionUnitTest { // Then assertEquals(3, allFields.length); - Field lastNameField = allFields[0]; - assertEquals(LAST_NAME_FIELD, lastNameField.getName()); - assertEquals(String.class, lastNameField.getType()); - - Field firstNameField = allFields[1]; - assertEquals(FIRST_NAME_FIELD, firstNameField.getName()); - assertEquals(String.class, firstNameField.getType()); - - Field employeeIdField = allFields[2]; - assertEquals(EMPLOYEE_ID_FIELD, employeeIdField.getName()); - assertEquals(int.class, employeeIdField.getType()); + assertTrue(Arrays.stream(allFields).anyMatch(field -> + field.getName().equals(LAST_NAME_FIELD) + && field.getType().equals(String.class)) + ); + assertTrue(Arrays.stream(allFields).anyMatch(field -> + field.getName().equals(FIRST_NAME_FIELD) + && field.getType().equals(String.class)) + ); + assertTrue(Arrays.stream(allFields).anyMatch(field -> + field.getName().equals(EMPLOYEE_ID_FIELD) + && field.getType().equals(int.class)) + ); } @Test - public void givenMonthEmployeeClass_whenGetAllFields_thenFourFields() { + public void givenEmployeeClass_whenGetDeclaredFieldsOnEmployeeSuperclassWithModifiersFilter_thenOneFields() { + // When + List personFields = Arrays.stream(Employee.class.getSuperclass().getDeclaredFields()) + .filter(f -> Modifier.isPublic(f.getModifiers()) || Modifier.isProtected(f.getModifiers())) + .collect(Collectors.toList()); + + // Then + assertEquals(1, personFields.size()); + + assertTrue(personFields.stream().anyMatch(field -> + field.getName().equals(LAST_NAME_FIELD) + && field.getType().equals(String.class)) + ); + } + + @Test + public void givenMonthEmployeeClass_whenGetAllFields_thenThreeFields() { // When List allFields = getAllFields(MonthEmployee.class); // Then - assertEquals(4, allFields.size()); + assertEquals(3, allFields.size()); - Field lastNameField = allFields.get(0); - assertEquals(LAST_NAME_FIELD, lastNameField.getName()); - assertEquals(String.class, lastNameField.getType()); - - Field firstNameField = allFields.get(1); - assertEquals(FIRST_NAME_FIELD, firstNameField.getName()); - assertEquals(String.class, firstNameField.getType()); - - Field employeeIdField = allFields.get(2); - assertEquals(EMPLOYEE_ID_FIELD, employeeIdField.getName()); - assertEquals(int.class, employeeIdField.getType()); - - Field monthEmployeeRewardField = allFields.get(3); - assertEquals(MONTH_EMPLOYEE_REWARD_FIELD, monthEmployeeRewardField.getName()); - assertEquals(double.class, monthEmployeeRewardField.getType()); + assertTrue(allFields.stream().anyMatch(field -> + field.getName().equals(LAST_NAME_FIELD) + && field.getType().equals(String.class)) + ); + assertTrue(allFields.stream().anyMatch(field -> + field.getName().equals(EMPLOYEE_ID_FIELD) + && field.getType().equals(int.class)) + ); + assertTrue(allFields.stream().anyMatch(field -> + field.getName().equals(MONTH_EMPLOYEE_REWARD_FIELD) + && field.getType().equals(double.class)) + ); } public List getAllFields(Class clazz) { @@ -119,9 +139,11 @@ public class PersonAndEmployeeReflectionUnitTest { return Collections.emptyList(); } - List result = new ArrayList<>(); - result.addAll(getAllFields(clazz.getSuperclass())); - result.addAll(Arrays.asList(clazz.getDeclaredFields())); + List result = new ArrayList<>(getAllFields(clazz.getSuperclass())); + List filteredFields = Arrays.stream(clazz.getDeclaredFields()) + .filter(f -> Modifier.isPublic(f.getModifiers()) || Modifier.isProtected(f.getModifiers())) + .collect(Collectors.toList()); + result.addAll(filteredFields); return result; } diff --git a/core-kotlin-2/.gitignore b/core-kotlin-2/.gitignore new file mode 100644 index 0000000000..0c017e8f8c --- /dev/null +++ b/core-kotlin-2/.gitignore @@ -0,0 +1,14 @@ +/bin/ + +#ignore gradle +.gradle/ + + +#ignore build and generated files +build/ +node/ +out/ + +#ignore installed node modules and package lock file +node_modules/ +package-lock.json diff --git a/core-kotlin-2/README.md b/core-kotlin-2/README.md new file mode 100644 index 0000000000..ff12555376 --- /dev/null +++ b/core-kotlin-2/README.md @@ -0,0 +1 @@ +## Relevant articles: diff --git a/core-kotlin-2/build.gradle b/core-kotlin-2/build.gradle new file mode 100644 index 0000000000..b058e0ecad --- /dev/null +++ b/core-kotlin-2/build.gradle @@ -0,0 +1,48 @@ + + +group 'com.baeldung.ktor' +version '1.0-SNAPSHOT' + + +buildscript { + ext.kotlin_version = '1.2.41' + + repositories { + mavenCentral() + } + dependencies { + + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" + } +} + +apply plugin: 'java' +apply plugin: 'kotlin' +apply plugin: 'application' + +mainClassName = 'APIServer.kt' + +sourceCompatibility = 1.8 +compileKotlin { kotlinOptions.jvmTarget = "1.8" } +compileTestKotlin { kotlinOptions.jvmTarget = "1.8" } + +kotlin { experimental { coroutines "enable" } } + +repositories { + mavenCentral() + jcenter() + maven { url "https://dl.bintray.com/kotlin/ktor" } +} +sourceSets { + main{ + kotlin{ + srcDirs 'com/baeldung/ktor' + } + } + +} + +dependencies { + compile "ch.qos.logback:logback-classic:1.2.1" + testCompile group: 'junit', name: 'junit', version: '4.12' +} \ No newline at end of file diff --git a/core-kotlin-2/gradle/wrapper/gradle-wrapper.jar b/core-kotlin-2/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000000..01b8bf6b1f Binary files /dev/null and b/core-kotlin-2/gradle/wrapper/gradle-wrapper.jar differ diff --git a/core-kotlin-2/gradle/wrapper/gradle-wrapper.properties b/core-kotlin-2/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000000..933b6473ce --- /dev/null +++ b/core-kotlin-2/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-bin.zip diff --git a/core-kotlin-2/gradlew b/core-kotlin-2/gradlew new file mode 100644 index 0000000000..cccdd3d517 --- /dev/null +++ b/core-kotlin-2/gradlew @@ -0,0 +1,172 @@ +#!/usr/bin/env sh + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=$(save "$@") + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong +if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then + cd "$(dirname "$0")" +fi + +exec "$JAVACMD" "$@" diff --git a/core-kotlin-2/gradlew.bat b/core-kotlin-2/gradlew.bat new file mode 100644 index 0000000000..f9553162f1 --- /dev/null +++ b/core-kotlin-2/gradlew.bat @@ -0,0 +1,84 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/core-kotlin-2/pom.xml b/core-kotlin-2/pom.xml new file mode 100644 index 0000000000..81df3cee81 --- /dev/null +++ b/core-kotlin-2/pom.xml @@ -0,0 +1,16 @@ + + + 4.0.0 + core-kotlin-2 + core-kotlin-2 + jar + + + com.baeldung + parent-kotlin + 1.0.0-SNAPSHOT + ../parent-kotlin + + + diff --git a/core-kotlin-2/resources/logback.xml b/core-kotlin-2/resources/logback.xml new file mode 100644 index 0000000000..9452207268 --- /dev/null +++ b/core-kotlin-2/resources/logback.xml @@ -0,0 +1,11 @@ + + + + %d{YYYY-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + \ No newline at end of file diff --git a/core-kotlin-2/settings.gradle b/core-kotlin-2/settings.gradle new file mode 100644 index 0000000000..c91c993971 --- /dev/null +++ b/core-kotlin-2/settings.gradle @@ -0,0 +1,2 @@ +rootProject.name = 'KtorWithKotlin' + diff --git a/core-kotlin-2/src/main/resources/logback.xml b/core-kotlin-2/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/core-kotlin-2/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/core-kotlin/src/test/kotlin/com/baeldung/voidtypes/VoidTypesUnitTest.kt b/core-kotlin-2/src/test/kotlin/voidtypes/VoidTypesUnitTest.kt similarity index 100% rename from core-kotlin/src/test/kotlin/com/baeldung/voidtypes/VoidTypesUnitTest.kt rename to core-kotlin-2/src/test/kotlin/voidtypes/VoidTypesUnitTest.kt diff --git a/core-kotlin-2/src/test/resources/Kotlin.in b/core-kotlin-2/src/test/resources/Kotlin.in new file mode 100644 index 0000000000..d140d4429e --- /dev/null +++ b/core-kotlin-2/src/test/resources/Kotlin.in @@ -0,0 +1,5 @@ +Hello to Kotlin. Its: +1. Concise +2. Safe +3. Interoperable +4. Tool-friendly \ No newline at end of file diff --git a/core-kotlin-2/src/test/resources/Kotlin.out b/core-kotlin-2/src/test/resources/Kotlin.out new file mode 100644 index 0000000000..63d15d2528 --- /dev/null +++ b/core-kotlin-2/src/test/resources/Kotlin.out @@ -0,0 +1,2 @@ +Kotlin +Concise, Safe, Interoperable, Tool-friendly \ No newline at end of file diff --git a/core-kotlin/README.md b/core-kotlin/README.md index 225ad87e87..6ee79b2a2e 100644 --- a/core-kotlin/README.md +++ b/core-kotlin/README.md @@ -51,3 +51,4 @@ - [Operator Overloading in Kotlin](https://www.baeldung.com/kotlin-operator-overloading) - [Inline Classes in Kotlin](https://www.baeldung.com/kotlin-inline-classes) - [Creating Java static final Equivalents in Kotlin](https://www.baeldung.com/kotlin-java-static-final) +- [Nested forEach in Kotlin](https://www.baeldung.com/kotlin-nested-foreach) diff --git a/core-kotlin/pom.xml b/core-kotlin/pom.xml index ed79ebc01b..5de986b49e 100644 --- a/core-kotlin/pom.xml +++ b/core-kotlin/pom.xml @@ -64,13 +64,13 @@ nl.komponents.kovenant kovenant - 3.3.0 + ${kovenant.version} pom uy.kohesive.injekt injekt-core - 1.16.1 + ${injekt-core.version} @@ -82,6 +82,8 @@ 3.10.0 1.4.197 1.15.0 + 3.3.0 + 1.16.1 diff --git a/core-kotlin/src/main/kotlin/com/baeldung/static/ConsoleUtils.kt b/core-kotlin/src/main/kotlin/com/baeldung/static/ConsoleUtils.kt new file mode 100644 index 0000000000..23c7cfb11a --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/static/ConsoleUtils.kt @@ -0,0 +1,10 @@ +package com.baeldung.static + +class ConsoleUtils { + companion object { + @JvmStatic + fun debug(debugMessage : String) { + println("[DEBUG] $debugMessage") + } + } +} \ No newline at end of file diff --git a/core-kotlin/src/main/kotlin/com/baeldung/static/LoggingUtils.kt b/core-kotlin/src/main/kotlin/com/baeldung/static/LoggingUtils.kt new file mode 100644 index 0000000000..e67addc9ea --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/static/LoggingUtils.kt @@ -0,0 +1,5 @@ +package com.baeldung.static + +fun debug(debugMessage : String) { + println("[DEBUG] $debugMessage") +} \ No newline at end of file diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/junit5/CalculatorTest5.kt b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/junit5/CalculatorTest5.kt index 40cd9adc99..daaedca5a3 100644 --- a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/junit5/CalculatorTest5.kt +++ b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/junit5/CalculatorTest5.kt @@ -7,12 +7,12 @@ class CalculatorTest5 { private val calculator = Calculator() @Test - fun whenAdding1and3_thenAnswerIs4() { + fun `Adding 1 and 3 should be equal to 4`() { Assertions.assertEquals(4, calculator.add(1, 3)) } @Test - fun whenDividingBy0_thenErrorOccurs() { + fun `Dividing by zero should throw the DivideByZeroException`() { val exception = Assertions.assertThrows(DivideByZeroException::class.java) { calculator.divide(5, 0) } @@ -21,7 +21,7 @@ class CalculatorTest5 { } @Test - fun whenSquaringNumbers_thenCorrectAnswerGiven() { + fun `The square of a number should be equal to that number multiplied in itself`() { Assertions.assertAll( Executable { Assertions.assertEquals(1, calculator.square(1)) }, Executable { Assertions.assertEquals(4, calculator.square(2)) }, @@ -76,7 +76,7 @@ class CalculatorTest5 { Tag("logarithms") ) @Test - fun whenIcalculateLog2Of8_thenIget3() { + fun `Log to base 2 of 8 should be equal to 3`() { Assertions.assertEquals(3.0, calculator.log(2, 8)) } } diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/junit5/SimpleTest5.kt b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/junit5/SimpleTest5.kt index 70d3fb90bf..15ff201430 100644 --- a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/junit5/SimpleTest5.kt +++ b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/junit5/SimpleTest5.kt @@ -5,15 +5,16 @@ import org.junit.jupiter.api.Disabled import org.junit.jupiter.api.Test class SimpleTest5 { + @Test - fun whenEmptyList_thenListIsEmpty() { + fun `isEmpty should return true for empty lists`() { val list = listOf() Assertions.assertTrue(list::isEmpty) } @Test @Disabled - fun when3equals4_thenTestFails() { + fun `3 is equal to 4`() { Assertions.assertEquals(3, 4) { "Three does not equal four" } diff --git a/core-kotlin/src/test/kotlin/com/baeldung/static/ConsoleUtilsUnitTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/static/ConsoleUtilsUnitTest.kt new file mode 100644 index 0000000000..8abed144eb --- /dev/null +++ b/core-kotlin/src/test/kotlin/com/baeldung/static/ConsoleUtilsUnitTest.kt @@ -0,0 +1,10 @@ +package com.baeldung.static + +import org.junit.Test + +class ConsoleUtilsUnitTest { + @Test + fun givenAStaticMethod_whenCalled_thenNoErrorIsThrown() { + ConsoleUtils.debug("test message") + } +} \ No newline at end of file diff --git a/core-kotlin/src/test/kotlin/com/baeldung/static/LoggingUtilsUnitTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/static/LoggingUtilsUnitTest.kt new file mode 100644 index 0000000000..59587ff009 --- /dev/null +++ b/core-kotlin/src/test/kotlin/com/baeldung/static/LoggingUtilsUnitTest.kt @@ -0,0 +1,10 @@ +package com.baeldung.static + +import org.junit.Test + +class LoggingUtilsUnitTest { + @Test + fun givenAPackageMethod_whenCalled_thenNoErrorIsThrown() { + debug("test message") + } +} \ No newline at end of file diff --git a/couchbase/pom.xml b/couchbase/pom.xml index 7da027597e..994b80e7cd 100644 --- a/couchbase/pom.xml +++ b/couchbase/pom.xml @@ -5,9 +5,9 @@ com.baeldung couchbase 0.1-SNAPSHOT - jar couchbase Couchbase Tutorials + jar com.baeldung diff --git a/custom-pmd/pom.xml b/custom-pmd/pom.xml index 0f73282ae3..74e6d9593b 100644 --- a/custom-pmd/pom.xml +++ b/custom-pmd/pom.xml @@ -4,8 +4,8 @@ org.baeldung.pmd custom-pmd 0.0.1 - jar custom-pmd + jar http://maven.apache.org diff --git a/ddd/pom.xml b/ddd/pom.xml index a61ae24e92..749e444e52 100644 --- a/ddd/pom.xml +++ b/ddd/pom.xml @@ -1,6 +1,12 @@ 4.0.0 + com.baeldung.ddd + ddd + 0.0.1-SNAPSHOT + ddd + jar + DDD series examples org.springframework.boot @@ -9,18 +15,6 @@ - com.baeldung.ddd - ddd - 0.0.1-SNAPSHOT - jar - ddd - DDD series examples - - - 1.0.1 - 2.22.0 - - org.springframework.boot @@ -88,4 +82,10 @@ test + + + 1.0.1 + 2.22.0 + + \ No newline at end of file diff --git a/deeplearning4j/pom.xml b/deeplearning4j/pom.xml index 38be189bd0..181dbc871c 100644 --- a/deeplearning4j/pom.xml +++ b/deeplearning4j/pom.xml @@ -3,9 +3,9 @@ 4.0.0 com.baeldung.deeplearning4j deeplearning4j - jar 1.0-SNAPSHOT deeplearning4j + jar com.baeldung diff --git a/disruptor/pom.xml b/disruptor/pom.xml index c26dcc0cd4..296704f546 100644 --- a/disruptor/pom.xml +++ b/disruptor/pom.xml @@ -4,8 +4,8 @@ com.baeldung disruptor 0.1.0-SNAPSHOT - jar disruptor + jar com.baeldung diff --git a/flyway-cdi-extension/pom.xml b/flyway-cdi-extension/pom.xml index dbb32f1e5a..f49a51ea4b 100644 --- a/flyway-cdi-extension/pom.xml +++ b/flyway-cdi-extension/pom.xml @@ -8,44 +8,49 @@ 1.0-SNAPSHOT flyway-cdi-extension - - 1.8 - 1.8 - - javax.enterprise cdi-api - 2.0.SP1 + ${cdi-api.version} org.jboss.weld.se weld-se-core - 3.0.5.Final + ${weld-se-core.version} runtime org.flywaydb flyway-core - 5.1.4 + ${flyway-core.version} org.apache.tomcat tomcat-jdbc - 8.5.33 + ${tomcat-jdbc.version} javax.annotation javax.annotation-api - 1.3.2 + ${javax.annotation-api.version} com.h2database h2 - 1.4.197 + ${h2.version} runtime + + 1.8 + 1.8 + 2.0.SP1 + 3.0.5.Final + 5.1.4 + 8.5.33 + 1.3.2 + 1.4.197 + diff --git a/geotools/pom.xml b/geotools/pom.xml index 3ac8a63564..f2a9a77d2a 100644 --- a/geotools/pom.xml +++ b/geotools/pom.xml @@ -4,8 +4,8 @@ 4.0.0 geotools 0.0.1-SNAPSHOT - jar geotools + jar http://maven.apache.org diff --git a/google-cloud/pom.xml b/google-cloud/pom.xml index 85f47cc2f5..e39e186f05 100644 --- a/google-cloud/pom.xml +++ b/google-cloud/pom.xml @@ -4,9 +4,9 @@ 4.0.0 google-cloud 0.1-SNAPSHOT - jar google-cloud Google Cloud Tutorials + jar com.baeldung diff --git a/google-web-toolkit/pom.xml b/google-web-toolkit/pom.xml index db9ce2eac0..f4c6a0ab39 100644 --- a/google-web-toolkit/pom.xml +++ b/google-web-toolkit/pom.xml @@ -7,9 +7,9 @@ 4.0.0 com.baeldung google-web-toolkit - war 1.0-SNAPSHOT google-web-toolkit + war com.baeldung @@ -23,7 +23,7 @@ com.google.gwt gwt - 2.8.2 + ${gwt.version} pom import @@ -49,7 +49,7 @@ junit junit - 4.11 + ${junit.version} test @@ -120,6 +120,8 @@ UTF-8 UTF-8 + 4.11 + 2.8.2 diff --git a/grpc/pom.xml b/grpc/pom.xml index 725bec3e70..ab550c31d7 100644 --- a/grpc/pom.xml +++ b/grpc/pom.xml @@ -3,8 +3,8 @@ 4.0.0 grpc 0.0.1-SNAPSHOT - jar grpc + jar com.baeldung diff --git a/guice/pom.xml b/guice/pom.xml index f3e7873245..8ed2b557dc 100644 --- a/guice/pom.xml +++ b/guice/pom.xml @@ -5,8 +5,8 @@ com.baeldung.examples.guice guice 1.0-SNAPSHOT - jar guice + jar com.baeldung @@ -26,4 +26,4 @@ 4.1.0 - + \ No newline at end of file diff --git a/guice/src/main/java/com/baeldung/examples/common/Account.java b/guice/src/main/java/com/baeldung/examples/common/Account.java new file mode 100644 index 0000000000..fd2df005ac --- /dev/null +++ b/guice/src/main/java/com/baeldung/examples/common/Account.java @@ -0,0 +1,24 @@ +package com.baeldung.examples.common; + +public class Account { + + private String accountNumber; + private String type; + + public String getAccountNumber() { + return accountNumber; + } + + public void setAccountNumber(String accountNumber) { + this.accountNumber = accountNumber; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + +} diff --git a/guice/src/main/java/com/baeldung/examples/common/AccountService.java b/guice/src/main/java/com/baeldung/examples/common/AccountService.java new file mode 100644 index 0000000000..97a64e3c6e --- /dev/null +++ b/guice/src/main/java/com/baeldung/examples/common/AccountService.java @@ -0,0 +1,5 @@ +package com.baeldung.examples.common; + +public interface AccountService { + +} diff --git a/guice/src/main/java/com/baeldung/examples/common/AccountServiceImpl.java b/guice/src/main/java/com/baeldung/examples/common/AccountServiceImpl.java new file mode 100644 index 0000000000..18d6777c4a --- /dev/null +++ b/guice/src/main/java/com/baeldung/examples/common/AccountServiceImpl.java @@ -0,0 +1,5 @@ +package com.baeldung.examples.common; + +public class AccountServiceImpl implements AccountService { + +} diff --git a/guice/src/main/java/com/baeldung/examples/common/AudioBookService.java b/guice/src/main/java/com/baeldung/examples/common/AudioBookService.java new file mode 100644 index 0000000000..5d501f2051 --- /dev/null +++ b/guice/src/main/java/com/baeldung/examples/common/AudioBookService.java @@ -0,0 +1,5 @@ +package com.baeldung.examples.common; + +public interface AudioBookService { + +} diff --git a/guice/src/main/java/com/baeldung/examples/common/AudioBookServiceImpl.java b/guice/src/main/java/com/baeldung/examples/common/AudioBookServiceImpl.java new file mode 100644 index 0000000000..c64e953a58 --- /dev/null +++ b/guice/src/main/java/com/baeldung/examples/common/AudioBookServiceImpl.java @@ -0,0 +1,5 @@ +package com.baeldung.examples.common; + +public class AudioBookServiceImpl implements AudioBookService { + +} diff --git a/guice/src/main/java/com/baeldung/examples/common/AuthorService.java b/guice/src/main/java/com/baeldung/examples/common/AuthorService.java new file mode 100644 index 0000000000..9be148b8c3 --- /dev/null +++ b/guice/src/main/java/com/baeldung/examples/common/AuthorService.java @@ -0,0 +1,5 @@ +package com.baeldung.examples.common; + +public interface AuthorService { + +} diff --git a/guice/src/main/java/com/baeldung/examples/common/AuthorServiceImpl.java b/guice/src/main/java/com/baeldung/examples/common/AuthorServiceImpl.java new file mode 100644 index 0000000000..bac532e469 --- /dev/null +++ b/guice/src/main/java/com/baeldung/examples/common/AuthorServiceImpl.java @@ -0,0 +1,5 @@ +package com.baeldung.examples.common; + +public class AuthorServiceImpl implements AuthorService { + +} diff --git a/guice/src/main/java/com/baeldung/examples/common/BookService.java b/guice/src/main/java/com/baeldung/examples/common/BookService.java new file mode 100644 index 0000000000..56339c1398 --- /dev/null +++ b/guice/src/main/java/com/baeldung/examples/common/BookService.java @@ -0,0 +1,5 @@ +package com.baeldung.examples.common; + +public interface BookService { + +} diff --git a/guice/src/main/java/com/baeldung/examples/common/BookServiceImpl.java b/guice/src/main/java/com/baeldung/examples/common/BookServiceImpl.java new file mode 100644 index 0000000000..aee0d22e51 --- /dev/null +++ b/guice/src/main/java/com/baeldung/examples/common/BookServiceImpl.java @@ -0,0 +1,7 @@ +package com.baeldung.examples.common; + +public class BookServiceImpl implements BookService { + + private AuthorService authorService; + +} diff --git a/guice/src/main/java/com/baeldung/examples/common/PersonDao.java b/guice/src/main/java/com/baeldung/examples/common/PersonDao.java new file mode 100644 index 0000000000..980fee0252 --- /dev/null +++ b/guice/src/main/java/com/baeldung/examples/common/PersonDao.java @@ -0,0 +1,5 @@ +package com.baeldung.examples.common; + +public interface PersonDao { + +} diff --git a/guice/src/main/java/com/baeldung/examples/common/PersonDaoImpl.java b/guice/src/main/java/com/baeldung/examples/common/PersonDaoImpl.java new file mode 100644 index 0000000000..ecbf198cc0 --- /dev/null +++ b/guice/src/main/java/com/baeldung/examples/common/PersonDaoImpl.java @@ -0,0 +1,5 @@ +package com.baeldung.examples.common; + +public class PersonDaoImpl implements PersonDao { + +} \ No newline at end of file diff --git a/guice/src/main/java/com/baeldung/examples/guice/Foo.java b/guice/src/main/java/com/baeldung/examples/guice/Foo.java new file mode 100644 index 0000000000..fca32b165b --- /dev/null +++ b/guice/src/main/java/com/baeldung/examples/guice/Foo.java @@ -0,0 +1,4 @@ +package com.baeldung.examples.guice; + +public class Foo { +} diff --git a/guice/src/main/java/com/baeldung/examples/guice/FooProcessor.java b/guice/src/main/java/com/baeldung/examples/guice/FooProcessor.java new file mode 100644 index 0000000000..929013cd2b --- /dev/null +++ b/guice/src/main/java/com/baeldung/examples/guice/FooProcessor.java @@ -0,0 +1,9 @@ +package com.baeldung.examples.guice; + +import com.google.inject.Inject; + +public class FooProcessor { + + @Inject + private Foo foo; +} \ No newline at end of file diff --git a/guice/src/main/java/com/baeldung/examples/guice/GuicePersonService.java b/guice/src/main/java/com/baeldung/examples/guice/GuicePersonService.java new file mode 100644 index 0000000000..ce12e3e528 --- /dev/null +++ b/guice/src/main/java/com/baeldung/examples/guice/GuicePersonService.java @@ -0,0 +1,19 @@ +package com.baeldung.examples.guice; + +import com.baeldung.examples.common.PersonDao; +import com.google.inject.Inject; + +public class GuicePersonService { + + @Inject + private PersonDao personDao; + + public PersonDao getPersonDao() { + return personDao; + } + + public void setPersonDao(PersonDao personDao) { + this.personDao = personDao; + } + +} diff --git a/guice/src/main/java/com/baeldung/examples/guice/GuiceUserService.java b/guice/src/main/java/com/baeldung/examples/guice/GuiceUserService.java new file mode 100644 index 0000000000..0e58d0bacf --- /dev/null +++ b/guice/src/main/java/com/baeldung/examples/guice/GuiceUserService.java @@ -0,0 +1,19 @@ +package com.baeldung.examples.guice; + +import com.baeldung.examples.common.AccountService; +import com.google.inject.Inject; + +public class GuiceUserService { + + @Inject + private AccountService accountService; + + public AccountService getAccountService() { + return accountService; + } + + public void setAccountService(AccountService accountService) { + this.accountService = accountService; + } + +} diff --git a/guice/src/main/java/com/baeldung/examples/guice/Person.java b/guice/src/main/java/com/baeldung/examples/guice/Person.java new file mode 100644 index 0000000000..d54b5110eb --- /dev/null +++ b/guice/src/main/java/com/baeldung/examples/guice/Person.java @@ -0,0 +1,24 @@ +package com.baeldung.examples.guice; + +public class Person { + 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/guice/src/main/java/com/baeldung/examples/guice/modules/GuiceModule.java b/guice/src/main/java/com/baeldung/examples/guice/modules/GuiceModule.java new file mode 100644 index 0000000000..fbcd36b56a --- /dev/null +++ b/guice/src/main/java/com/baeldung/examples/guice/modules/GuiceModule.java @@ -0,0 +1,50 @@ +package com.baeldung.examples.guice.modules; + +import com.baeldung.examples.common.AccountService; +import com.baeldung.examples.common.AccountServiceImpl; +import com.baeldung.examples.common.BookService; +import com.baeldung.examples.common.BookServiceImpl; +import com.baeldung.examples.common.PersonDao; +import com.baeldung.examples.common.PersonDaoImpl; +import com.baeldung.examples.guice.Foo; +import com.baeldung.examples.guice.Person; +import com.google.inject.AbstractModule; +import com.google.inject.Provider; +import com.google.inject.Provides; + +public class GuiceModule extends AbstractModule { + + @Override + protected void configure() { + try { + bind(AccountService.class).to(AccountServiceImpl.class); + bind(Person.class).toConstructor(Person.class.getConstructor()); + // bind(Person.class).toProvider(new Provider() { + // public Person get() { + // Person p = new Person(); + // return p; + // } + // }); + bind(Foo.class).toProvider(new Provider() { + public Foo get() { + return new Foo(); + } + }); + bind(PersonDao.class).to(PersonDaoImpl.class); + + } catch (NoSuchMethodException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + } + + @Provides + public BookService bookServiceGenerator() { + return new BookServiceImpl(); + } + +} diff --git a/guice/src/test/java/com/baeldung/examples/GuiceUnitTest.java b/guice/src/test/java/com/baeldung/examples/GuiceUnitTest.java new file mode 100644 index 0000000000..dd2a89e101 --- /dev/null +++ b/guice/src/test/java/com/baeldung/examples/GuiceUnitTest.java @@ -0,0 +1,61 @@ +package com.baeldung.examples; + +import static org.junit.Assert.assertNotNull; + +import org.junit.Test; + +import com.baeldung.examples.common.BookService; +import com.baeldung.examples.guice.FooProcessor; +import com.baeldung.examples.guice.GuicePersonService; +import com.baeldung.examples.guice.GuiceUserService; +import com.baeldung.examples.guice.Person; +import com.baeldung.examples.guice.modules.GuiceModule; +import com.google.inject.Guice; +import com.google.inject.Injector; + +public class GuiceUnitTest { + + @Test + public void givenAccountServiceInjectedInGuiceUserService_WhenGetAccountServiceInvoked_ThenReturnValueIsNotNull() { + Injector injector = Guice.createInjector(new GuiceModule()); + GuiceUserService guiceUserService = injector.getInstance(GuiceUserService.class); + assertNotNull(guiceUserService.getAccountService()); + } + + @Test + public void givenBookServiceIsRegisteredInModule_WhenBookServiceIsInjected_ThenReturnValueIsNotNull() { + Injector injector = Guice.createInjector(new GuiceModule()); + BookService bookService = injector.getInstance(BookService.class); + assertNotNull(bookService); + } + + @Test + public void givenMultipleBindingsForPerson_WhenPersonIsInjected_ThenTestFailsByProvisionException() { + Injector injector = Guice.createInjector(new GuiceModule()); + Person person = injector.getInstance(Person.class); + assertNotNull(person); + } + + @Test + public void givenFooInjectedToFooProcessorAsOptionalDependency_WhenFooProcessorIsRetrievedFromContext_ThenCreationExceptionIsNotThrown() { + Injector injector = Guice.createInjector(new GuiceModule()); + FooProcessor fooProcessor = injector.getInstance(FooProcessor.class); + assertNotNull(fooProcessor); + } + + @Test + public void givenGuicePersonServiceConstructorAnnotatedByInject_WhenGuicePersonServiceIsInjected_ThenInstanceWillBeCreatedFromTheConstructor() { + Injector injector = Guice.createInjector(new GuiceModule()); + GuicePersonService personService = injector.getInstance(GuicePersonService.class); + assertNotNull(personService); + } + + @Test + public void givenPersonDaoInjectedToGuicePersonServiceBySetterInjection_WhenGuicePersonServiceIsInjected_ThenPersonDaoInitializedByTheSetter() { + Injector injector = Guice.createInjector(new GuiceModule()); + GuicePersonService personService = injector.getInstance(GuicePersonService.class); + assertNotNull(personService); + assertNotNull(personService.getPersonDao()); + } + +} diff --git a/jackson/README.md b/jackson/README.md index 04e88d0ea1..e201a06727 100644 --- a/jackson/README.md +++ b/jackson/README.md @@ -37,3 +37,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Serialize Only Fields that meet a Custom Criteria with Jackson](http://www.baeldung.com/jackson-serialize-field-custom-criteria) - [Mapping Nested Values with Jackson](http://www.baeldung.com/jackson-nested-values) - [Convert XML to JSON Using Jackson](https://www.baeldung.com/jackson-convert-xml-json) +- [Deserialize Immutable Objects with Jackson](https://www.baeldung.com/jackson-deserialize-immutable-objects) diff --git a/java-collections-conversions/pom.xml b/java-collections-conversions/pom.xml index 9b54652001..ee7221b25e 100644 --- a/java-collections-conversions/pom.xml +++ b/java-collections-conversions/pom.xml @@ -3,8 +3,8 @@ 4.0.0 java-collections-conversions 0.1.0-SNAPSHOT - jar java-collections-conversions + jar com.baeldung diff --git a/java-collections-maps/README.md b/java-collections-maps/README.md index b4ab270448..5d65e961de 100644 --- a/java-collections-maps/README.md +++ b/java-collections-maps/README.md @@ -19,3 +19,4 @@ - [How to Check If a Key Exists in a Map](https://www.baeldung.com/java-map-key-exists) - [Comparing Two HashMaps in Java](https://www.baeldung.com/java-compare-hashmaps) - [Immutable Map Implementations in Java](https://www.baeldung.com/java-immutable-maps) +- [Map to String Conversion in Java](https://www.baeldung.com/java-map-to-string-conversion) diff --git a/java-collections-maps/pom.xml b/java-collections-maps/pom.xml index 0803866c51..b5eba31437 100644 --- a/java-collections-maps/pom.xml +++ b/java-collections-maps/pom.xml @@ -3,8 +3,8 @@ 4.0.0 java-collections-maps 0.1.0-SNAPSHOT - jar java-collections-maps + jar com.baeldung @@ -39,7 +39,7 @@ one.util streamex - 0.6.5 + ${streamex.version} @@ -50,5 +50,6 @@ 1.7.0 3.6.1 7.1.0 + 0.6.5 diff --git a/java-collections-maps/src/test/java/com/baeldung/java/map/MultiValuedMapUnitTest.java b/java-collections-maps/src/test/java/com/baeldung/java/map/MultiValuedMapUnitTest.java index 67e4a5b0a0..b02b67f685 100644 --- a/java-collections-maps/src/test/java/com/baeldung/java/map/MultiValuedMapUnitTest.java +++ b/java-collections-maps/src/test/java/com/baeldung/java/map/MultiValuedMapUnitTest.java @@ -22,139 +22,157 @@ public class MultiValuedMapUnitTest { public void givenMultiValuesMap_whenPuttingMultipleValuesUsingPutMethod_thenReturningAllValues() { MultiValuedMap map = new ArrayListValuedHashMap<>(); - map.put("key", "value1"); - map.put("key", "value2"); - map.put("key", "value2"); + map.put("fruits", "apple"); + map.put("fruits", "orange"); - assertThat((Collection) map.get("key")).containsExactly("value1", "value2", "value2"); + assertThat((Collection) map.get("fruits")).containsExactly("apple", "orange"); + } @Test public void givenMultiValuesMap_whenPuttingMultipleValuesUsingPutAllMethod_thenReturningAllValues() { MultiValuedMap map = new ArrayListValuedHashMap<>(); + + map.putAll("vehicles", Arrays.asList("car", "bike")); - map.putAll("key", Arrays.asList("value1", "value2", "value2")); - - assertThat((Collection) map.get("key")).containsExactly("value1", "value2", "value2"); + assertThat((Collection) map.get("vehicles")).containsExactly("car", "bike"); + } @Test public void givenMultiValuesMap_whenGettingValueUsingGetMethod_thenReturningValue() { MultiValuedMap map = new ArrayListValuedHashMap<>(); - map.put("key", "value"); + + map.put("fruits", "apple"); - assertThat((Collection) map.get("key")).containsExactly("value"); + assertThat((Collection) map.get("fruits")).containsExactly("apple"); } @Test public void givenMultiValuesMap_whenUsingEntriesMethod_thenReturningMappings() { MultiValuedMap map = new ArrayListValuedHashMap<>(); - map.put("key", "value1"); - map.put("key", "value2"); - + map.put("fruits", "apple"); + map.put("fruits", "orange"); + Collection> entries = (Collection>) map.entries(); for(Map.Entry entry : entries) { - assertThat(entry.getKey()).contains("key"); - assertTrue(entry.getValue().equals("value1") || entry.getValue().equals("value2") ); + assertThat(entry.getKey()).contains("fruits"); + assertTrue(entry.getValue().equals("apple") || entry.getValue().equals("orange") ); } } @Test public void givenMultiValuesMap_whenUsingKeysMethod_thenReturningAllKeys() { MultiValuedMap map = new ArrayListValuedHashMap<>(); - map.put("key", "value"); - map.put("key1", "value1"); - map.put("key2", "value2"); + + map.put("fruits", "apple"); + map.put("fruits", "orange"); + map.put("vehicles", "car"); + map.put("vehicles", "bike"); - assertThat(((Collection) map.keys())).contains("key", "key1", "key2"); + assertThat(((Collection) map.keys())).contains("fruits", "vehicles"); } @Test public void givenMultiValuesMap_whenUsingKeySetMethod_thenReturningAllKeys() { MultiValuedMap map = new ArrayListValuedHashMap<>(); - map.put("key", "value"); - map.put("key1", "value1"); - map.put("key2", "value2"); + + map.put("fruits", "apple"); + map.put("fruits", "orange"); + map.put("vehicles", "car"); + map.put("vehicles", "bike"); - assertThat((Collection) map.keySet()).contains("key", "key1", "key2"); + assertThat((Collection) map.keySet()).contains("fruits", "vehicles"); + } @Test public void givenMultiValuesMap_whenUsingValuesMethod_thenReturningAllValues() { MultiValuedMap map = new ArrayListValuedHashMap<>(); - map.put("key", "value"); - map.put("key1", "value1"); - map.put("key2", "value2"); + + map.put("fruits", "apple"); + map.put("fruits", "orange"); + map.put("vehicles", "car"); + map.put("vehicles", "bike"); - assertThat(((Collection) map.values())).contains("value", "value1", "value2"); + assertThat(((Collection) map.values())).contains("apple", "orange", "car", "bike"); } @Test public void givenMultiValuesMap_whenUsingRemoveMethod_thenReturningUpdatedMap() { MultiValuedMap map = new ArrayListValuedHashMap<>(); - map.put("key", "value"); - map.put("key1", "value1"); - map.put("key2", "value2"); - assertThat(((Collection) map.values())).contains("value", "value1", "value2"); + + map.put("fruits", "apple"); + map.put("fruits", "orange"); + map.put("vehicles", "car"); + map.put("vehicles", "bike"); + assertThat(((Collection) map.values())).contains("apple", "orange", "car", "bike"); - map.remove("key"); + map.remove("fruits"); - assertThat(((Collection) map.values())).contains("value1", "value2"); + assertThat(((Collection) map.values())).contains("car", "bike"); + } @Test public void givenMultiValuesMap_whenUsingRemoveMappingMethod_thenReturningUpdatedMapAfterMappingRemoved() { MultiValuedMap map = new ArrayListValuedHashMap<>(); - map.put("key", "value"); - map.put("key1", "value1"); - map.put("key2", "value2"); - assertThat(((Collection) map.values())).contains("value", "value1", "value2"); + + map.put("fruits", "apple"); + map.put("fruits", "orange"); + map.put("vehicles", "car"); + map.put("vehicles", "bike"); + assertThat(((Collection) map.values())).contains("apple", "orange", "car", "bike"); - map.removeMapping("key", "value"); + map.removeMapping("fruits", "apple"); - assertThat(((Collection) map.values())).contains("value1", "value2"); + assertThat(((Collection) map.values())).contains("orange", "car", "bike"); } @Test public void givenMultiValuesMap_whenUsingClearMethod_thenReturningEmptyMap() { MultiValuedMap map = new ArrayListValuedHashMap<>(); - map.put("key", "value"); - map.put("key1", "value1"); - map.put("key2", "value2"); - assertThat(((Collection) map.values())).contains("value", "value1", "value2"); + map.put("fruits", "apple"); + map.put("fruits", "orange"); + map.put("vehicles", "car"); + map.put("vehicles", "bike"); + assertThat(((Collection) map.values())).contains("apple", "orange", "car", "bike"); map.clear(); - + assertTrue(map.isEmpty()); } @Test public void givenMultiValuesMap_whenUsingContainsKeyMethod_thenReturningTrue() { MultiValuedMap map = new ArrayListValuedHashMap<>(); - map.put("key", "value"); - map.put("key1", "value1"); - map.put("key2", "value2"); + map.put("fruits", "apple"); + map.put("fruits", "orange"); + map.put("vehicles", "car"); + map.put("vehicles", "bike"); - assertTrue(map.containsKey("key")); + assertTrue(map.containsKey("fruits")); } @Test public void givenMultiValuesMap_whenUsingContainsValueMethod_thenReturningTrue() { MultiValuedMap map = new ArrayListValuedHashMap<>(); - map.put("key", "value"); - map.put("key1", "value1"); - map.put("key2", "value2"); + map.put("fruits", "apple"); + map.put("fruits", "orange"); + map.put("vehicles", "car"); + map.put("vehicles", "bike"); - assertTrue(map.containsValue("value")); + assertTrue(map.containsValue("orange")); } @Test public void givenMultiValuesMap_whenUsingIsEmptyMethod_thenReturningFalse() { MultiValuedMap map = new ArrayListValuedHashMap<>(); - map.put("key", "value"); - map.put("key1", "value1"); - map.put("key2", "value2"); + map.put("fruits", "apple"); + map.put("fruits", "orange"); + map.put("vehicles", "car"); + map.put("vehicles", "bike"); assertFalse(map.isEmpty()); } @@ -162,42 +180,42 @@ public class MultiValuedMapUnitTest { @Test public void givenMultiValuesMap_whenUsingSizeMethod_thenReturningElementCount() { MultiValuedMap map = new ArrayListValuedHashMap<>(); - map.put("key", "value"); - map.put("key1", "value1"); - map.put("key2", "value2"); + map.put("fruits", "apple"); + map.put("fruits", "orange"); + map.put("vehicles", "car"); + map.put("vehicles", "bike"); - assertEquals(3, map.size()); + assertEquals(4, map.size()); } @Test public void givenArrayListValuedHashMap_whenPuttingDoubleValues_thenReturningAllValues() { MultiValuedMap map = new ArrayListValuedHashMap<>(); + map.put("fruits", "apple"); + map.put("fruits", "orange"); + map.put("fruits", "orange"); - map.put("key", "value1"); - map.put("key", "value2"); - map.put("key", "value2"); - - assertThat((Collection) map.get("key")).containsExactly("value1", "value2", "value2"); + assertThat((Collection) map.get("fruits")).containsExactly("apple", "orange", "orange"); } @Test public void givenHashSetValuedHashMap_whenPuttingTwiceTheSame_thenReturningOneValue() { MultiValuedMap map = new HashSetValuedHashMap<>(); - - map.put("key1", "value1"); - map.put("key1", "value1"); - - assertThat((Collection) map.get("key1")).containsExactly("value1"); + map.put("fruits", "apple"); + map.put("fruits", "apple"); + + assertThat((Collection) map.get("fruits")).containsExactly("apple"); } @Test(expected = UnsupportedOperationException.class) public void givenUnmodifiableMultiValuedMap_whenInserting_thenThrowingException() { MultiValuedMap map = new ArrayListValuedHashMap<>(); - map.put("key", "value1"); - map.put("key", "value2"); + map.put("fruits", "apple"); + map.put("fruits", "orange"); MultiValuedMap immutableMap = MultiMapUtils.unmodifiableMultiValuedMap(map); - immutableMap.put("key", "value3"); + immutableMap.put("fruits", "banana"); + } diff --git a/java-dates/README.md b/java-dates/README.md index ac3166d938..8171e5def9 100644 --- a/java-dates/README.md +++ b/java-dates/README.md @@ -27,4 +27,5 @@ - [Convert Between java.time.Instant and java.sql.Timestamp](https://www.baeldung.com/java-time-instant-to-java-sql-timestamp) - [Convert between String and Timestamp](https://www.baeldung.com/java-string-to-timestamp) - [A Guide to SimpleDateFormat](https://www.baeldung.com/java-simple-date-format) -- [ZoneOffset in Java](https://www.baeldung.com/java-zone-offset) \ No newline at end of file +- [ZoneOffset in Java](https://www.baeldung.com/java-zone-offset) +- [Differences Between ZonedDateTime and OffsetDateTime](https://www.baeldung.com/java-zoneddatetime-offsetdatetime) diff --git a/java-dates/pom.xml b/java-dates/pom.xml index 2618fad1d4..8dd5ad675e 100644 --- a/java-dates/pom.xml +++ b/java-dates/pom.xml @@ -4,8 +4,8 @@ com.baeldung java-dates 0.1.0-SNAPSHOT - jar java-dates + jar com.baeldung diff --git a/java-numbers/pom.xml b/java-numbers/pom.xml index 0f5140ea5e..eb75f85bf0 100644 --- a/java-numbers/pom.xml +++ b/java-numbers/pom.xml @@ -4,8 +4,8 @@ 4.0.0 java-numbers 0.1.0-SNAPSHOT - jar java-numbers + jar com.baeldung @@ -13,6 +13,7 @@ 0.0.1-SNAPSHOT ../parent-java + log4j diff --git a/java-streams/README.md b/java-streams/README.md index 33ca2619a8..15ea1c742a 100644 --- a/java-streams/README.md +++ b/java-streams/README.md @@ -15,3 +15,5 @@ - [Stream Ordering in Java](https://www.baeldung.com/java-stream-ordering) - [Introduction to Protonpack](https://www.baeldung.com/java-protonpack) - [Java Stream Filter with Lambda Expression](https://www.baeldung.com/java-stream-filter-lambda) +- [Counting Matches on a Stream Filter](https://www.baeldung.com/java-stream-filter-count) +- [Java 8 Streams peek() API](https://www.baeldung.com/java-streams-peek-api) diff --git a/java-streams/pom.xml b/java-streams/pom.xml index 2b52ebb4b3..0de1a424d6 100644 --- a/java-streams/pom.xml +++ b/java-streams/pom.xml @@ -3,8 +3,8 @@ 4.0.0 java-streams 0.1.0-SNAPSHOT - jar java-streams + jar com.baeldung @@ -94,10 +94,10 @@ org.apache.maven.plugins maven-compiler-plugin - 3.1 + ${maven-compiler-plugin.version} - 1.8 - 1.8 + ${maven.compiler.source} + ${maven.compiler.target} -parameters @@ -117,5 +117,8 @@ 3.11.1 1.8.9 + 3.1 + 1.8 + 1.8 diff --git a/java-streams/src/test/java/com/baeldung/stream/StreamMapUnitTest.java b/java-streams/src/test/java/com/baeldung/stream/StreamMapUnitTest.java new file mode 100644 index 0000000000..5cb2a274d1 --- /dev/null +++ b/java-streams/src/test/java/com/baeldung/stream/StreamMapUnitTest.java @@ -0,0 +1,83 @@ +package com.baeldung.stream; + +import org.junit.Before; +import org.junit.Test; + +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +public class StreamMapUnitTest { + + private Map books; + + @Before + public void setup() { + books = new HashMap<>(); + books.put("978-0201633610", "Design patterns : elements of reusable object-oriented software"); + books.put("978-1617291999", "Java 8 in Action: Lambdas, Streams, and functional-style programming"); + books.put("978-0134685991", "Effective Java"); + } + + + @Test + public void whenOptionalVersionCalledForExistingTitle_thenReturnOptionalWithISBN() { + Optional optionalIsbn = books.entrySet().stream() + .filter(e -> "Effective Java".equals(e.getValue())) + .map(Map.Entry::getKey).findFirst(); + + assertEquals("978-0134685991", optionalIsbn.get()); + } + + @Test + public void whenOptionalVersionCalledForNonExistingTitle_thenReturnEmptyOptionalForISBN() { + Optional optionalIsbn = books.entrySet().stream() + .filter(e -> "Non Existent Title".equals(e.getValue())) + .map(Map.Entry::getKey).findFirst(); + + assertEquals(false, optionalIsbn.isPresent()); + } + + @Test + public void whenMultipleResultsVersionCalledForExistingTitle_aCollectionWithMultipleValuesIsReturned() { + books.put("978-0321356680", "Effective Java: Second Edition"); + + List isbnCodes = books.entrySet().stream() + .filter(e -> e.getValue().startsWith("Effective Java")) + .map(Map.Entry::getKey) + .collect(Collectors.toList()); + + assertTrue(isbnCodes.contains("978-0321356680")); + assertTrue(isbnCodes.contains("978-0134685991")); + } + + @Test + public void whenMultipleResultsVersionCalledForNonExistingTitle_aCollectionWithNoValuesIsReturned() { + List isbnCodes = books.entrySet().stream() + .filter(e -> e.getValue().startsWith("Spring")) + .map(Map.Entry::getKey) + .collect(Collectors.toList()); + + assertTrue(isbnCodes.isEmpty()); + } + + @Test + public void whenKeysFollowingPatternReturnsAllValuesForThoseKeys() { + List titlesForKeyPattern = books.entrySet().stream() + .filter(e -> e.getKey().startsWith("978-0")) + .map(Map.Entry::getValue) + .collect(Collectors.toList()); + assertEquals(2, titlesForKeyPattern.size()); + assertTrue(titlesForKeyPattern.contains("Design patterns : elements of reusable object-oriented software")); + assertTrue(titlesForKeyPattern.contains("Effective Java")); + } + +} diff --git a/java-strings/README.md b/java-strings/README.md index b72a378d06..1ab5e098f6 100644 --- a/java-strings/README.md +++ b/java-strings/README.md @@ -50,3 +50,6 @@ - [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) +- [Java String Interview Questions and Answers](https://www.baeldung.com/java-string-interview-questions) +- [Check if a String is a Pangram in Java](https://www.baeldung.com/java-string-pangram) +- [Check If a String Contains Multiple Keywords](https://www.baeldung.com/string-contains-multiple-words) diff --git a/java-strings/pom.xml b/java-strings/pom.xml index 9f89ed6d76..4555b8ad4a 100755 --- a/java-strings/pom.xml +++ b/java-strings/pom.xml @@ -66,20 +66,20 @@ com.vdurmont emoji-java - 4.0.0 + ${emoji-java.version} org.junit.jupiter junit-jupiter-api - 5.3.1 + ${junit-jupiter-api.version} test org.hamcrest hamcrest-library - 1.3 + ${hamcrest-library.version} test @@ -87,18 +87,18 @@ org.passay passay - 1.3.1 + ${passay.version} org.apache.commons commons-text - 1.4 + ${commons-text.version} org.ahocorasick ahocorasick - 0.4.0 + ${ahocorasick.version} @@ -116,10 +116,10 @@ org.apache.maven.plugins maven-compiler-plugin - 3.1 + ${maven-compiler-plugin.version} - 1.8 - 1.8 + ${java.version} + ${java.version} -parameters @@ -135,6 +135,12 @@ 1.19 61.1 27.0.1-jre + 4.0.0 + 5.3.1 + 1.3 + 1.3.1 + 1.4 + 0.4.0 diff --git a/javax-servlets/pom.xml b/javax-servlets/pom.xml index f00dd0ebe8..bf85feb7ce 100644 --- a/javax-servlets/pom.xml +++ b/javax-servlets/pom.xml @@ -80,6 +80,7 @@ test + 4.5.3 5.0.5.RELEASE diff --git a/javaxval/pom.xml b/javaxval/pom.xml index 5f2690b5b4..f31aa0dc77 100644 --- a/javaxval/pom.xml +++ b/javaxval/pom.xml @@ -50,6 +50,7 @@ test + 2.0.1.Final 6.0.13.Final diff --git a/jee-7-security/pom.xml b/jee-7-security/pom.xml index 622ca19903..5b7bb07239 100644 --- a/jee-7-security/pom.xml +++ b/jee-7-security/pom.xml @@ -4,8 +4,8 @@ 4.0.0 jee-7-security 1.0-SNAPSHOT - war jee-7-security + war JavaEE 7 Spring Security Application @@ -56,7 +56,7 @@ javax.mvc javax.mvc-api - 1.0-pr + ${javax.mvc-api.version} @@ -97,6 +97,7 @@ 2.2 1.1.2 4.2.3.RELEASE + 1.0-pr diff --git a/jee-7/pom.xml b/jee-7/pom.xml index 97ed2cc51d..62ccb9d313 100644 --- a/jee-7/pom.xml +++ b/jee-7/pom.xml @@ -128,52 +128,52 @@ org.jboss.spec.javax.batch jboss-batch-api_1.0_spec - 1.0.0.Final + ${jboss-batch-api.version} org.jberet jberet-core - 1.0.2.Final + ${jberet.version} org.jberet jberet-support - 1.0.2.Final + ${jberet.version} org.jboss.spec.javax.transaction jboss-transaction-api_1.2_spec - 1.0.0.Final + ${jboss-transaction-api.version} org.jboss.marshalling jboss-marshalling - 1.4.2.Final + ${jboss-marshalling.version} org.jboss.weld weld-core - 2.1.1.Final + ${weld.version} org.jboss.weld.se weld-se - 2.1.1.Final + ${weld.version} org.jberet jberet-se - 1.0.2.Final + ${jberet.version} com.h2database h2 - 1.4.178 + ${h2.version} org.glassfish.jersey.containers jersey-container-jetty-servlet - 2.22.1 + ${jersey-container-jetty-servlet.version} @@ -533,6 +533,13 @@ 1.2 2.2 20160715 + 1.0.0.Final + 1.0.2.Final + 1.0.0.Final + 1.4.2.Final + 2.1.1.Final + 1.4.178 + 2.22.1 - \ No newline at end of file + diff --git a/jgroups/pom.xml b/jgroups/pom.xml index 34bdd59919..e95fe2be3c 100644 --- a/jgroups/pom.xml +++ b/jgroups/pom.xml @@ -4,9 +4,9 @@ 4.0.0 jgroups 0.1-SNAPSHOT - jar jgroups Reliable Messaging with JGroups Tutorial + jar com.baeldung diff --git a/jhipster/jhipster-microservice/car-app/pom.xml b/jhipster/jhipster-microservice/car-app/pom.xml index b05979b9c5..529877d448 100644 --- a/jhipster/jhipster-microservice/car-app/pom.xml +++ b/jhipster/jhipster-microservice/car-app/pom.xml @@ -1,6 +1,10 @@ 4.0.0 + com.car.app + car-app + car-app + war jhipster-microservice @@ -8,94 +12,10 @@ 1.0.0-SNAPSHOT - com.car.app - car-app - war - car-app - ${maven.version} - - -Djava.security.egd=file:/dev/./urandom -Xmx256m - 3.6.2 - 2.0.0 - 2.5 - 3.5 - 0.4.13 - 1.2 - 5.2.8.Final - 2.6.0 - 0.7.9 - 1.8 - 3.21.0-GA - 1.0.0 - 1.1.0 - 0.7.0 - 3.6 - 2.0.0 - 3.6.2 - 4.8 - jdt_apt - 1.1.0.Final - 2.10 - 1.4.1 - 3.0.1 - yyyyMMddHHmmss - 3.0.0 - 3.1.3 - v6.10.0 - - - - - ${project.build.directory}/test-results - 0.0.20 - false - 3.2.2 - 2.12.1 - 3.2 - - src/main/webapp/content/**/*.*, src/main/webapp/bower_components/**/*.*, src/main/webapp/i18n/*.js, target/www/**/*.* - - S3437,UndocumentedApi,BoldAndItalicTagsCheck - - - src/main/webapp/app/**/*.* - Web:BoldAndItalicTagsCheck - - src/main/java/**/* - squid:S3437 - - src/main/java/**/* - squid:UndocumentedApi - - ${project.testresult.directory}/coverage/jacoco/jacoco-it.exec - ${project.testresult.directory}/coverage/jacoco/jacoco.exec - jacoco - - ${project.testresult.directory}/karma - - ${project.testresult.directory}/coverage/report-lcov/lcov.info - - ${project.testresult.directory}/coverage/report-lcov/lcov.info - - ${project.basedir}/src/main/ - ${project.testresult.directory}/surefire-reports - ${project.basedir}/src/test/ - - 2.5.0 - - Camden.SR5 - 2.6.1 - 1.4.10.Final - 1.1.0.Final - v0.21.3 - - @@ -898,4 +818,84 @@ + + + -Djava.security.egd=file:/dev/./urandom -Xmx256m + 3.6.2 + 2.0.0 + 2.5 + 3.5 + 0.4.13 + 1.2 + 5.2.8.Final + 2.6.0 + 0.7.9 + 1.8 + 3.21.0-GA + 1.0.0 + 1.1.0 + 0.7.0 + 3.6 + 2.0.0 + 3.6.2 + 4.8 + jdt_apt + 1.1.0.Final + 2.10 + 1.4.1 + 3.0.1 + yyyyMMddHHmmss + 3.0.0 + 3.1.3 + v6.10.0 + + + + + ${project.build.directory}/test-results + 0.0.20 + false + 3.2.2 + 2.12.1 + 3.2 + + src/main/webapp/content/**/*.*, src/main/webapp/bower_components/**/*.*, src/main/webapp/i18n/*.js, target/www/**/*.* + + S3437,UndocumentedApi,BoldAndItalicTagsCheck + + + src/main/webapp/app/**/*.* + Web:BoldAndItalicTagsCheck + + src/main/java/**/* + squid:S3437 + + src/main/java/**/* + squid:UndocumentedApi + + ${project.testresult.directory}/coverage/jacoco/jacoco-it.exec + ${project.testresult.directory}/coverage/jacoco/jacoco.exec + jacoco + + ${project.testresult.directory}/karma + + ${project.testresult.directory}/coverage/report-lcov/lcov.info + + ${project.testresult.directory}/coverage/report-lcov/lcov.info + + ${project.basedir}/src/main/ + ${project.testresult.directory}/surefire-reports + ${project.basedir}/src/test/ + + 2.5.0 + + Camden.SR5 + 2.6.1 + 1.4.10.Final + 1.1.0.Final + v0.21.3 + + diff --git a/jhipster/jhipster-microservice/dealer-app/pom.xml b/jhipster/jhipster-microservice/dealer-app/pom.xml index 803a0f62e6..1eac8a930e 100644 --- a/jhipster/jhipster-microservice/dealer-app/pom.xml +++ b/jhipster/jhipster-microservice/dealer-app/pom.xml @@ -1,6 +1,10 @@ 4.0.0 + com.dealer.app + dealer-app + dealer-app + war jhipster-microservice @@ -8,93 +12,10 @@ 1.0.0-SNAPSHOT - com.dealer.app - dealer-app - war - dealer-app - ${maven.version} - - -Djava.security.egd=file:/dev/./urandom -Xmx256m - 3.6.2 - 2.0.0 - 2.5 - 3.5 - 0.4.13 - 1.2 - 5.2.8.Final - 2.6.0 - 0.7.9 - 3.21.0-GA - 1.0.0 - 1.1.0 - 0.7.0 - 3.6 - 2.0.0 - 3.6.2 - 4.8 - jdt_apt - 1.1.0.Final - 2.10 - 1.4.1 - 3.0.1 - yyyyMMddHHmmss - 3.0.0 - 3.1.3 - v6.10.0 - - - - - ${project.build.directory}/test-results - 0.0.20 - false - 3.2.2 - 2.12.1 - 3.2 - - src/main/webapp/content/**/*.*, src/main/webapp/bower_components/**/*.*, src/main/webapp/i18n/*.js, target/www/**/*.* - - S3437,UndocumentedApi,BoldAndItalicTagsCheck - - - src/main/webapp/app/**/*.* - Web:BoldAndItalicTagsCheck - - src/main/java/**/* - squid:S3437 - - src/main/java/**/* - squid:UndocumentedApi - - ${project.testresult.directory}/coverage/jacoco/jacoco-it.exec - ${project.testresult.directory}/coverage/jacoco/jacoco.exec - jacoco - - ${project.testresult.directory}/karma - - ${project.testresult.directory}/coverage/report-lcov/lcov.info - - ${project.testresult.directory}/coverage/report-lcov/lcov.info - - ${project.basedir}/src/main/ - ${project.testresult.directory}/surefire-reports - ${project.basedir}/src/test/ - - 2.5.0 - - Camden.SR5 - 2.6.1 - 1.4.10.Final - 1.1.0.Final - v0.21.3 - - @@ -892,5 +813,83 @@ + + + -Djava.security.egd=file:/dev/./urandom -Xmx256m + 3.6.2 + 2.0.0 + 2.5 + 3.5 + 0.4.13 + 1.2 + 5.2.8.Final + 2.6.0 + 0.7.9 + 3.21.0-GA + 1.0.0 + 1.1.0 + 0.7.0 + 3.6 + 2.0.0 + 3.6.2 + 4.8 + jdt_apt + 1.1.0.Final + 2.10 + 1.4.1 + 3.0.1 + yyyyMMddHHmmss + 3.0.0 + 3.1.3 + v6.10.0 + + + + + ${project.build.directory}/test-results + 0.0.20 + false + 3.2.2 + 2.12.1 + 3.2 + src/main/webapp/content/**/*.*, src/main/webapp/bower_components/**/*.*, src/main/webapp/i18n/*.js, target/www/**/*.* + + S3437,UndocumentedApi,BoldAndItalicTagsCheck + + + src/main/webapp/app/**/*.* + Web:BoldAndItalicTagsCheck + + src/main/java/**/* + squid:S3437 + + src/main/java/**/* + squid:UndocumentedApi + + ${project.testresult.directory}/coverage/jacoco/jacoco-it.exec + ${project.testresult.directory}/coverage/jacoco/jacoco.exec + jacoco + + ${project.testresult.directory}/karma + + ${project.testresult.directory}/coverage/report-lcov/lcov.info + + ${project.testresult.directory}/coverage/report-lcov/lcov.info + + ${project.basedir}/src/main/ + ${project.testresult.directory}/surefire-reports + ${project.basedir}/src/test/ + + 2.5.0 + + Camden.SR5 + 2.6.1 + 1.4.10.Final + 1.1.0.Final + v0.21.3 + + diff --git a/jhipster/jhipster-microservice/gateway-app/pom.xml b/jhipster/jhipster-microservice/gateway-app/pom.xml index ed0c929027..babc9e4f24 100644 --- a/jhipster/jhipster-microservice/gateway-app/pom.xml +++ b/jhipster/jhipster-microservice/gateway-app/pom.xml @@ -1,6 +1,10 @@ 4.0.0 + com.gateway + gateway-app + gateway-app + war jhipster-microservice @@ -8,97 +12,10 @@ 1.0.0-SNAPSHOT - com.gateway - gateway-app - war - gateway-app - ${maven.version} - - -Djava.security.egd=file:/dev/./urandom -Xmx256m - 3.6.2 - 2.0.0 - 3.6.0 - 1.10 - 2.5 - 3.5 - 0.4.13 - 1.3 - 1.2 - 5.2.8.Final - 2.6.0 - 0.7.9 - 3.21.0-GA - 1.0.0 - 1.1.0 - 0.7.0 - 3.6 - 2.0.0 - 3.6.2 - 4.8 - 1.3.0 - jdt_apt - 1.1.0.Final - 2.10 - 1.4.1 - 3.0.1 - yyyyMMddHHmmss - 3.0.0 - 3.1.3 - v6.10.0 - - - - - ${project.build.directory}/test-results - 0.0.20 - false - 3.2.2 - 2.12.1 - 3.2 - - src/main/webapp/content/**/*.*, src/main/webapp/bower_components/**/*.*, src/main/webapp/i18n/*.js, target/www/**/*.* - - S3437,UndocumentedApi,BoldAndItalicTagsCheck - - - src/main/webapp/app/**/*.* - Web:BoldAndItalicTagsCheck - - src/main/java/**/* - squid:S3437 - - src/main/java/**/* - squid:UndocumentedApi - - ${project.testresult.directory}/coverage/jacoco/jacoco-it.exec - ${project.testresult.directory}/coverage/jacoco/jacoco.exec - jacoco - - ${project.testresult.directory}/karma - - ${project.testresult.directory}/coverage/report-lcov/lcov.info - - ${project.testresult.directory}/coverage/report-lcov/lcov.info - - ${project.basedir}/src/main/ - ${project.testresult.directory}/surefire-reports - ${project.basedir}/src/test/ - - 2.5.0 - - Camden.SR5 - 2.6.1 - 1.4.10.Final - 1.1.0.Final - v0.21.3 - - @@ -1008,5 +925,87 @@ + + + -Djava.security.egd=file:/dev/./urandom -Xmx256m + 3.6.2 + 2.0.0 + 3.6.0 + 1.10 + 2.5 + 3.5 + 0.4.13 + 1.3 + 1.2 + 5.2.8.Final + 2.6.0 + 0.7.9 + 3.21.0-GA + 1.0.0 + 1.1.0 + 0.7.0 + 3.6 + 2.0.0 + 3.6.2 + 4.8 + 1.3.0 + jdt_apt + 1.1.0.Final + 2.10 + 1.4.1 + 3.0.1 + yyyyMMddHHmmss + 3.0.0 + 3.1.3 + v6.10.0 + + + + + ${project.build.directory}/test-results + 0.0.20 + false + 3.2.2 + 2.12.1 + 3.2 + + src/main/webapp/content/**/*.*, src/main/webapp/bower_components/**/*.*, src/main/webapp/i18n/*.js, target/www/**/*.* + + S3437,UndocumentedApi,BoldAndItalicTagsCheck + + + src/main/webapp/app/**/*.* + Web:BoldAndItalicTagsCheck + + src/main/java/**/* + squid:S3437 + + src/main/java/**/* + squid:UndocumentedApi + + ${project.testresult.directory}/coverage/jacoco/jacoco-it.exec + ${project.testresult.directory}/coverage/jacoco/jacoco.exec + jacoco + + ${project.testresult.directory}/karma + + ${project.testresult.directory}/coverage/report-lcov/lcov.info + + ${project.testresult.directory}/coverage/report-lcov/lcov.info + + ${project.basedir}/src/main/ + ${project.testresult.directory}/surefire-reports + ${project.basedir}/src/test/ + + 2.5.0 + + Camden.SR5 + 2.6.1 + 1.4.10.Final + 1.1.0.Final + v0.21.3 + diff --git a/jhipster/jhipster-uaa/gateway/pom.xml b/jhipster/jhipster-uaa/gateway/pom.xml index 52f84e4006..0f815bedad 100644 --- a/jhipster/jhipster-uaa/gateway/pom.xml +++ b/jhipster/jhipster-uaa/gateway/pom.xml @@ -1,12 +1,11 @@ 4.0.0 - com.baeldung.jhipster.gateway gateway 0.0.1-SNAPSHOT - war Gateway + war @@ -14,87 +13,6 @@ - - - 3.0.0 - 1.8 - 2.12.6 - v8.12.0 - 6.4.1 - UTF-8 - UTF-8 - ${project.build.directory}/test-results - yyyyMMddHHmmss - ${java.version} - ${java.version} - -Djava.security.egd=file:/dev/./urandom -Xmx256m - jdt_apt - false - - - - - - - 2.0.25 - - 2.0.5.RELEASE - - 5.2.17.Final - - 3.22.0-GA - - 3.5.5 - 3.6 - 2.0.1.Final - 1.2.0.Final - - - 3.1.0 - 3.8.0 - 2.10 - 3.0.0-M2 - 3.1.0 - 2.22.0 - 3.2.2 - 0.9.11 - 1.6 - 0.8.2 - 3.4.2 - 3.5.0.1254 - 2.2.5 - - - http://localhost:9001 - src/main/webapp/content/**/*.*, src/main/webapp/i18n/*.js, target/www/**/*.* - S3437,S4684,UndocumentedApi,BoldAndItalicTagsCheck - - src/main/webapp/app/**/*.* - Web:BoldAndItalicTagsCheck - - src/main/java/**/* - squid:S3437 - - src/main/java/**/* - squid:UndocumentedApi - - src/main/java/**/* - squid:S4684 - ${project.testresult.directory}/coverage/jacoco/jacoco.exec - jacoco - ${project.testresult.directory}/jest/TESTS-results-sonar.xml - ${project.testresult.directory}/lcov.info - ${project.basedir}/src/main/ - ${project.testresult.directory}/surefire-reports - ${project.basedir}/src/test/ - - - - @@ -1092,4 +1010,85 @@ + + + + 3.0.0 + 1.8 + 2.12.6 + v8.12.0 + 6.4.1 + UTF-8 + UTF-8 + ${project.build.directory}/test-results + yyyyMMddHHmmss + ${java.version} + ${java.version} + -Djava.security.egd=file:/dev/./urandom -Xmx256m + jdt_apt + false + + + + + + + 2.0.25 + + 2.0.5.RELEASE + + 5.2.17.Final + + 3.22.0-GA + + 3.5.5 + 3.6 + 2.0.1.Final + 1.2.0.Final + + + 3.1.0 + 3.8.0 + 2.10 + 3.0.0-M2 + 3.1.0 + 2.22.0 + 3.2.2 + 0.9.11 + 1.6 + 0.8.2 + 3.4.2 + 3.5.0.1254 + 2.2.5 + + + http://localhost:9001 + src/main/webapp/content/**/*.*, src/main/webapp/i18n/*.js, target/www/**/*.* + S3437,S4684,UndocumentedApi,BoldAndItalicTagsCheck + + src/main/webapp/app/**/*.* + Web:BoldAndItalicTagsCheck + + src/main/java/**/* + squid:S3437 + + src/main/java/**/* + squid:UndocumentedApi + + src/main/java/**/* + squid:S4684 + ${project.testresult.directory}/coverage/jacoco/jacoco.exec + jacoco + ${project.testresult.directory}/jest/TESTS-results-sonar.xml + ${project.testresult.directory}/lcov.info + ${project.basedir}/src/main/ + ${project.testresult.directory}/surefire-reports + ${project.basedir}/src/test/ + + + diff --git a/jhipster/jhipster-uaa/pom.xml b/jhipster/jhipster-uaa/pom.xml index e8ccaabfb0..88df59b735 100644 --- a/jhipster/jhipster-uaa/pom.xml +++ b/jhipster/jhipster-uaa/pom.xml @@ -4,8 +4,8 @@ 4.0.0 com.baeldung.jhipster jhipster-microservice-uaa - pom JHipster Microservice with UAA + pom jhipster diff --git a/jhipster/jhipster-uaa/quotes/pom.xml b/jhipster/jhipster-uaa/quotes/pom.xml index 9984f009ff..81ab23471f 100644 --- a/jhipster/jhipster-uaa/quotes/pom.xml +++ b/jhipster/jhipster-uaa/quotes/pom.xml @@ -1,12 +1,11 @@ 4.0.0 - com.baeldung.jhipster.quotes quotes 0.0.1-SNAPSHOT - war Quotes + war @@ -14,85 +13,6 @@ - - - 3.0.0 - 1.8 - 2.12.6 - v8.12.0 - 6.4.1 - UTF-8 - UTF-8 - ${project.build.directory}/test-results - yyyyMMddHHmmss - ${java.version} - ${java.version} - -Djava.security.egd=file:/dev/./urandom -Xmx256m - jdt_apt - false - - - - - - - 2.0.25 - - 2.0.5.RELEASE - - 5.2.17.Final - - 3.22.0-GA - - 3.5.5 - 3.6 - 2.0.1.Final - 1.2.0.Final - - - 3.1.0 - 3.8.0 - 2.10 - 3.0.0-M2 - 3.1.0 - 2.22.0 - 3.2.2 - 0.9.11 - 0.8.2 - 3.4.2 - 3.5.0.1254 - 2.2.5 - - - http://localhost:9001 - src/main/webapp/content/**/*.*, src/main/webapp/i18n/*.js, target/www/**/*.* - S3437,S4684,UndocumentedApi,BoldAndItalicTagsCheck - - src/main/webapp/app/**/*.* - Web:BoldAndItalicTagsCheck - - src/main/java/**/* - squid:S3437 - - src/main/java/**/* - squid:UndocumentedApi - - src/main/java/**/* - squid:S4684 - ${project.testresult.directory}/coverage/jacoco/jacoco.exec - jacoco - ${project.testresult.directory}/lcov.info - ${project.basedir}/src/main/ - ${project.testresult.directory}/surefire-reports - ${project.basedir}/src/test/ - - - - @@ -912,4 +832,83 @@ + + + + 3.0.0 + 1.8 + 2.12.6 + v8.12.0 + 6.4.1 + UTF-8 + UTF-8 + ${project.build.directory}/test-results + yyyyMMddHHmmss + ${java.version} + ${java.version} + -Djava.security.egd=file:/dev/./urandom -Xmx256m + jdt_apt + false + + + + + + + 2.0.25 + + 2.0.5.RELEASE + + 5.2.17.Final + + 3.22.0-GA + + 3.5.5 + 3.6 + 2.0.1.Final + 1.2.0.Final + + + 3.1.0 + 3.8.0 + 2.10 + 3.0.0-M2 + 3.1.0 + 2.22.0 + 3.2.2 + 0.9.11 + 0.8.2 + 3.4.2 + 3.5.0.1254 + 2.2.5 + + + http://localhost:9001 + src/main/webapp/content/**/*.*, src/main/webapp/i18n/*.js, target/www/**/*.* + S3437,S4684,UndocumentedApi,BoldAndItalicTagsCheck + + src/main/webapp/app/**/*.* + Web:BoldAndItalicTagsCheck + + src/main/java/**/* + squid:S3437 + + src/main/java/**/* + squid:UndocumentedApi + + src/main/java/**/* + squid:S4684 + ${project.testresult.directory}/coverage/jacoco/jacoco.exec + jacoco + ${project.testresult.directory}/lcov.info + ${project.basedir}/src/main/ + ${project.testresult.directory}/surefire-reports + ${project.basedir}/src/test/ + + + diff --git a/jhipster/jhipster-uaa/uaa/pom.xml b/jhipster/jhipster-uaa/uaa/pom.xml index 9c4783747a..2c4dd9d0f0 100644 --- a/jhipster/jhipster-uaa/uaa/pom.xml +++ b/jhipster/jhipster-uaa/uaa/pom.xml @@ -1,12 +1,11 @@ 4.0.0 - com.baeldung.jhipster.uaa uaa 0.0.1-SNAPSHOT - war Uaa + war @@ -14,85 +13,6 @@ - - - 3.0.0 - 1.8 - 2.12.6 - v8.12.0 - 6.4.1 - UTF-8 - UTF-8 - ${project.build.directory}/test-results - yyyyMMddHHmmss - ${java.version} - ${java.version} - -Djava.security.egd=file:/dev/./urandom -Xmx256m - jdt_apt - false - - - - - - - 2.0.25 - - 2.0.5.RELEASE - - 5.2.17.Final - - 3.22.0-GA - - 3.5.5 - 3.6 - 2.0.1.Final - 1.2.0.Final - - - 3.1.0 - 3.8.0 - 2.10 - 3.0.0-M2 - 3.1.0 - 2.22.0 - 3.2.2 - 0.9.11 - 0.8.2 - 3.4.2 - 3.5.0.1254 - 2.2.5 - - - http://localhost:9001 - src/main/webapp/content/**/*.*, src/main/webapp/i18n/*.js, target/www/**/*.* - S3437,S4684,UndocumentedApi,BoldAndItalicTagsCheck - - src/main/webapp/app/**/*.* - Web:BoldAndItalicTagsCheck - - src/main/java/**/* - squid:S3437 - - src/main/java/**/* - squid:UndocumentedApi - - src/main/java/**/* - squid:S4684 - ${project.testresult.directory}/coverage/jacoco/jacoco.exec - jacoco - ${project.testresult.directory}/lcov.info - ${project.basedir}/src/main/ - ${project.testresult.directory}/surefire-reports - ${project.basedir}/src/test/ - - - - @@ -912,4 +832,84 @@ + + + + 3.0.0 + 1.8 + 2.12.6 + v8.12.0 + 6.4.1 + UTF-8 + UTF-8 + ${project.build.directory}/test-results + yyyyMMddHHmmss + ${java.version} + ${java.version} + -Djava.security.egd=file:/dev/./urandom -Xmx256m + jdt_apt + false + + + + + + + 2.0.25 + + 2.0.5.RELEASE + + 5.2.17.Final + + 3.22.0-GA + + 3.5.5 + 3.6 + 2.0.1.Final + 1.2.0.Final + + + 3.1.0 + 3.8.0 + 2.10 + 3.0.0-M2 + 3.1.0 + 2.22.0 + 3.2.2 + 0.9.11 + 0.8.2 + 3.4.2 + 3.5.0.1254 + 2.2.5 + + + http://localhost:9001 + src/main/webapp/content/**/*.*, src/main/webapp/i18n/*.js, target/www/**/*.* + S3437,S4684,UndocumentedApi,BoldAndItalicTagsCheck + + src/main/webapp/app/**/*.* + Web:BoldAndItalicTagsCheck + + src/main/java/**/* + squid:S3437 + + src/main/java/**/* + squid:UndocumentedApi + + src/main/java/**/* + squid:S4684 + ${project.testresult.directory}/coverage/jacoco/jacoco.exec + jacoco + ${project.testresult.directory}/lcov.info + ${project.basedir}/src/main/ + ${project.testresult.directory}/surefire-reports + ${project.basedir}/src/test/ + + + + diff --git a/jhipster/pom.xml b/jhipster/pom.xml index 5132c6dc95..3fcc53b354 100644 --- a/jhipster/pom.xml +++ b/jhipster/pom.xml @@ -5,8 +5,8 @@ com.baeldung.jhipster jhipster 1.0.0-SNAPSHOT - pom JHipster + pom parent-boot-1 diff --git a/jib/pom.xml b/jib/pom.xml index ad4011c3c4..5c9f242a20 100644 --- a/jib/pom.xml +++ b/jib/pom.xml @@ -18,11 +18,7 @@ spring-boot-starter-web - - - 1.8 - - + @@ -32,7 +28,7 @@ com.google.cloud.tools jib-maven-plugin - 0.9.10 + ${jib-maven-plugin.version} registry.hub.docker.com/baeldungjib/jib-spring-boot-app @@ -42,4 +38,8 @@ + + 1.8 + 0.9.10 + diff --git a/jjwt/pom.xml b/jjwt/pom.xml index 6bf9f4426a..2d03543293 100644 --- a/jjwt/pom.xml +++ b/jjwt/pom.xml @@ -5,8 +5,8 @@ io.jsonwebtoken jjwt 0.0.1-SNAPSHOT - jar jjwt + jar Exercising the JJWT diff --git a/jmeter/pom.xml b/jmeter/pom.xml index 943b75e03b..514546987d 100644 --- a/jmeter/pom.xml +++ b/jmeter/pom.xml @@ -4,9 +4,9 @@ 4.0.0 jmeter 0.0.1-SNAPSHOT - jar jmeter Intro to Performance testing using JMeter + jar parent-boot-1 diff --git a/jmh/pom.xml b/jmh/pom.xml index 1e01809fe6..70a0a398d4 100644 --- a/jmh/pom.xml +++ b/jmh/pom.xml @@ -3,9 +3,9 @@ 4.0.0 com.baeldung jmh - jar 1.0-SNAPSHOT jmh + jar http://maven.apache.org diff --git a/jooby/src/test/java/com/baeldung/jooby/AppLiveTest.java b/jooby/src/test/java/com/baeldung/jooby/AppLiveTest.java new file mode 100644 index 0000000000..1bd12f8bb3 --- /dev/null +++ b/jooby/src/test/java/com/baeldung/jooby/AppLiveTest.java @@ -0,0 +1,21 @@ +package com.baeldung.jooby; + +import static io.restassured.RestAssured.get; +import static org.hamcrest.Matchers.equalTo; + +import org.jooby.test.JoobyRule; +import org.junit.ClassRule; +import org.junit.Test; + +public class AppLiveTest { + + @ClassRule + public static JoobyRule app = new JoobyRule(new App()); + + @Test + public void given_defaultUrl_expect_fixedString() { + get("/").then().assertThat().body(equalTo("Hello World!")).statusCode(200) + .contentType("text/html;charset=UTF-8"); + } + +} diff --git a/jooby/src/test/java/com/baeldung/jooby/AppUnitTest.java b/jooby/src/test/java/com/baeldung/jooby/AppUnitTest.java index ab7388f5f4..9bca30e2c1 100644 --- a/jooby/src/test/java/com/baeldung/jooby/AppUnitTest.java +++ b/jooby/src/test/java/com/baeldung/jooby/AppUnitTest.java @@ -1,25 +1,12 @@ package com.baeldung.jooby; -import static io.restassured.RestAssured.get; -import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertEquals; -import org.jooby.test.JoobyRule; import org.jooby.test.MockRouter; -import org.junit.ClassRule; import org.junit.Test; public class AppUnitTest { - @ClassRule - public static JoobyRule app = new JoobyRule(new App()); - - @Test - public void given_defaultUrl_expect_fixedString() { - get("/").then().assertThat().body(equalTo("Hello World!")).statusCode(200) - .contentType("text/html;charset=UTF-8"); - } - @Test public void given_defaultUrl_with_mockrouter_expect_fixedString() throws Throwable { String result = new MockRouter(new App()).get("/"); diff --git a/json/pom.xml b/json/pom.xml index fce2d26db5..23955e5a75 100644 --- a/json/pom.xml +++ b/json/pom.xml @@ -32,17 +32,17 @@ org.json json - 20171018 + ${json.version} com.google.code.gson gson - 2.8.5 + ${gson.version} com.fasterxml.jackson.core jackson-databind - 2.9.7 + ${jackson-databind.version} javax.json.bind @@ -52,14 +52,14 @@ junit junit - 4.12 + ${junit.version} test org.glassfish javax.json - 1.1.2 + ${javax.version} org.eclipse @@ -81,6 +81,11 @@ 1.0 4.1 1.0.1 + 20171018 + 2.8.5 + 2.9.7 + 4.12 + 1.1.2 diff --git a/jta/pom.xml b/jta/pom.xml index 4754c1872b..038f1dc8d1 100644 --- a/jta/pom.xml +++ b/jta/pom.xml @@ -7,7 +7,6 @@ 1.0-SNAPSHOT jta jar - JEE JTA demo @@ -17,12 +16,6 @@ - - UTF-8 - UTF-8 - 1.8 - - org.springframework.boot @@ -46,7 +39,7 @@ org.hsqldb hsqldb - 2.4.1 + ${hsqldb.version} @@ -86,4 +79,11 @@ + + + UTF-8 + UTF-8 + 1.8 + 2.4.1 + diff --git a/kotlin-libraries/README.md b/kotlin-libraries/README.md index 4110bfe12e..5e2526e64e 100644 --- a/kotlin-libraries/README.md +++ b/kotlin-libraries/README.md @@ -9,3 +9,4 @@ - [Working with Dates in Kotlin](https://www.baeldung.com/kotlin-dates) - [Introduction to Arrow in Kotlin](https://www.baeldung.com/kotlin-arrow) - [Kotlin with Ktor](https://www.baeldung.com/kotlin-ktor) +- [REST API With Kotlin and Kovert](https://www.baeldung.com/kotlin-kovert) diff --git a/libraries-security/pom.xml b/libraries-security/pom.xml index 3077abc29c..ba51227ce0 100644 --- a/libraries-security/pom.xml +++ b/libraries-security/pom.xml @@ -23,7 +23,7 @@ org.springframework.security.oauth spring-security-oauth2 - 2.3.3.RELEASE + ${spring-security-oauth2.version} @@ -41,21 +41,21 @@ org.passay passay - 1.3.1 + ${passay.version} org.cryptacular cryptacular - 1.2.2 + ${cryptacular.version} - 4.12 2.0.4.RELEASE 5.6.0 + 2.3.3.RELEASE + 1.3.1 + 1.2.2 - - diff --git a/libraries-server/README.md b/libraries-server/README.md index 28f963ade8..75c12fd61a 100644 --- a/libraries-server/README.md +++ b/libraries-server/README.md @@ -7,3 +7,4 @@ - [Creating and Configuring Jetty 9 Server in Java](http://www.baeldung.com/jetty-java-programmatic) - [Testing Netty with EmbeddedChannel](http://www.baeldung.com/testing-netty-embedded-channel) - [MQTT Client in Java](https://www.baeldung.com/java-mqtt-client) +- [Guide to XMPP Smack Client](https://www.baeldung.com/xmpp-smack-chat-client) diff --git a/libraries-server/pom.xml b/libraries-server/pom.xml index f60e664fa7..b30b6137a1 100644 --- a/libraries-server/pom.xml +++ b/libraries-server/pom.xml @@ -5,16 +5,17 @@ 0.0.1-SNAPSHOT libraries-server - + com.baeldung parent-modules 1.0.0-SNAPSHOT - + + org.eclipse.paho org.eclipse.paho.client.mqttv3 - 1.2.0 + ${eclipse.paho.client.mqttv3.version} @@ -107,6 +108,7 @@ 4.12 8.5.24 4.3.1 + 1.2.0 \ No newline at end of file diff --git a/libraries/README.md b/libraries/README.md index b247caedda..378317778e 100644 --- a/libraries/README.md +++ b/libraries/README.md @@ -64,7 +64,8 @@ - [Exactly Once Processing in Kafka](https://www.baeldung.com/kafka-exactly-once) - [An Introduction to SuanShu](https://www.baeldung.com/suanshu) - [Implementing a FTP-Client in Java](http://www.baeldung.com/java-ftp-client) -- [Introduction to Functional Java](https://www.baeldung.com/java-functional-library +- [Introduction to Functional Java](https://www.baeldung.com/java-functional-library) +- [Intro to Derive4J](https://www.baeldung.com/derive4j) The libraries module contains examples related to small libraries that are relatively easy to use and does not require any separate module of its own. diff --git a/logging-modules/logback/pom.xml b/logging-modules/logback/pom.xml index ef7adbc3ea..845424af0c 100644 --- a/logging-modules/logback/pom.xml +++ b/logging-modules/logback/pom.xml @@ -4,9 +4,9 @@ http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - logback logback 0.1-SNAPSHOT + logback com.baeldung diff --git a/lombok-custom/pom.xml b/lombok-custom/pom.xml index 41bd042a5e..f016405fd6 100644 --- a/lombok-custom/pom.xml +++ b/lombok-custom/pom.xml @@ -2,34 +2,35 @@ - - parent-modules - com.baeldung - 1.0.0-SNAPSHOT - 4.0.0 lombok-custom 0.1-SNAPSHOT + + parent-modules + com.baeldung + 1.0.0-SNAPSHOT + + org.projectlombok lombok - 1.14.8 + ${lombok.version} provided org.kohsuke.metainf-services metainf-services - 1.8 + ${metainf-services.version} org.eclipse.jdt core - 3.3.0-v_771 + ${eclipse.jdt.core.version} @@ -54,5 +55,12 @@ + + + 1.14.8 + 1.8 + 3.3.0-v_771 + - \ No newline at end of file + + diff --git a/lombok/src/main/java/com/baeldung/lombok/getter/GetterLazy.java b/lombok/src/main/java/com/baeldung/lombok/getter/GetterLazy.java new file mode 100644 index 0000000000..5ac82a74d8 --- /dev/null +++ b/lombok/src/main/java/com/baeldung/lombok/getter/GetterLazy.java @@ -0,0 +1,36 @@ +package com.baeldung.lombok.getter; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import lombok.Getter; + +public class GetterLazy { + + private static final String DELIMETER = ","; + + @Getter(lazy = true) + private final Map transactions = readTxnsFromFile(); + + private Map readTxnsFromFile() { + + final Map cache = new HashMap<>(); + List txnRows = readTxnListFromFile(); + + txnRows.forEach(s -> { + String[] txnIdValueTuple = s.split(DELIMETER); + cache.put(txnIdValueTuple[0], Long.parseLong(txnIdValueTuple[1])); + }); + + return cache; + } + + private List readTxnListFromFile() { + + // read large file + return Stream.of("file content here").collect(Collectors.toList()); + } +} diff --git a/maven-archetype/src/main/resources/archetype-resources/pom.xml b/maven-archetype/src/main/resources/archetype-resources/pom.xml index eb69f64626..a5c813652d 100644 --- a/maven-archetype/src/main/resources/archetype-resources/pom.xml +++ b/maven-archetype/src/main/resources/archetype-resources/pom.xml @@ -1,7 +1,6 @@ 4.0.0 - ${groupId} ${artifactId} ${version} diff --git a/maven-polyglot/maven-polyglot-json-extension/pom.xml b/maven-polyglot/maven-polyglot-json-extension/pom.xml index fe1e025d1f..5b18529ec5 100644 --- a/maven-polyglot/maven-polyglot-json-extension/pom.xml +++ b/maven-polyglot/maven-polyglot-json-extension/pom.xml @@ -7,11 +7,6 @@ maven-polyglot-json-extension 1.0-SNAPSHOT maven-polyglot-json-extension - - - 1.8 - 1.8 - @@ -43,5 +38,10 @@ + + + 1.8 + 1.8 + \ No newline at end of file diff --git a/maven/versions-maven-plugin/original/pom.xml b/maven/versions-maven-plugin/original/pom.xml index 295c77b860..7608e4d168 100644 --- a/maven/versions-maven-plugin/original/pom.xml +++ b/maven/versions-maven-plugin/original/pom.xml @@ -6,10 +6,6 @@ versions-maven-plugin-example 0.0.1-SNAPSHOT - - 1.15 - - @@ -73,4 +69,8 @@ + + 1.15 + + \ No newline at end of file diff --git a/metrics/pom.xml b/metrics/pom.xml index d7d7a8a911..014931a957 100644 --- a/metrics/pom.xml +++ b/metrics/pom.xml @@ -66,7 +66,7 @@ org.springframework.boot spring-boot-starter-web - 2.0.7.RELEASE + ${spring-boot-starter-web.version} @@ -89,7 +89,7 @@ org.assertj assertj-core - 3.11.1 + ${assertj-core.version} test @@ -102,6 +102,8 @@ 0.12.0.RELEASE 2.9.1 0.57.1 + 2.0.7.RELEASE + 3.11.1 diff --git a/micronaut/pom.xml b/micronaut/pom.xml index aa69c77f73..2a8d135483 100644 --- a/micronaut/pom.xml +++ b/micronaut/pom.xml @@ -4,12 +4,6 @@ micronaut 0.1 micronaut - - - com.baeldung.micronaut.helloworld.server.ServerApplication - 1.0.0.RC2 - 1.8 - @@ -133,4 +127,10 @@ + + + com.baeldung.micronaut.helloworld.server.ServerApplication + 1.0.0.RC2 + 1.8 + diff --git a/mustache/pom.xml b/mustache/pom.xml index 1b89997996..027d62ebc4 100644 --- a/mustache/pom.xml +++ b/mustache/pom.xml @@ -3,8 +3,8 @@ 4.0.0 mustache - jar mustache + jar parent-boot-2 diff --git a/osgi/osgi-intro-sample-activator/pom.xml b/osgi/osgi-intro-sample-activator/pom.xml index 77d7198698..95ac1fc0fb 100644 --- a/osgi/osgi-intro-sample-activator/pom.xml +++ b/osgi/osgi-intro-sample-activator/pom.xml @@ -2,9 +2,9 @@ 4.0.0 + osgi-intro-sample-activator bundle - osgi-intro-sample-activator diff --git a/parent-java/pom.xml b/parent-java/pom.xml index 8f603b2d09..cb3e205871 100644 --- a/parent-java/pom.xml +++ b/parent-java/pom.xml @@ -4,9 +4,9 @@ com.baeldung parent-java 0.0.1-SNAPSHOT - pom parent-java Parent for all java modules + pom com.baeldung diff --git a/parent-kotlin/pom.xml b/parent-kotlin/pom.xml index 73c98e1a80..7a3a8b10ca 100644 --- a/parent-kotlin/pom.xml +++ b/parent-kotlin/pom.xml @@ -3,8 +3,8 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 4.0.0 parent-kotlin - pom parent-kotlin + pom Parent for all kotlin modules diff --git a/parent-spring-4/pom.xml b/parent-spring-4/pom.xml index 9b3c42599b..6cbcf3000e 100644 --- a/parent-spring-4/pom.xml +++ b/parent-spring-4/pom.xml @@ -4,8 +4,8 @@ com.baeldung parent-spring-4 0.0.1-SNAPSHOT - pom parent-spring-4 + pom Parent for all spring 4 core modules diff --git a/parent-spring-5/pom.xml b/parent-spring-5/pom.xml index 51a2c1fd1f..650305b7e2 100644 --- a/parent-spring-5/pom.xml +++ b/parent-spring-5/pom.xml @@ -4,9 +4,9 @@ com.baeldung parent-spring-5 0.0.1-SNAPSHOT - pom parent-spring-5 Parent for all spring 5 core modules + pom com.baeldung diff --git a/patterns/pom.xml b/patterns/pom.xml index bc1f5173e2..3c3bb6d5ea 100644 --- a/patterns/pom.xml +++ b/patterns/pom.xml @@ -17,6 +17,7 @@ front-controller intercepting-filter design-patterns + solid diff --git a/patterns/principles/solid/README.md b/patterns/principles/solid/README.md new file mode 100644 index 0000000000..e2d72ecd28 --- /dev/null +++ b/patterns/principles/solid/README.md @@ -0,0 +1,5 @@ +### Relevant Articles: + +- [A Guide to Solid Principles](https://www.baeldung.com/solid-principles) + + diff --git a/patterns/principles/solid/src/main/java/com/baeldung/d/Keyboard.java b/patterns/principles/solid/src/main/java/com/baeldung/d/Keyboard.java deleted file mode 100644 index acb50cedb4..0000000000 --- a/patterns/principles/solid/src/main/java/com/baeldung/d/Keyboard.java +++ /dev/null @@ -1,4 +0,0 @@ -package com.baeldung.d; - -public class Keyboard { -} diff --git a/patterns/principles/solid/pom.xml b/patterns/solid/pom.xml similarity index 53% rename from patterns/principles/solid/pom.xml rename to patterns/solid/pom.xml index 825c7730a5..2837504197 100644 --- a/patterns/principles/solid/pom.xml +++ b/patterns/solid/pom.xml @@ -3,21 +3,15 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - com.baeldung - solid/artifactId> + solid 1.0-SNAPSHOT - - - - - junit - junit - 4.12 - test - - - + + com.baeldung + patterns + 1.0.0-SNAPSHOT + .. + diff --git a/patterns/solid/src/main/java/com/baeldung/d/Keyboard.java b/patterns/solid/src/main/java/com/baeldung/d/Keyboard.java new file mode 100644 index 0000000000..cc6fc47d65 --- /dev/null +++ b/patterns/solid/src/main/java/com/baeldung/d/Keyboard.java @@ -0,0 +1,4 @@ +package com.baeldung.d; + +public interface Keyboard { +} diff --git a/patterns/principles/solid/src/main/java/com/baeldung/d/Monitor.java b/patterns/solid/src/main/java/com/baeldung/d/Monitor.java similarity index 100% rename from patterns/principles/solid/src/main/java/com/baeldung/d/Monitor.java rename to patterns/solid/src/main/java/com/baeldung/d/Monitor.java diff --git a/patterns/solid/src/main/java/com/baeldung/d/StandardKeyboard.java b/patterns/solid/src/main/java/com/baeldung/d/StandardKeyboard.java new file mode 100644 index 0000000000..cb0e229943 --- /dev/null +++ b/patterns/solid/src/main/java/com/baeldung/d/StandardKeyboard.java @@ -0,0 +1,5 @@ +package com.baeldung.d; + +public class StandardKeyboard implements Keyboard { + +} diff --git a/patterns/principles/solid/src/main/java/com/baeldung/d/Windows98Machine.java b/patterns/solid/src/main/java/com/baeldung/d/Windows98Machine.java similarity index 66% rename from patterns/principles/solid/src/main/java/com/baeldung/d/Windows98Machine.java rename to patterns/solid/src/main/java/com/baeldung/d/Windows98Machine.java index a9f130aedb..4d6ead9aa2 100644 --- a/patterns/principles/solid/src/main/java/com/baeldung/d/Windows98Machine.java +++ b/patterns/solid/src/main/java/com/baeldung/d/Windows98Machine.java @@ -2,13 +2,13 @@ package com.baeldung.d; public class Windows98Machine { - private final Keyboard keyboard; + private final StandardKeyboard keyboard; private final Monitor monitor; public Windows98Machine() { monitor = new Monitor(); - keyboard = new Keyboard(); + keyboard = new StandardKeyboard(); } diff --git a/patterns/principles/solid/src/main/java/com/baeldung/d/Windows98MachineDI.java b/patterns/solid/src/main/java/com/baeldung/d/Windows98MachineDI.java similarity index 100% rename from patterns/principles/solid/src/main/java/com/baeldung/d/Windows98MachineDI.java rename to patterns/solid/src/main/java/com/baeldung/d/Windows98MachineDI.java diff --git a/patterns/principles/solid/src/main/java/com/baeldung/i/BearCarer.java b/patterns/solid/src/main/java/com/baeldung/i/BearCarer.java similarity index 100% rename from patterns/principles/solid/src/main/java/com/baeldung/i/BearCarer.java rename to patterns/solid/src/main/java/com/baeldung/i/BearCarer.java diff --git a/patterns/principles/solid/src/main/java/com/baeldung/i/BearCleaner.java b/patterns/solid/src/main/java/com/baeldung/i/BearCleaner.java similarity index 100% rename from patterns/principles/solid/src/main/java/com/baeldung/i/BearCleaner.java rename to patterns/solid/src/main/java/com/baeldung/i/BearCleaner.java diff --git a/patterns/principles/solid/src/main/java/com/baeldung/i/BearFeeder.java b/patterns/solid/src/main/java/com/baeldung/i/BearFeeder.java similarity index 100% rename from patterns/principles/solid/src/main/java/com/baeldung/i/BearFeeder.java rename to patterns/solid/src/main/java/com/baeldung/i/BearFeeder.java diff --git a/patterns/principles/solid/src/main/java/com/baeldung/i/BearKeeper.java b/patterns/solid/src/main/java/com/baeldung/i/BearKeeper.java similarity index 100% rename from patterns/principles/solid/src/main/java/com/baeldung/i/BearKeeper.java rename to patterns/solid/src/main/java/com/baeldung/i/BearKeeper.java diff --git a/patterns/principles/solid/src/main/java/com/baeldung/i/BearPetter.java b/patterns/solid/src/main/java/com/baeldung/i/BearPetter.java similarity index 100% rename from patterns/principles/solid/src/main/java/com/baeldung/i/BearPetter.java rename to patterns/solid/src/main/java/com/baeldung/i/BearPetter.java diff --git a/patterns/principles/solid/src/main/java/com/baeldung/i/CrazyPerson.java b/patterns/solid/src/main/java/com/baeldung/i/CrazyPerson.java similarity index 100% rename from patterns/principles/solid/src/main/java/com/baeldung/i/CrazyPerson.java rename to patterns/solid/src/main/java/com/baeldung/i/CrazyPerson.java diff --git a/patterns/principles/solid/src/main/java/com/baeldung/l/Car.java b/patterns/solid/src/main/java/com/baeldung/l/Car.java similarity index 100% rename from patterns/principles/solid/src/main/java/com/baeldung/l/Car.java rename to patterns/solid/src/main/java/com/baeldung/l/Car.java diff --git a/patterns/principles/solid/src/main/java/com/baeldung/l/ElectricCar.java b/patterns/solid/src/main/java/com/baeldung/l/ElectricCar.java similarity index 100% rename from patterns/principles/solid/src/main/java/com/baeldung/l/ElectricCar.java rename to patterns/solid/src/main/java/com/baeldung/l/ElectricCar.java diff --git a/patterns/principles/solid/src/main/java/com/baeldung/l/Engine.java b/patterns/solid/src/main/java/com/baeldung/l/Engine.java similarity index 100% rename from patterns/principles/solid/src/main/java/com/baeldung/l/Engine.java rename to patterns/solid/src/main/java/com/baeldung/l/Engine.java diff --git a/patterns/principles/solid/src/main/java/com/baeldung/l/MotorCar.java b/patterns/solid/src/main/java/com/baeldung/l/MotorCar.java similarity index 100% rename from patterns/principles/solid/src/main/java/com/baeldung/l/MotorCar.java rename to patterns/solid/src/main/java/com/baeldung/l/MotorCar.java diff --git a/patterns/principles/solid/src/main/java/com/baeldung/o/Guitar.java b/patterns/solid/src/main/java/com/baeldung/o/Guitar.java similarity index 100% rename from patterns/principles/solid/src/main/java/com/baeldung/o/Guitar.java rename to patterns/solid/src/main/java/com/baeldung/o/Guitar.java diff --git a/patterns/principles/solid/src/main/java/com/baeldung/o/SuperCoolGuitarWithFlames.java b/patterns/solid/src/main/java/com/baeldung/o/SuperCoolGuitarWithFlames.java similarity index 100% rename from patterns/principles/solid/src/main/java/com/baeldung/o/SuperCoolGuitarWithFlames.java rename to patterns/solid/src/main/java/com/baeldung/o/SuperCoolGuitarWithFlames.java diff --git a/patterns/principles/solid/src/main/java/com/baeldung/s/BadBook.java b/patterns/solid/src/main/java/com/baeldung/s/BadBook.java similarity index 100% rename from patterns/principles/solid/src/main/java/com/baeldung/s/BadBook.java rename to patterns/solid/src/main/java/com/baeldung/s/BadBook.java diff --git a/patterns/principles/solid/src/main/java/com/baeldung/s/BookPrinter.java b/patterns/solid/src/main/java/com/baeldung/s/BookPrinter.java similarity index 100% rename from patterns/principles/solid/src/main/java/com/baeldung/s/BookPrinter.java rename to patterns/solid/src/main/java/com/baeldung/s/BookPrinter.java diff --git a/patterns/principles/solid/src/main/java/com/baeldung/s/GoodBook.java b/patterns/solid/src/main/java/com/baeldung/s/GoodBook.java similarity index 100% rename from patterns/principles/solid/src/main/java/com/baeldung/s/GoodBook.java rename to patterns/solid/src/main/java/com/baeldung/s/GoodBook.java diff --git a/persistence-modules/activejdbc/pom.xml b/persistence-modules/activejdbc/pom.xml index 6a29f14ced..45a618b840 100644 --- a/persistence-modules/activejdbc/pom.xml +++ b/persistence-modules/activejdbc/pom.xml @@ -3,8 +3,8 @@ 4.0.0 activejdbc 1.0-SNAPSHOT - jar activejdbc + jar http://maven.apache.org diff --git a/persistence-modules/apache-cayenne/pom.xml b/persistence-modules/apache-cayenne/pom.xml index d0c6d1f2b2..776b2b5233 100644 --- a/persistence-modules/apache-cayenne/pom.xml +++ b/persistence-modules/apache-cayenne/pom.xml @@ -2,11 +2,10 @@ 4.0.0 - apache-cayenne 0.0.1-SNAPSHOT - jar apache-cayenne + jar Introduction to Apache Cayenne diff --git a/persistence-modules/core-java-persistence/pom.xml b/persistence-modules/core-java-persistence/pom.xml index f012d60ee6..a777eeb73f 100644 --- a/persistence-modules/core-java-persistence/pom.xml +++ b/persistence-modules/core-java-persistence/pom.xml @@ -4,14 +4,16 @@ com.baeldung.core-java-persistence core-java-persistence 0.1.0-SNAPSHOT - jar core-java-persistence + jar + com.baeldung parent-java 0.0.1-SNAPSHOT ../../parent-java + org.assertj @@ -50,6 +52,7 @@ ${springframework.boot.spring-boot-starter.version} + core-java-persistence @@ -58,7 +61,8 @@ true - + + 3.10.0 1.4.197 @@ -68,4 +72,5 @@ 1.5.8.RELEASE 4.3.4.RELEASE + \ No newline at end of file diff --git a/persistence-modules/deltaspike/pom.xml b/persistence-modules/deltaspike/pom.xml index b798d2f39e..9a4669102a 100644 --- a/persistence-modules/deltaspike/pom.xml +++ b/persistence-modules/deltaspike/pom.xml @@ -5,8 +5,8 @@ com.baeldung deltaspike 1.0 - war deltaspike + war A starter Java EE 7 webapp which uses DeltaSpike http://wildfly.org diff --git a/persistence-modules/flyway/pom.xml b/persistence-modules/flyway/pom.xml index 237b426521..eb827f5675 100644 --- a/persistence-modules/flyway/pom.xml +++ b/persistence-modules/flyway/pom.xml @@ -3,8 +3,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 flyway - jar flyway + jar Flyway Callbacks Demo diff --git a/persistence-modules/hibernate5/README.md b/persistence-modules/hibernate5/README.md index 03bdd9b759..a4e95a9062 100644 --- a/persistence-modules/hibernate5/README.md +++ b/persistence-modules/hibernate5/README.md @@ -29,3 +29,4 @@ - [Hibernate Named Query](https://www.baeldung.com/hibernate-named-query) - [Using c3p0 with Hibernate](https://www.baeldung.com/hibernate-c3p0) - [Persist a JSON Object Using Hibernate](https://www.baeldung.com/hibernate-persist-json-object) +- [Common Hibernate Exceptions](https://www.baeldung.com/hibernate-exceptions) diff --git a/persistence-modules/hibernate5/pom.xml b/persistence-modules/hibernate5/pom.xml index af94025a73..a09669c8b5 100644 --- a/persistence-modules/hibernate5/pom.xml +++ b/persistence-modules/hibernate5/pom.xml @@ -73,6 +73,16 @@ hibernate-jpamodelgen ${hibernate.version} + + org.openjdk.jmh + jmh-core + ${openjdk-jmh.version} + + + org.openjdk.jmh + jmh-generator-annprocess + ${openjdk-jmh.version} + @@ -92,6 +102,7 @@ 1.4.196 3.8.0 2.9.7 + 1.21 diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java index e0d1de591b..ea0af97d5a 100644 --- a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java @@ -68,6 +68,11 @@ public class HibernateUtil { return sessionFactory; } + public static SessionFactory getSessionFactoryByProperties(Properties properties) throws IOException { + ServiceRegistry serviceRegistry = configureServiceRegistry(properties); + return makeSessionFactory(serviceRegistry); + } + private static SessionFactory makeSessionFactory(ServiceRegistry serviceRegistry) { MetadataSources metadataSources = new MetadataSources(serviceRegistry); @@ -119,12 +124,15 @@ public class HibernateUtil { } private static ServiceRegistry configureServiceRegistry() throws IOException { - Properties properties = getProperties(); + return configureServiceRegistry(getProperties()); + } + + private static ServiceRegistry configureServiceRegistry(Properties properties) throws IOException { return new StandardServiceRegistryBuilder().applySettings(properties) .build(); } - private static Properties getProperties() throws IOException { + public static Properties getProperties() throws IOException { Properties properties = new Properties(); URL propertiesURL = Thread.currentThread() .getContextClassLoader() diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Student.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Student.java index a6dec4a30d..9b26c117eb 100644 --- a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Student.java +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Student.java @@ -9,15 +9,43 @@ import javax.persistence.Id; public class Student { @Id - @GeneratedValue (strategy = GenerationType.SEQUENCE) + @GeneratedValue(strategy = GenerationType.SEQUENCE) private long studentId; + private String name; + + private int age; + + public Student() { + } + + public Student(String name, int age) { + this.name = name; + this.age = age; + } + public long getStudentId() { return studentId; } - public void setStudent_id(long studentId) { + public void setStudentId(long studentId) { this.studentId = studentId; } - + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + } diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/aggregatefunctions/AggregateFunctionsIntegrationTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/aggregatefunctions/AggregateFunctionsIntegrationTest.java new file mode 100644 index 0000000000..0b2bdf7ead --- /dev/null +++ b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/aggregatefunctions/AggregateFunctionsIntegrationTest.java @@ -0,0 +1,87 @@ +package com.baeldung.hibernate.aggregatefunctions; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.IOException; + +import org.hibernate.HibernateException; +import org.hibernate.Session; +import org.hibernate.Transaction; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +import com.baeldung.hibernate.HibernateUtil; +import com.baeldung.hibernate.pojo.Student; + +public class AggregateFunctionsIntegrationTest { + + private static Session session; + private static Transaction transaction; + + @BeforeClass + public static final void setup() throws HibernateException, IOException { + session = HibernateUtil.getSessionFactory() + .openSession(); + transaction = session.beginTransaction(); + + Student jonas = new Student("Jonas", 22); + session.save(jonas); + + Student sally = new Student("Sally", 20); + session.save(sally); + + Student simon = new Student("Simon", 25); + session.save(simon); + + Student raven = new Student("Raven", 21); + session.save(raven); + + Student sam = new Student("Sam", 23); + session.save(sam); + + } + + @AfterClass + public static final void teardown() { + if (session != null) { + transaction.rollback(); + session.close(); + } + } + + @Test + public void whenMaxAge_ThenReturnValue() { + int maxAge = (int) session.createQuery("SELECT MAX(age) from Student") + .getSingleResult(); + assertThat(maxAge).isEqualTo(25); + } + + @Test + public void whenMinAge_ThenReturnValue() { + int minAge = (int) session.createQuery("SELECT MIN(age) from Student") + .getSingleResult(); + assertThat(minAge).isEqualTo(20); + } + + @Test + public void whenAverageAge_ThenReturnValue() { + Double avgAge = (Double) session.createQuery("SELECT AVG(age) from Student") + .getSingleResult(); + assertThat(avgAge).isEqualTo(22.2); + } + + @Test + public void whenCountAll_ThenReturnValue() { + Long totalStudents = (Long) session.createQuery("SELECT COUNT(*) from Student") + .getSingleResult(); + assertThat(totalStudents).isEqualTo(5); + } + + @Test + public void whenSumOfAllAges_ThenReturnValue() { + Long sumOfAllAges = (Long) session.createQuery("SELECT SUM(age) from Student") + .getSingleResult(); + assertThat(sumOfAllAges).isEqualTo(111); + } +} diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/queryplancache/QueryPlanCacheBenchmark.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/queryplancache/QueryPlanCacheBenchmark.java new file mode 100644 index 0000000000..13eae3d877 --- /dev/null +++ b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/queryplancache/QueryPlanCacheBenchmark.java @@ -0,0 +1,106 @@ +package com.baeldung.hibernate.queryplancache; + +import com.baeldung.hibernate.HibernateUtil; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.jpa.QueryHints; +import org.hibernate.query.Query; +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.BenchmarkMode; +import org.openjdk.jmh.annotations.Fork; +import org.openjdk.jmh.annotations.Measurement; +import org.openjdk.jmh.annotations.Mode; +import org.openjdk.jmh.annotations.OutputTimeUnit; +import org.openjdk.jmh.annotations.Param; +import org.openjdk.jmh.annotations.Scope; +import org.openjdk.jmh.annotations.Setup; +import org.openjdk.jmh.annotations.State; +import org.openjdk.jmh.annotations.TearDown; +import org.openjdk.jmh.annotations.Warmup; +import org.openjdk.jmh.infra.Blackhole; +import org.openjdk.jmh.runner.RunnerException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.util.Properties; +import java.util.concurrent.TimeUnit; + +public class QueryPlanCacheBenchmark { + + private static final Logger LOGGER = LoggerFactory.getLogger(QueryPlanCacheBenchmark.class); + + @State(Scope.Thread) + public static class QueryPlanCacheBenchMarkState { + @Param({"1", "2", "3"}) + public int planCacheSize; + + public Session session; + + @Setup + public void stateSetup() throws IOException { + LOGGER.info("State - Setup"); + session = initSession(planCacheSize); + LOGGER.info("State - Setup Complete"); + } + + private Session initSession(int planCacheSize) throws IOException { + Properties properties = HibernateUtil.getProperties(); + properties.put("hibernate.query.plan_cache_max_size", planCacheSize); + properties.put("hibernate.query.plan_parameter_metadata_max_size", planCacheSize); + SessionFactory sessionFactory = HibernateUtil.getSessionFactoryByProperties(properties); + return sessionFactory.openSession(); + } + + @TearDown + public void tearDownState() { + LOGGER.info("State - Teardown"); + SessionFactory sessionFactory = session.getSessionFactory(); + session.close(); + sessionFactory.close(); + LOGGER.info("State - Teardown complete"); + } + } + + @Benchmark + @BenchmarkMode(Mode.AverageTime) + @OutputTimeUnit(TimeUnit.MICROSECONDS) + @Fork(1) + @Warmup(iterations = 2) + @Measurement(iterations = 5) + public void givenQueryPlanCacheSize_thenCompileQueries(QueryPlanCacheBenchMarkState state, Blackhole blackhole) { + + Query query1 = findEmployeesByDepartmentNameQuery(state.session); + Query query2 = findEmployeesByDesignationQuery(state.session); + Query query3 = findDepartmentOfAnEmployeeQuery(state.session); + + blackhole.consume(query1); + blackhole.consume(query2); + blackhole.consume(query3); + + } + + private Query findEmployeesByDepartmentNameQuery(Session session) { + return session.createQuery("SELECT e FROM DeptEmployee e " + + "JOIN e.department WHERE e.department.name = :deptName") + .setMaxResults(30) + .setHint(QueryHints.HINT_FETCH_SIZE, 30); + } + + private Query findEmployeesByDesignationQuery(Session session) { + return session.createQuery("SELECT e FROM DeptEmployee e " + + "WHERE e.title = :designation") + .setHint(QueryHints.SPEC_HINT_TIMEOUT, 1000); + } + + private Query findDepartmentOfAnEmployeeQuery(Session session) { + return session.createQuery("SELECT e.department FROM DeptEmployee e " + + "JOIN e.department WHERE e.employeeNumber = :empId"); + + } + + public static void main(String... args) throws IOException, RunnerException { + //main-class to run the benchmark + org.openjdk.jmh.Main.main(args); + } +} diff --git a/persistence-modules/influxdb/pom.xml b/persistence-modules/influxdb/pom.xml index 5043d61897..8e1aeebe6d 100644 --- a/persistence-modules/influxdb/pom.xml +++ b/persistence-modules/influxdb/pom.xml @@ -4,8 +4,8 @@ 4.0.0 influxdb 0.1-SNAPSHOT - jar influxdb + jar InfluxDB SDK Tutorial diff --git a/persistence-modules/java-jpa/README.md b/persistence-modules/java-jpa/README.md index 2eea5e60b4..2c26581bab 100644 --- a/persistence-modules/java-jpa/README.md +++ b/persistence-modules/java-jpa/README.md @@ -4,3 +4,5 @@ - [A Guide to Stored Procedures with JPA](http://www.baeldung.com/jpa-stored-procedures) - [Fixing the JPA error “java.lang.String cannot be cast to Ljava.lang.String;”](https://www.baeldung.com/jpa-error-java-lang-string-cannot-be-cast) - [JPA Entity Graph](https://www.baeldung.com/jpa-entity-graph) +- [JPA 2.2 Support for Java 8 Date/Time Types](https://www.baeldung.com/jpa-java-time) +- [Converting Between LocalDate and SQL Date](https://www.baeldung.com/java-convert-localdate-sql-date) diff --git a/persistence-modules/jnosql/jnosql-artemis/pom.xml b/persistence-modules/jnosql/jnosql-artemis/pom.xml index 8a978fb179..a07f26c6ee 100644 --- a/persistence-modules/jnosql/jnosql-artemis/pom.xml +++ b/persistence-modules/jnosql/jnosql-artemis/pom.xml @@ -12,11 +12,30 @@ jnosql 1.0-SNAPSHOT - - - 2.4.2 - false - + + + + javax + javaee-web-api + 8.0 + provided + + + org.jnosql.artemis + artemis-configuration + ${jnosql.version} + + + org.jnosql.artemis + artemis-document + ${jnosql.version} + + + org.jnosql.diana + mongodb-driver + ${jnosql.version} + + ${project.artifactId} @@ -58,31 +77,9 @@ - - - - javax - javaee-web-api - 8.0 - provided - - - - org.jnosql.artemis - artemis-configuration - ${jnosql.version} - - - org.jnosql.artemis - artemis-document - ${jnosql.version} - - - org.jnosql.diana - mongodb-driver - ${jnosql.version} - - - + + 2.4.2 + false + diff --git a/persistence-modules/jnosql/jnosql-diana/pom.xml b/persistence-modules/jnosql/jnosql-diana/pom.xml index 126f0314d9..b52c808cf5 100644 --- a/persistence-modules/jnosql/jnosql-diana/pom.xml +++ b/persistence-modules/jnosql/jnosql-diana/pom.xml @@ -12,45 +12,6 @@ 1.0-SNAPSHOT - - - - org.codehaus.mojo - exec-maven-plugin - 1.6.0 - - - document - - java - - - com.baeldung.jnosql.diana.document.DocumentApp - - - - column - - java - - - com.baeldung.jnosql.diana.column.ColumnFamilyApp - - - - key - - java - - - com.baeldung.jnosql.diana.key.KeyValueApp - - - - - - - @@ -90,4 +51,43 @@ + + + + org.codehaus.mojo + exec-maven-plugin + 1.6.0 + + + document + + java + + + com.baeldung.jnosql.diana.document.DocumentApp + + + + column + + java + + + com.baeldung.jnosql.diana.column.ColumnFamilyApp + + + + key + + java + + + com.baeldung.jnosql.diana.key.KeyValueApp + + + + + + + \ No newline at end of file diff --git a/persistence-modules/jnosql/pom.xml b/persistence-modules/jnosql/pom.xml index 5fb29a3b9c..513a447b91 100644 --- a/persistence-modules/jnosql/pom.xml +++ b/persistence-modules/jnosql/pom.xml @@ -9,15 +9,14 @@ jnosql pom - - 1.8 - 1.8 - 0.0.5 - - jnosql-diana jnosql-artemis + + 1.8 + 1.8 + 0.0.5 + diff --git a/persistence-modules/querydsl/pom.xml b/persistence-modules/querydsl/pom.xml index d3bf1b1fb7..4d4347e909 100644 --- a/persistence-modules/querydsl/pom.xml +++ b/persistence-modules/querydsl/pom.xml @@ -5,8 +5,8 @@ com.baeldung querydsl 0.1-SNAPSHOT - jar querydsl + jar http://maven.apache.org diff --git a/persistence-modules/solr/pom.xml b/persistence-modules/solr/pom.xml index 49f2f85856..1c14c06315 100644 --- a/persistence-modules/solr/pom.xml +++ b/persistence-modules/solr/pom.xml @@ -4,8 +4,8 @@ com.baeldung solr 0.0.1-SNAPSHOT - jar solr + jar com.baeldung diff --git a/persistence-modules/spring-boot-h2/spring-boot-h2-database/pom.xml b/persistence-modules/spring-boot-h2/spring-boot-h2-database/pom.xml index 6ebc75de8d..a181360e2b 100644 --- a/persistence-modules/spring-boot-h2/spring-boot-h2-database/pom.xml +++ b/persistence-modules/spring-boot-h2/spring-boot-h2-database/pom.xml @@ -8,7 +8,6 @@ 0.0.1-SNAPSHOT spring-boot-h2-database jar - Demo Spring Boot applications that starts H2 in memory database @@ -18,20 +17,11 @@ - - UTF-8 - UTF-8 - 1.8 - - com.baeldung.h2db.demo.server.SpringBootApp - - org.springframework.boot spring-boot-starter-data-jpa - com.h2database h2 @@ -51,4 +41,13 @@ + + + UTF-8 + UTF-8 + 1.8 + + com.baeldung.h2db.demo.server.SpringBootApp + + diff --git a/persistence-modules/spring-boot-persistence-mongodb/pom.xml b/persistence-modules/spring-boot-persistence-mongodb/pom.xml index fc267eedf6..86b93c7826 100644 --- a/persistence-modules/spring-boot-persistence-mongodb/pom.xml +++ b/persistence-modules/spring-boot-persistence-mongodb/pom.xml @@ -3,6 +3,10 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 + spring-boot-persistence-mongodb + spring-boot-persistence-mongodb + war + This is simple boot application for Spring boot persistence mongodb test parent-boot-2 @@ -11,11 +15,6 @@ ../../parent-boot-2 - spring-boot-persistence-mongodb - war - spring-boot-persistence-mongodb - This is simple boot application for Spring boot persistence mongodb test - org.springframework.boot diff --git a/persistence-modules/spring-boot-persistence/README.MD b/persistence-modules/spring-boot-persistence/README.MD index cab6be1ec8..6fe5e6f05f 100644 --- a/persistence-modules/spring-boot-persistence/README.MD +++ b/persistence-modules/spring-boot-persistence/README.MD @@ -6,4 +6,4 @@ - [Configuring a Tomcat Connection Pool in Spring Boot](https://www.baeldung.com/spring-boot-tomcat-connection-pool) - [Hibernate Field Naming with Spring Boot](https://www.baeldung.com/hibernate-field-naming-spring-boot) - [Integrating Spring Boot with HSQLDB](https://www.baeldung.com/spring-boot-hsqldb) - +- [Configuring a DataSource Programmatically in Spring Boot](https://www.baeldung.com/spring-boot-configure-data-source-programmatic) diff --git a/persistence-modules/spring-data-cassandra-reactive/pom.xml b/persistence-modules/spring-data-cassandra-reactive/pom.xml index 5303f9a53a..d2bc574ee9 100644 --- a/persistence-modules/spring-data-cassandra-reactive/pom.xml +++ b/persistence-modules/spring-data-cassandra-reactive/pom.xml @@ -3,13 +3,11 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - com.baeldung spring-data-cassandra-reactive 0.0.1-SNAPSHOT - jar - spring-data-cassandra-reactive + jar Spring Data Cassandra reactive @@ -19,13 +17,6 @@ ../../parent-boot-2 - - UTF-8 - UTF-8 - - 1.8 - - org.springframework.data @@ -57,5 +48,11 @@ + + UTF-8 + UTF-8 + + 1.8 + diff --git a/persistence-modules/spring-data-cassandra/pom.xml b/persistence-modules/spring-data-cassandra/pom.xml index 11953a734b..4f323a72d8 100644 --- a/persistence-modules/spring-data-cassandra/pom.xml +++ b/persistence-modules/spring-data-cassandra/pom.xml @@ -4,8 +4,8 @@ com.baeldung spring-data-cassandra 0.0.1-SNAPSHOT - jar spring-data-cassandra + jar com.baeldung diff --git a/persistence-modules/spring-data-elasticsearch/pom.xml b/persistence-modules/spring-data-elasticsearch/pom.xml index ee9e71a1cb..9495d56798 100644 --- a/persistence-modules/spring-data-elasticsearch/pom.xml +++ b/persistence-modules/spring-data-elasticsearch/pom.xml @@ -4,8 +4,8 @@ com.baeldung spring-data-elasticsearch 0.0.1-SNAPSHOT - jar spring-data-elasticsearch + jar com.baeldung diff --git a/persistence-modules/spring-data-jpa/README.md b/persistence-modules/spring-data-jpa/README.md index 976a692699..739031ff5e 100644 --- a/persistence-modules/spring-data-jpa/README.md +++ b/persistence-modules/spring-data-jpa/README.md @@ -19,6 +19,7 @@ - [Sorting Query Results with Spring Data](https://www.baeldung.com/spring-data-sorting) - [INSERT Statement in JPA](https://www.baeldung.com/jpa-insert) - [Pagination and Sorting using Spring Data JPA](https://www.baeldung.com/spring-data-jpa-pagination-sorting) +- [Spring Data JPA Query by Example](https://www.baeldung.com/spring-data-query-by-example) ### Eclipse Config After importing the project into Eclipse, you may see the following error: diff --git a/persistence-modules/spring-data-jpa/pom.xml b/persistence-modules/spring-data-jpa/pom.xml index 786e587734..401f4877ac 100644 --- a/persistence-modules/spring-data-jpa/pom.xml +++ b/persistence-modules/spring-data-jpa/pom.xml @@ -27,11 +27,27 @@ org.hibernate hibernate-envers + com.h2database h2 + + + org.testcontainers + postgresql + 1.10.6 + test + + + + org.postgresql + postgresql + 42.2.5 + + + org.springframework.security spring-security-test diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/config/PersistenceConfiguration.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/config/PersistenceConfiguration.java index 2bdd4e5451..891624443b 100644 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/config/PersistenceConfiguration.java +++ b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/config/PersistenceConfiguration.java @@ -1,14 +1,11 @@ package com.baeldung.config; -import java.util.Properties; - -import javax.sql.DataSource; - +import com.baeldung.dao.repositories.impl.ExtendedRepositoryImpl; +import com.baeldung.services.IBarService; +import com.baeldung.services.impl.BarSpringDataJpaService; +import com.google.common.base.Preconditions; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.PropertySource; +import org.springframework.context.annotation.*; import org.springframework.core.env.Environment; import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor; import org.springframework.data.jpa.repository.config.EnableJpaAuditing; @@ -21,10 +18,8 @@ import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; -import com.baeldung.dao.repositories.impl.ExtendedRepositoryImpl; -import com.baeldung.services.IBarService; -import com.baeldung.services.impl.BarSpringDataJpaService; -import com.google.common.base.Preconditions; +import javax.sql.DataSource; +import java.util.Properties; @Configuration @ComponentScan({ "com.baeldung.dao", "com.baeldung.services" }) @@ -32,6 +27,7 @@ import com.google.common.base.Preconditions; @EnableJpaRepositories(basePackages = { "com.baeldung.dao" }, repositoryBaseClass = ExtendedRepositoryImpl.class) @EnableJpaAuditing @PropertySource("classpath:persistence.properties") +@Profile("!tc") public class PersistenceConfiguration { @Autowired diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/config/PersistenceProductConfiguration.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/config/PersistenceProductConfiguration.java index 207fba9bc5..ecaee82ae5 100644 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/config/PersistenceProductConfiguration.java +++ b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/config/PersistenceProductConfiguration.java @@ -4,6 +4,7 @@ import com.google.common.base.Preconditions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; @@ -19,6 +20,7 @@ import java.util.HashMap; @Configuration @PropertySource({"classpath:persistence-multiple-db.properties"}) @EnableJpaRepositories(basePackages = "com.baeldung.dao.repositories.product", entityManagerFactoryRef = "productEntityManager", transactionManagerRef = "productTransactionManager") +@Profile("!tc") public class PersistenceProductConfiguration { @Autowired private Environment env; diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/config/PersistenceUserConfiguration.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/config/PersistenceUserConfiguration.java index dd32477755..6893d889e6 100644 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/config/PersistenceUserConfiguration.java +++ b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/config/PersistenceUserConfiguration.java @@ -2,10 +2,7 @@ package com.baeldung.config; import com.google.common.base.Preconditions; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Primary; -import org.springframework.context.annotation.PropertySource; +import org.springframework.context.annotation.*; import org.springframework.core.env.Environment; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.jdbc.datasource.DriverManagerDataSource; @@ -20,6 +17,7 @@ import java.util.HashMap; @Configuration @PropertySource({"classpath:persistence-multiple-db.properties"}) @EnableJpaRepositories(basePackages = "com.baeldung.dao.repositories.user", entityManagerFactoryRef = "userEntityManager", transactionManagerRef = "userTransactionManager") +@Profile("!tc") public class PersistenceUserConfiguration { @Autowired private Environment env; 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 ad3b207fc6..9e3d0de1ec 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,7 +1,6 @@ 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; @@ -25,13 +24,13 @@ public interface UserRepository extends JpaRepository , UserRepos @Query("SELECT u FROM User u WHERE u.status = 1") Collection findAllActiveUsers(); - @Query(value = "SELECT * FROM USERS.USERS u WHERE u.status = 1", nativeQuery = true) + @Query(value = "SELECT * FROM Users u WHERE u.status = 1", nativeQuery = true) Collection findAllActiveUsersNative(); @Query("SELECT u FROM User u WHERE u.status = ?1") User findUserByStatus(Integer status); - @Query(value = "SELECT * FROM USERS.Users u WHERE u.status = ?1", nativeQuery = true) + @Query(value = "SELECT * FROM Users u WHERE u.status = ?1", nativeQuery = true) User findUserByStatusNative(Integer status); @Query("SELECT u FROM User u WHERE u.status = ?1 and u.name = ?2") @@ -40,7 +39,7 @@ public interface UserRepository extends JpaRepository , UserRepos @Query("SELECT u FROM User u WHERE u.status = :status and u.name = :name") User findUserByStatusAndNameNamedParams(@Param("status") Integer status, @Param("name") String name); - @Query(value = "SELECT * FROM USERS.Users u WHERE u.status = :status AND u.name = :name", nativeQuery = true) + @Query(value = "SELECT * FROM Users u WHERE u.status = :status AND u.name = :name", nativeQuery = true) User findUserByStatusAndNameNamedParamsNative(@Param("status") Integer status, @Param("name") String name); @Query("SELECT u FROM User u WHERE u.status = :status and u.name = :name") @@ -52,7 +51,7 @@ public interface UserRepository extends JpaRepository , UserRepos @Query("SELECT u FROM User u WHERE u.name like :name%") User findUserByNameLikeNamedParam(@Param("name") String name); - @Query(value = "SELECT * FROM USERS.users u WHERE u.name LIKE ?1%", nativeQuery = true) + @Query(value = "SELECT * FROM users u WHERE u.name LIKE ?1%", nativeQuery = true) User findUserByNameLikeNative(String name); @Query(value = "SELECT u FROM User u") @@ -61,7 +60,7 @@ public interface UserRepository extends JpaRepository , UserRepos @Query(value = "SELECT u FROM User u ORDER BY id") Page findAllUsersWithPagination(Pageable pageable); - @Query(value = "SELECT * FROM USERS.Users ORDER BY id", countQuery = "SELECT count(*) FROM USERS.Users", nativeQuery = true) + @Query(value = "SELECT * FROM Users ORDER BY id", countQuery = "SELECT count(*) FROM Users", nativeQuery = true) Page findAllUsersWithPaginationNative(Pageable pageable); @Modifying @@ -69,9 +68,16 @@ public interface UserRepository extends JpaRepository , UserRepos int updateUserSetStatusForName(@Param("status") Integer status, @Param("name") String name); @Modifying - @Query(value = "UPDATE USERS.Users u SET u.status = ? WHERE u.name = ?", nativeQuery = true) + @Query(value = "UPDATE Users u SET u.status = ? WHERE u.name = ?", nativeQuery = true) int updateUserSetStatusForNameNative(Integer status, String name); + @Modifying + @Query(value = "UPDATE Users u SET status = ? WHERE u.name = ?", nativeQuery = true) + int updateUserSetStatusForNameNativePostgres(Integer status, String name); + + @Query(value = "SELECT u FROM User u WHERE u.name IN :names") + List findUserByNameList(@Param("names") Collection names); + void deleteAllByCreationDateAfter(LocalDate date); @Modifying(clearAutomatically = true, flushAutomatically = true) @@ -83,7 +89,7 @@ public interface UserRepository extends JpaRepository , UserRepos int deleteDeactivatedUsers(); @Modifying(clearAutomatically = true, flushAutomatically = true) - @Query(value = "alter table USERS.USERS add column deleted int(1) not null default 0", nativeQuery = true) + @Query(value = "alter table Users add column deleted int(1) not null default 0", nativeQuery = true) void addDeletedColumn(); } diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/domain/user/Possession.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/domain/user/Possession.java index 614e13df36..b1427c0270 100644 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/domain/user/Possession.java +++ b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/domain/user/Possession.java @@ -1,13 +1,9 @@ package com.baeldung.domain.user; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Table; +import javax.persistence.*; @Entity -@Table(schema = "users") +@Table public class Possession { @Id diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/domain/user/User.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/domain/user/User.java index 49e36505e4..7109271eeb 100644 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/domain/user/User.java +++ b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/domain/user/User.java @@ -6,7 +6,7 @@ import java.util.List; import java.util.Objects; @Entity -@Table(name = "users", schema = "users") +@Table(name = "users") public class User { @Id diff --git a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/UserRepositoryCommon.java b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/UserRepositoryCommon.java new file mode 100644 index 0000000000..a69b5474bf --- /dev/null +++ b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/UserRepositoryCommon.java @@ -0,0 +1,528 @@ +package com.baeldung.dao.repositories; + +import com.baeldung.dao.repositories.user.UserRepository; +import com.baeldung.domain.user.User; +import org.junit.After; +import org.junit.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Sort; +import org.springframework.data.jpa.domain.JpaSort; +import org.springframework.data.mapping.PropertyReferenceException; +import org.springframework.transaction.annotation.Transactional; + +import javax.persistence.EntityManager; +import javax.persistence.Query; +import java.time.LocalDate; +import java.util.*; +import java.util.function.Predicate; +import java.util.stream.Stream; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.*; + +class UserRepositoryCommon { + + final String USER_EMAIL = "email@example.com"; + final String USER_EMAIL2 = "email2@example.com"; + final String USER_EMAIL3 = "email3@example.com"; + final String USER_EMAIL4 = "email4@example.com"; + final Integer INACTIVE_STATUS = 0; + final Integer ACTIVE_STATUS = 1; + private final String USER_EMAIL5 = "email5@example.com"; + private final String USER_EMAIL6 = "email6@example.com"; + private final String USER_NAME_ADAM = "Adam"; + private final String USER_NAME_PETER = "Peter"; + + @Autowired + protected UserRepository userRepository; + @Autowired + private EntityManager entityManager; + + @Test + @Transactional + public void givenUsersWithSameNameInDB_WhenFindAllByName_ThenReturnStreamOfUsers() { + User user1 = new User(); + user1.setName(USER_NAME_ADAM); + user1.setEmail(USER_EMAIL); + userRepository.save(user1); + + User user2 = new User(); + user2.setName(USER_NAME_ADAM); + user2.setEmail(USER_EMAIL2); + userRepository.save(user2); + + User user3 = new User(); + user3.setName(USER_NAME_ADAM); + user3.setEmail(USER_EMAIL3); + userRepository.save(user3); + + User user4 = new User(); + user4.setName("SAMPLE"); + user4.setEmail(USER_EMAIL4); + userRepository.save(user4); + + try (Stream foundUsersStream = userRepository.findAllByName(USER_NAME_ADAM)) { + assertThat(foundUsersStream.count()).isEqualTo(3l); + } + } + + @Test + public void givenUsersInDB_WhenFindAllWithQueryAnnotation_ThenReturnCollectionWithActiveUsers() { + User user1 = new User(); + user1.setName(USER_NAME_ADAM); + user1.setEmail(USER_EMAIL); + user1.setStatus(ACTIVE_STATUS); + userRepository.save(user1); + + User user2 = new User(); + user2.setName(USER_NAME_ADAM); + user2.setEmail(USER_EMAIL2); + user2.setStatus(ACTIVE_STATUS); + userRepository.save(user2); + + User user3 = new User(); + user3.setName(USER_NAME_ADAM); + user3.setEmail(USER_EMAIL3); + user3.setStatus(INACTIVE_STATUS); + userRepository.save(user3); + + Collection allActiveUsers = userRepository.findAllActiveUsers(); + + assertThat(allActiveUsers.size()).isEqualTo(2); + } + + @Test + public void givenUsersInDB_WhenFindAllWithQueryAnnotationNative_ThenReturnCollectionWithActiveUsers() { + User user1 = new User(); + user1.setName(USER_NAME_ADAM); + user1.setEmail(USER_EMAIL); + user1.setStatus(ACTIVE_STATUS); + userRepository.save(user1); + + User user2 = new User(); + user2.setName(USER_NAME_ADAM); + user2.setEmail(USER_EMAIL2); + user2.setStatus(ACTIVE_STATUS); + userRepository.save(user2); + + User user3 = new User(); + user3.setName(USER_NAME_ADAM); + user3.setEmail(USER_EMAIL3); + user3.setStatus(INACTIVE_STATUS); + userRepository.save(user3); + + Collection allActiveUsers = userRepository.findAllActiveUsersNative(); + + assertThat(allActiveUsers.size()).isEqualTo(2); + } + + @Test + public void givenUserInDB_WhenFindUserByStatusWithQueryAnnotation_ThenReturnActiveUser() { + User user = new User(); + user.setName(USER_NAME_ADAM); + user.setEmail(USER_EMAIL); + user.setStatus(ACTIVE_STATUS); + userRepository.save(user); + + User userByStatus = userRepository.findUserByStatus(ACTIVE_STATUS); + + assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); + } + + @Test + public void givenUserInDB_WhenFindUserByStatusWithQueryAnnotationNative_ThenReturnActiveUser() { + User user = new User(); + user.setName(USER_NAME_ADAM); + user.setEmail(USER_EMAIL); + user.setStatus(ACTIVE_STATUS); + userRepository.save(user); + + User userByStatus = userRepository.findUserByStatusNative(ACTIVE_STATUS); + + assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); + } + + @Test + public void givenUsersInDB_WhenFindUserByStatusAndNameWithQueryAnnotationIndexedParams_ThenReturnOneUser() { + User user = new User(); + user.setName(USER_NAME_ADAM); + user.setEmail(USER_EMAIL); + user.setStatus(ACTIVE_STATUS); + userRepository.save(user); + + User user2 = new User(); + user2.setName(USER_NAME_PETER); + user2.setEmail(USER_EMAIL2); + user2.setStatus(ACTIVE_STATUS); + userRepository.save(user2); + + User userByStatus = userRepository.findUserByStatusAndName(ACTIVE_STATUS, USER_NAME_ADAM); + + assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); + } + + @Test + public void givenUsersInDB_WhenFindUserByStatusAndNameWithQueryAnnotationNamedParams_ThenReturnOneUser() { + User user = new User(); + user.setName(USER_NAME_ADAM); + user.setEmail(USER_EMAIL); + user.setStatus(ACTIVE_STATUS); + userRepository.save(user); + + User user2 = new User(); + user2.setName(USER_NAME_PETER); + user2.setEmail(USER_EMAIL2); + user2.setStatus(ACTIVE_STATUS); + userRepository.save(user2); + + User userByStatus = userRepository.findUserByStatusAndNameNamedParams(ACTIVE_STATUS, USER_NAME_ADAM); + + assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); + } + + @Test + public void givenUsersInDB_WhenFindUserByStatusAndNameWithQueryAnnotationNativeNamedParams_ThenReturnOneUser() { + User user = new User(); + user.setName(USER_NAME_ADAM); + user.setEmail(USER_EMAIL); + user.setStatus(ACTIVE_STATUS); + userRepository.save(user); + + User user2 = new User(); + user2.setName(USER_NAME_PETER); + user2.setEmail(USER_EMAIL2); + user2.setStatus(ACTIVE_STATUS); + userRepository.save(user2); + + User userByStatus = userRepository.findUserByStatusAndNameNamedParamsNative(ACTIVE_STATUS, USER_NAME_ADAM); + + assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); + } + + @Test + public void givenUsersInDB_WhenFindUserByStatusAndNameWithQueryAnnotationNamedParamsCustomNames_ThenReturnOneUser() { + User user = new User(); + user.setName(USER_NAME_ADAM); + user.setEmail(USER_EMAIL); + user.setStatus(ACTIVE_STATUS); + userRepository.save(user); + + User user2 = new User(); + user2.setName(USER_NAME_PETER); + user2.setEmail(USER_EMAIL2); + user2.setStatus(ACTIVE_STATUS); + userRepository.save(user2); + + User userByStatus = userRepository.findUserByUserStatusAndUserName(ACTIVE_STATUS, USER_NAME_ADAM); + + assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); + } + + @Test + public void givenUsersInDB_WhenFindUserByNameLikeWithQueryAnnotationIndexedParams_ThenReturnUser() { + User user = new User(); + user.setName(USER_NAME_ADAM); + user.setEmail(USER_EMAIL); + user.setStatus(ACTIVE_STATUS); + userRepository.save(user); + + User userByStatus = userRepository.findUserByNameLike("Ad"); + + assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); + } + + @Test + public void givenUsersInDB_WhenFindUserByNameLikeWithQueryAnnotationNamedParams_ThenReturnUser() { + User user = new User(); + user.setName(USER_NAME_ADAM); + user.setEmail(USER_EMAIL); + user.setStatus(ACTIVE_STATUS); + userRepository.save(user); + + User userByStatus = userRepository.findUserByNameLikeNamedParam("Ad"); + + assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); + } + + @Test + public void givenUsersInDB_WhenFindUserByNameLikeWithQueryAnnotationNative_ThenReturnUser() { + User user = new User(); + user.setName(USER_NAME_ADAM); + user.setEmail(USER_EMAIL); + user.setStatus(ACTIVE_STATUS); + userRepository.save(user); + + User userByStatus = userRepository.findUserByNameLikeNative("Ad"); + + assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); + } + + @Test + public void givenUsersInDB_WhenFindAllWithSortByName_ThenReturnUsersSorted() { + userRepository.save(new User(USER_NAME_ADAM, LocalDate.now(), USER_EMAIL, ACTIVE_STATUS)); + userRepository.save(new User(USER_NAME_PETER, LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, INACTIVE_STATUS)); + + List usersSortByName = userRepository.findAll(new Sort(Sort.Direction.ASC, "name")); + + assertThat(usersSortByName.get(0) + .getName()).isEqualTo(USER_NAME_ADAM); + } + + @Test(expected = PropertyReferenceException.class) + public void givenUsersInDB_WhenFindAllSortWithFunction_ThenThrowException() { + userRepository.save(new User(USER_NAME_ADAM, LocalDate.now(), USER_EMAIL, ACTIVE_STATUS)); + userRepository.save(new User(USER_NAME_PETER, LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, INACTIVE_STATUS)); + + userRepository.findAll(new Sort(Sort.Direction.ASC, "name")); + + List usersSortByNameLength = userRepository.findAll(new Sort("LENGTH(name)")); + + assertThat(usersSortByNameLength.get(0) + .getName()).isEqualTo(USER_NAME_ADAM); + } + + @Test + public void givenUsersInDB_WhenFindAllSortWithFunctionQueryAnnotationJPQL_ThenReturnUsersSorted() { + userRepository.save(new User(USER_NAME_ADAM, LocalDate.now(), USER_EMAIL, ACTIVE_STATUS)); + userRepository.save(new User(USER_NAME_PETER, LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, INACTIVE_STATUS)); + + userRepository.findAllUsers(new Sort("name")); + + List usersSortByNameLength = userRepository.findAllUsers(JpaSort.unsafe("LENGTH(name)")); + + assertThat(usersSortByNameLength.get(0) + .getName()).isEqualTo(USER_NAME_ADAM); + } + + @Test + public void givenUsersInDB_WhenFindAllWithPageRequestQueryAnnotationJPQL_ThenReturnPageOfUsers() { + userRepository.save(new User(USER_NAME_ADAM, LocalDate.now(), USER_EMAIL, ACTIVE_STATUS)); + userRepository.save(new User(USER_NAME_PETER, LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, INACTIVE_STATUS)); + userRepository.save(new User("SAMPLE1", LocalDate.now(), USER_EMAIL4, INACTIVE_STATUS)); + userRepository.save(new User("SAMPLE2", LocalDate.now(), USER_EMAIL5, INACTIVE_STATUS)); + userRepository.save(new User("SAMPLE3", LocalDate.now(), USER_EMAIL6, INACTIVE_STATUS)); + + Page usersPage = userRepository.findAllUsersWithPagination(new PageRequest(1, 3)); + + assertThat(usersPage.getContent() + .get(0) + .getName()).isEqualTo("SAMPLE1"); + } + + @Test + public void givenUsersInDB_WhenFindAllWithPageRequestQueryAnnotationNative_ThenReturnPageOfUsers() { + userRepository.save(new User(USER_NAME_ADAM, LocalDate.now(), USER_EMAIL, ACTIVE_STATUS)); + userRepository.save(new User(USER_NAME_PETER, LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, INACTIVE_STATUS)); + userRepository.save(new User("SAMPLE1", LocalDate.now(), USER_EMAIL4, INACTIVE_STATUS)); + userRepository.save(new User("SAMPLE2", LocalDate.now(), USER_EMAIL5, INACTIVE_STATUS)); + userRepository.save(new User("SAMPLE3", LocalDate.now(), USER_EMAIL6, INACTIVE_STATUS)); + + Page usersSortByNameLength = userRepository.findAllUsersWithPaginationNative(new PageRequest(1, 3)); + + assertThat(usersSortByNameLength.getContent() + .get(0) + .getName()).isEqualTo(USER_NAME_PETER); + } + + @Test + @Transactional + public void givenUsersInDB_WhenUpdateStatusForNameModifyingQueryAnnotationJPQL_ThenModifyMatchingUsers() { + userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL, ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE1", LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE3", LocalDate.now(), USER_EMAIL4, ACTIVE_STATUS)); + + int updatedUsersSize = userRepository.updateUserSetStatusForName(INACTIVE_STATUS, "SAMPLE"); + + assertThat(updatedUsersSize).isEqualTo(2); + } + + @Test + public void givenUsersInDB_WhenFindByEmailsWithDynamicQuery_ThenReturnCollection() { + + 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); + } + + @Test + public void givenUsersInDBWhenFindByNameListReturnCollection() { + + User user1 = new User(); + user1.setName(USER_NAME_ADAM); + user1.setEmail(USER_EMAIL); + userRepository.save(user1); + + User user2 = new User(); + user2.setName(USER_NAME_PETER); + user2.setEmail(USER_EMAIL2); + userRepository.save(user2); + + List names = Arrays.asList(USER_NAME_ADAM, USER_NAME_PETER); + + List usersWithNames = userRepository.findUserByNameList(names); + + assertThat(usersWithNames.size()).isEqualTo(2); + } + + + @Test + @Transactional + public void givenTwoUsers_whenFindByNameUsr01_ThenUserUsr01() { + User usr01 = new User("usr01", LocalDate.now(), "usr01@baeldung.com", 1); + User usr02 = new User("usr02", LocalDate.now(), "usr02@baeldung.com", 1); + + userRepository.save(usr01); + userRepository.save(usr02); + + try (Stream users = userRepository.findAllByName("usr01")) { + assertTrue(users.allMatch(usr -> usr.equals(usr01))); + } + } + + @Test + @Transactional + public void givenTwoUsers_whenFindByNameUsr00_ThenNoUsers() { + User usr01 = new User("usr01", LocalDate.now(), "usr01@baeldung.com", 1); + User usr02 = new User("usr02", LocalDate.now(), "usr02@baeldung.com", 1); + + userRepository.save(usr01); + userRepository.save(usr02); + + try (Stream users = userRepository.findAllByName("usr00")) { + assertEquals(0, users.count()); + } + } + + @Test + public void givenTwoUsers_whenFindUsersWithGmailAddress_ThenUserUsr02() { + User usr01 = new User("usr01", LocalDate.now(), "usr01@baeldung.com", 1); + User usr02 = new User("usr02", LocalDate.now(), "usr02@gmail.com", 1); + + userRepository.save(usr01); + userRepository.save(usr02); + + List users = userRepository.findUsersWithGmailAddress(); + assertEquals(1, users.size()); + assertEquals(usr02, users.get(0)); + } + + @Test + @Transactional + public void givenTwoUsers_whenDeleteAllByCreationDateAfter_ThenOneUserRemains() { + User usr01 = new User("usr01", LocalDate.of(2018, 1, 1), "usr01@baeldung.com", 1); + User usr02 = new User("usr02", LocalDate.of(2018, 6, 1), "usr02@baeldung.com", 1); + + userRepository.save(usr01); + userRepository.save(usr02); + + userRepository.deleteAllByCreationDateAfter(LocalDate.of(2018, 5, 1)); + + List users = userRepository.findAll(); + + assertEquals(1, users.size()); + assertEquals(usr01, users.get(0)); + } + + @Test + public void givenTwoUsers_whenFindAllUsersByPredicates_ThenUserUsr01() { + User usr01 = new User("usr01", LocalDate.of(2018, 1, 1), "usr01@baeldung.com", 1); + User usr02 = new User("usr02", LocalDate.of(2018, 6, 1), "usr02@baeldung.org", 1); + + userRepository.save(usr01); + userRepository.save(usr02); + + List> predicates = new ArrayList<>(); + predicates.add(usr -> usr.getCreationDate().isAfter(LocalDate.of(2017, 12, 31))); + predicates.add(usr -> usr.getEmail().endsWith(".com")); + + List users = userRepository.findAllUsersByPredicates(predicates); + + assertEquals(1, users.size()); + assertEquals(usr01, users.get(0)); + } + + @Test + @Transactional + public void givenTwoUsers_whenDeactivateUsersNotLoggedInSince_ThenUserUsr02Deactivated() { + User usr01 = new User("usr01", LocalDate.of(2018, 1, 1), "usr01@baeldung.com", 1); + usr01.setLastLoginDate(LocalDate.now()); + User usr02 = new User("usr02", LocalDate.of(2018, 6, 1), "usr02@baeldung.org", 1); + usr02.setLastLoginDate(LocalDate.of(2018, 7, 20)); + + userRepository.save(usr01); + userRepository.save(usr02); + + userRepository.deactivateUsersNotLoggedInSince(LocalDate.of(2018, 8, 1)); + + List users = userRepository.findAllUsers(Sort.by(Sort.Order.asc("name"))); + assertTrue(users.get(0).isActive()); + assertFalse(users.get(1).isActive()); + } + + @Test + @Transactional + public void givenTwoUsers_whenDeleteDeactivatedUsers_ThenUserUsr02Deleted() { + User usr01 = new User("usr01", LocalDate.of(2018, 1, 1), "usr01@baeldung.com", 1); + usr01.setLastLoginDate(LocalDate.now()); + User usr02 = new User("usr02", LocalDate.of(2018, 6, 1), "usr02@baeldung.com", 0); + usr02.setLastLoginDate(LocalDate.of(2018, 7, 20)); + usr02.setActive(false); + + userRepository.save(usr01); + userRepository.save(usr02); + + int deletedUsersCount = userRepository.deleteDeactivatedUsers(); + + List users = userRepository.findAll(); + assertEquals(1, users.size()); + assertEquals(usr01, users.get(0)); + assertEquals(1, deletedUsersCount); + } + + @Test + @Transactional + public void givenTwoUsers_whenAddDeletedColumn_ThenUsersHaveDeletedColumn() { + User usr01 = new User("usr01", LocalDate.of(2018, 1, 1), "usr01@baeldung.com", 1); + usr01.setLastLoginDate(LocalDate.now()); + User usr02 = new User("usr02", LocalDate.of(2018, 6, 1), "usr02@baeldung.org", 1); + usr02.setLastLoginDate(LocalDate.of(2018, 7, 20)); + usr02.setActive(false); + + userRepository.save(usr01); + userRepository.save(usr02); + + userRepository.addDeletedColumn(); + + Query nativeQuery = entityManager.createNativeQuery("select deleted from USERS where NAME = 'usr01'"); + assertEquals(0, nativeQuery.getResultList().get(0)); + } + + @After + public void cleanUp() { + userRepository.deleteAll(); + } +} diff --git a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/UserRepositoryTCAutoIntegrationTest.java b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/UserRepositoryTCAutoIntegrationTest.java new file mode 100644 index 0000000000..6a851823e3 --- /dev/null +++ b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/UserRepositoryTCAutoIntegrationTest.java @@ -0,0 +1,42 @@ +package com.baeldung.dao.repositories; + +import com.baeldung.domain.user.User; +import com.baeldung.util.BaeldungPostgresqlContainer; +import org.junit.ClassRule; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.transaction.annotation.Transactional; +import org.testcontainers.containers.PostgreSQLContainer; + +import java.time.LocalDate; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Created by adam. + */ +@RunWith(SpringRunner.class) +@SpringBootTest +@ActiveProfiles({"tc", "tc-auto"}) +public class UserRepositoryTCAutoIntegrationTest extends UserRepositoryCommon { + + @ClassRule + public static PostgreSQLContainer postgreSQLContainer = BaeldungPostgresqlContainer.getInstance(); + + @Test + @Transactional + public void givenUsersInDB_WhenUpdateStatusForNameModifyingQueryAnnotationNativePostgres_ThenModifyMatchingUsers() { + userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL, ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE1", LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE3", LocalDate.now(), USER_EMAIL4, ACTIVE_STATUS)); + userRepository.flush(); + + int updatedUsersSize = userRepository.updateUserSetStatusForNameNativePostgres(INACTIVE_STATUS, "SAMPLE"); + + assertThat(updatedUsersSize).isEqualTo(2); + } +} diff --git a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/UserRepositoryTCIntegrationTest.java b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/UserRepositoryTCIntegrationTest.java new file mode 100644 index 0000000000..c300a07ab9 --- /dev/null +++ b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/UserRepositoryTCIntegrationTest.java @@ -0,0 +1,57 @@ +package com.baeldung.dao.repositories; + +import com.baeldung.domain.user.User; +import org.junit.ClassRule; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.util.TestPropertyValues; +import org.springframework.context.ApplicationContextInitializer; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.transaction.annotation.Transactional; +import org.testcontainers.containers.PostgreSQLContainer; + +import java.time.LocalDate; + +import static org.assertj.core.api.Assertions.assertThat; + +@RunWith(SpringRunner.class) +@SpringBootTest +@ActiveProfiles("tc") +@ContextConfiguration(initializers = {UserRepositoryTCIntegrationTest.Initializer.class}) +public class UserRepositoryTCIntegrationTest extends UserRepositoryCommon { + + @ClassRule + public static PostgreSQLContainer postgreSQLContainer = new PostgreSQLContainer("postgres:11.1") + .withDatabaseName("integration-tests-db") + .withUsername("sa") + .withPassword("sa"); + + @Test + @Transactional + public void givenUsersInDB_WhenUpdateStatusForNameModifyingQueryAnnotationNative_ThenModifyMatchingUsers() { + userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL, ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE1", LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE3", LocalDate.now(), USER_EMAIL4, ACTIVE_STATUS)); + userRepository.flush(); + + int updatedUsersSize = userRepository.updateUserSetStatusForNameNativePostgres(INACTIVE_STATUS, "SAMPLE"); + + assertThat(updatedUsersSize).isEqualTo(2); + } + + static class Initializer + implements ApplicationContextInitializer { + public void initialize(ConfigurableApplicationContext configurableApplicationContext) { + TestPropertyValues.of( + "spring.datasource.url=" + postgreSQLContainer.getJdbcUrl(), + "spring.datasource.username=" + postgreSQLContainer.getUsername(), + "spring.datasource.password=" + postgreSQLContainer.getPassword() + ).applyTo(configurableApplicationContext.getEnvironment()); + } + } +} diff --git a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/user/UserRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/user/UserRepositoryIntegrationTest.java index 14c2b0eb46..09f937c8f2 100644 --- a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/user/UserRepositoryIntegrationTest.java +++ b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/user/UserRepositoryIntegrationTest.java @@ -1,31 +1,17 @@ -package com.baeldung.dao.repositories.user; +package com.baeldung.dao.repositories; import com.baeldung.config.PersistenceConfiguration; import com.baeldung.domain.user.User; -import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.PageRequest; -import org.springframework.data.domain.Sort; -import org.springframework.data.jpa.domain.JpaSort; -import org.springframework.data.mapping.PropertyReferenceException; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.transaction.annotation.Transactional; -import javax.persistence.EntityManager; -import javax.persistence.Query; import java.time.LocalDate; -import java.util.*; -import java.util.function.Predicate; -import java.util.stream.Stream; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.*; /** * Created by adam. @@ -33,329 +19,7 @@ import static org.junit.Assert.*; @RunWith(SpringRunner.class) @SpringBootTest(classes = PersistenceConfiguration.class) @DirtiesContext -public class UserRepositoryIntegrationTest { - - private final String USER_NAME_ADAM = "Adam"; - private final String USER_NAME_PETER = "Peter"; - - private final String USER_EMAIL = "email@example.com"; - private final String USER_EMAIL2 = "email2@example.com"; - private final String USER_EMAIL3 = "email3@example.com"; - private final String USER_EMAIL4 = "email4@example.com"; - private final String USER_EMAIL5 = "email5@example.com"; - private final String USER_EMAIL6 = "email6@example.com"; - - private final Integer INACTIVE_STATUS = 0; - private final Integer ACTIVE_STATUS = 1; - - @Autowired - private UserRepository userRepository; - @Autowired - private EntityManager entityManager; - - @Test - @Transactional - public void givenUsersWithSameNameInDBWhenFindAllByNameThenReturnStreamOfUsers() { - User user1 = new User(); - user1.setName(USER_NAME_ADAM); - user1.setEmail(USER_EMAIL); - userRepository.save(user1); - - User user2 = new User(); - user2.setName(USER_NAME_ADAM); - user2.setEmail(USER_EMAIL2); - userRepository.save(user2); - - User user3 = new User(); - user3.setName(USER_NAME_ADAM); - user3.setEmail(USER_EMAIL3); - userRepository.save(user3); - - User user4 = new User(); - user4.setName("SAMPLE"); - user4.setEmail(USER_EMAIL4); - userRepository.save(user4); - - try (Stream foundUsersStream = userRepository.findAllByName(USER_NAME_ADAM)) { - assertThat(foundUsersStream.count()).isEqualTo(3l); - } - } - - @Test - public void givenUsersInDBWhenFindAllWithQueryAnnotationThenReturnCollectionWithActiveUsers() { - User user1 = new User(); - user1.setName(USER_NAME_ADAM); - user1.setEmail(USER_EMAIL); - user1.setStatus(ACTIVE_STATUS); - userRepository.save(user1); - - User user2 = new User(); - user2.setName(USER_NAME_ADAM); - user2.setEmail(USER_EMAIL2); - user2.setStatus(ACTIVE_STATUS); - userRepository.save(user2); - - User user3 = new User(); - user3.setName(USER_NAME_ADAM); - user3.setEmail(USER_EMAIL3); - user3.setStatus(INACTIVE_STATUS); - userRepository.save(user3); - - Collection allActiveUsers = userRepository.findAllActiveUsers(); - - assertThat(allActiveUsers.size()).isEqualTo(2); - } - - @Test - public void givenUsersInDBWhenFindAllWithQueryAnnotationNativeThenReturnCollectionWithActiveUsers() { - User user1 = new User(); - user1.setName(USER_NAME_ADAM); - user1.setEmail(USER_EMAIL); - user1.setStatus(ACTIVE_STATUS); - userRepository.save(user1); - - User user2 = new User(); - user2.setName(USER_NAME_ADAM); - user2.setEmail(USER_EMAIL2); - user2.setStatus(ACTIVE_STATUS); - userRepository.save(user2); - - User user3 = new User(); - user3.setName(USER_NAME_ADAM); - user3.setEmail(USER_EMAIL3); - user3.setStatus(INACTIVE_STATUS); - userRepository.save(user3); - - Collection allActiveUsers = userRepository.findAllActiveUsersNative(); - - assertThat(allActiveUsers.size()).isEqualTo(2); - } - - @Test - public void givenUserInDBWhenFindUserByStatusWithQueryAnnotationThenReturnActiveUser() { - User user = new User(); - user.setName(USER_NAME_ADAM); - user.setEmail(USER_EMAIL); - user.setStatus(ACTIVE_STATUS); - userRepository.save(user); - - User userByStatus = userRepository.findUserByStatus(ACTIVE_STATUS); - - assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test - public void givenUserInDBWhenFindUserByStatusWithQueryAnnotationNativeThenReturnActiveUser() { - User user = new User(); - user.setName(USER_NAME_ADAM); - user.setEmail(USER_EMAIL); - user.setStatus(ACTIVE_STATUS); - userRepository.save(user); - - User userByStatus = userRepository.findUserByStatusNative(ACTIVE_STATUS); - - assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test - public void givenUsersInDBWhenFindUserByStatusAndNameWithQueryAnnotationIndexedParamsThenReturnOneUser() { - User user = new User(); - user.setName(USER_NAME_ADAM); - user.setEmail(USER_EMAIL); - user.setStatus(ACTIVE_STATUS); - userRepository.save(user); - - User user2 = new User(); - user2.setName(USER_NAME_PETER); - user2.setEmail(USER_EMAIL2); - user2.setStatus(ACTIVE_STATUS); - userRepository.save(user2); - - User userByStatus = userRepository.findUserByStatusAndName(ACTIVE_STATUS, USER_NAME_ADAM); - - assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test - public void givenUsersInDBWhenFindUserByStatusAndNameWithQueryAnnotationNamedParamsThenReturnOneUser() { - User user = new User(); - user.setName(USER_NAME_ADAM); - user.setEmail(USER_EMAIL); - user.setStatus(ACTIVE_STATUS); - userRepository.save(user); - - User user2 = new User(); - user2.setName(USER_NAME_PETER); - user2.setEmail(USER_EMAIL2); - user2.setStatus(ACTIVE_STATUS); - userRepository.save(user2); - - User userByStatus = userRepository.findUserByStatusAndNameNamedParams(ACTIVE_STATUS, USER_NAME_ADAM); - - assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test - public void givenUsersInDBWhenFindUserByStatusAndNameWithQueryAnnotationNativeNamedParamsThenReturnOneUser() { - User user = new User(); - user.setName(USER_NAME_ADAM); - user.setEmail(USER_EMAIL); - user.setStatus(ACTIVE_STATUS); - userRepository.save(user); - - User user2 = new User(); - user2.setName(USER_NAME_PETER); - user2.setEmail(USER_EMAIL2); - user2.setStatus(ACTIVE_STATUS); - userRepository.save(user2); - - User userByStatus = userRepository.findUserByStatusAndNameNamedParamsNative(ACTIVE_STATUS, USER_NAME_ADAM); - - assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test - public void givenUsersInDBWhenFindUserByStatusAndNameWithQueryAnnotationNamedParamsCustomNamesThenReturnOneUser() { - User user = new User(); - user.setName(USER_NAME_ADAM); - user.setEmail(USER_EMAIL); - user.setStatus(ACTIVE_STATUS); - userRepository.save(user); - - User user2 = new User(); - user2.setName(USER_NAME_PETER); - user2.setEmail(USER_EMAIL2); - user2.setStatus(ACTIVE_STATUS); - userRepository.save(user2); - - User userByStatus = userRepository.findUserByUserStatusAndUserName(ACTIVE_STATUS, USER_NAME_ADAM); - - assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test - public void givenUsersInDBWhenFindUserByNameLikeWithQueryAnnotationIndexedParamsThenReturnUser() { - User user = new User(); - user.setName(USER_NAME_ADAM); - user.setEmail(USER_EMAIL); - user.setStatus(ACTIVE_STATUS); - userRepository.save(user); - - User userByStatus = userRepository.findUserByNameLike("Ad"); - - assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test - public void givenUsersInDBWhenFindUserByNameLikeWithQueryAnnotationNamedParamsThenReturnUser() { - User user = new User(); - user.setName(USER_NAME_ADAM); - user.setEmail(USER_EMAIL); - user.setStatus(ACTIVE_STATUS); - userRepository.save(user); - - User userByStatus = userRepository.findUserByNameLikeNamedParam("Ad"); - - assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test - public void givenUsersInDBWhenFindUserByNameLikeWithQueryAnnotationNativeThenReturnUser() { - User user = new User(); - user.setName(USER_NAME_ADAM); - user.setEmail(USER_EMAIL); - user.setStatus(ACTIVE_STATUS); - userRepository.save(user); - - User userByStatus = userRepository.findUserByNameLikeNative("Ad"); - - assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test - public void givenUsersInDBWhenFindAllWithSortByNameThenReturnUsersSorted() { - userRepository.save(new User(USER_NAME_ADAM, LocalDate.now(), USER_EMAIL, ACTIVE_STATUS)); - userRepository.save(new User(USER_NAME_PETER, LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, INACTIVE_STATUS)); - - List usersSortByName = userRepository.findAll(new Sort(Sort.Direction.ASC, "name")); - - assertThat(usersSortByName.get(0) - .getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test(expected = PropertyReferenceException.class) - public void givenUsersInDBWhenFindAllSortWithFunctionThenThrowException() { - userRepository.save(new User(USER_NAME_ADAM, LocalDate.now(), USER_EMAIL, ACTIVE_STATUS)); - userRepository.save(new User(USER_NAME_PETER, LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, INACTIVE_STATUS)); - - userRepository.findAll(new Sort(Sort.Direction.ASC, "name")); - - List usersSortByNameLength = userRepository.findAll(new Sort("LENGTH(name)")); - - assertThat(usersSortByNameLength.get(0) - .getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test - public void givenUsersInDBWhenFindAllSortWithFunctionQueryAnnotationJPQLThenReturnUsersSorted() { - userRepository.save(new User(USER_NAME_ADAM, LocalDate.now(), USER_EMAIL, ACTIVE_STATUS)); - userRepository.save(new User(USER_NAME_PETER, LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, INACTIVE_STATUS)); - - userRepository.findAllUsers(new Sort("name")); - - List usersSortByNameLength = userRepository.findAllUsers(JpaSort.unsafe("LENGTH(name)")); - - assertThat(usersSortByNameLength.get(0) - .getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test - public void givenUsersInDBWhenFindAllWithPageRequestQueryAnnotationJPQLThenReturnPageOfUsers() { - userRepository.save(new User(USER_NAME_ADAM, LocalDate.now(), USER_EMAIL, ACTIVE_STATUS)); - userRepository.save(new User(USER_NAME_PETER, LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, INACTIVE_STATUS)); - userRepository.save(new User("SAMPLE1", LocalDate.now(), USER_EMAIL4, INACTIVE_STATUS)); - userRepository.save(new User("SAMPLE2", LocalDate.now(), USER_EMAIL5, INACTIVE_STATUS)); - userRepository.save(new User("SAMPLE3", LocalDate.now(), USER_EMAIL6, INACTIVE_STATUS)); - - Page usersPage = userRepository.findAllUsersWithPagination(new PageRequest(1, 3)); - - assertThat(usersPage.getContent() - .get(0) - .getName()).isEqualTo("SAMPLE1"); - } - - @Test - public void givenUsersInDBWhenFindAllWithPageRequestQueryAnnotationNativeThenReturnPageOfUsers() { - userRepository.save(new User(USER_NAME_ADAM, LocalDate.now(), USER_EMAIL, ACTIVE_STATUS)); - userRepository.save(new User(USER_NAME_PETER, LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, INACTIVE_STATUS)); - userRepository.save(new User("SAMPLE1", LocalDate.now(), USER_EMAIL4, INACTIVE_STATUS)); - userRepository.save(new User("SAMPLE2", LocalDate.now(), USER_EMAIL5, INACTIVE_STATUS)); - userRepository.save(new User("SAMPLE3", LocalDate.now(), USER_EMAIL6, INACTIVE_STATUS)); - - Page usersSortByNameLength = userRepository.findAllUsersWithPaginationNative(new PageRequest(1, 3)); - - assertThat(usersSortByNameLength.getContent() - .get(0) - .getName()).isEqualTo("SAMPLE1"); - } - - @Test - @Transactional - public void givenUsersInDBWhenUpdateStatusForNameModifyingQueryAnnotationJPQLThenModifyMatchingUsers() { - userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE1", LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE3", LocalDate.now(), USER_EMAIL4, ACTIVE_STATUS)); - - int updatedUsersSize = userRepository.updateUserSetStatusForName(INACTIVE_STATUS, "SAMPLE"); - - assertThat(updatedUsersSize).isEqualTo(2); - } +public class UserRepositoryIntegrationTest extends UserRepositoryCommon { @Test @Transactional @@ -370,166 +34,4 @@ 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); - } - - @Test - @Transactional - public void givenTwoUsers_whenFindByNameUsr01_ThenUserUsr01() { - User usr01 = new User("usr01", LocalDate.now(), "usr01@baeldung.com", 1); - User usr02 = new User("usr02", LocalDate.now(), "usr02@baeldung.com", 1); - - userRepository.save(usr01); - userRepository.save(usr02); - - try (Stream users = userRepository.findAllByName("usr01")) { - assertTrue(users.allMatch(usr -> usr.equals(usr01))); - } - } - - @Test - @Transactional - public void givenTwoUsers_whenFindByNameUsr00_ThenNoUsers() { - User usr01 = new User("usr01", LocalDate.now(), "usr01@baeldung.com", 1); - User usr02 = new User("usr02", LocalDate.now(), "usr02@baeldung.com", 1); - - userRepository.save(usr01); - userRepository.save(usr02); - - try (Stream users = userRepository.findAllByName("usr00")) { - assertEquals(0, users.count()); - } - } - - @Test - public void givenTwoUsers_whenFindUsersWithGmailAddress_ThenUserUsr02() { - User usr01 = new User("usr01", LocalDate.now(), "usr01@baeldung.com", 1); - User usr02 = new User("usr02", LocalDate.now(), "usr02@gmail.com", 1); - - userRepository.save(usr01); - userRepository.save(usr02); - - List users = userRepository.findUsersWithGmailAddress(); - assertEquals(1, users.size()); - assertEquals(usr02, users.get(0)); - } - - @Test - @Transactional - public void givenTwoUsers_whenDeleteAllByCreationDateAfter_ThenOneUserRemains() { - User usr01 = new User("usr01", LocalDate.of(2018, 1, 1), "usr01@baeldung.com", 1); - User usr02 = new User("usr02", LocalDate.of(2018, 6, 1), "usr02@baeldung.com", 1); - - userRepository.save(usr01); - userRepository.save(usr02); - - userRepository.deleteAllByCreationDateAfter(LocalDate.of(2018, 5, 1)); - - List users = userRepository.findAll(); - - assertEquals(1, users.size()); - assertEquals(usr01, users.get(0)); - } - - @Test - public void givenTwoUsers_whenFindAllUsersByPredicates_ThenUserUsr01() { - User usr01 = new User("usr01", LocalDate.of(2018, 1, 1), "usr01@baeldung.com", 1); - User usr02 = new User("usr02", LocalDate.of(2018, 6, 1), "usr02@baeldung.org", 1); - - userRepository.save(usr01); - userRepository.save(usr02); - - List> predicates = new ArrayList<>(); - predicates.add(usr -> usr.getCreationDate().isAfter(LocalDate.of(2017, 12, 31))); - predicates.add(usr -> usr.getEmail().endsWith(".com")); - - List users = userRepository.findAllUsersByPredicates(predicates); - - assertEquals(1, users.size()); - assertEquals(usr01, users.get(0)); - } - - @Test - @Transactional - public void givenTwoUsers_whenDeactivateUsersNotLoggedInSince_ThenUserUsr02Deactivated() { - User usr01 = new User("usr01", LocalDate.of(2018, 1, 1), "usr01@baeldung.com", 1); - usr01.setLastLoginDate(LocalDate.now()); - User usr02 = new User("usr02", LocalDate.of(2018, 6, 1), "usr02@baeldung.org", 1); - usr02.setLastLoginDate(LocalDate.of(2018, 7, 20)); - - userRepository.save(usr01); - userRepository.save(usr02); - - userRepository.deactivateUsersNotLoggedInSince(LocalDate.of(2018, 8, 1)); - - List users = userRepository.findAllUsers(Sort.by(Sort.Order.asc("name"))); - assertTrue(users.get(0).isActive()); - assertFalse(users.get(1).isActive()); - } - - @Test - @Transactional - public void givenTwoUsers_whenDeleteDeactivatedUsers_ThenUserUsr02Deleted() { - User usr01 = new User("usr01", LocalDate.of(2018, 1, 1), "usr01@baeldung.com", 1); - usr01.setLastLoginDate(LocalDate.now()); - User usr02 = new User("usr02", LocalDate.of(2018, 6, 1), "usr02@baeldung.org", 1); - usr02.setLastLoginDate(LocalDate.of(2018, 7, 20)); - usr02.setActive(false); - - userRepository.save(usr01); - userRepository.save(usr02); - - int deletedUsersCount = userRepository.deleteDeactivatedUsers(); - - List users = userRepository.findAll(); - assertEquals(1, users.size()); - assertEquals(usr01, users.get(0)); - assertEquals(1, deletedUsersCount); - } - - @Test - @Transactional - public void givenTwoUsers_whenAddDeletedColumn_ThenUsersHaveDeletedColumn() { - User usr01 = new User("usr01", LocalDate.of(2018, 1, 1), "usr01@baeldung.com", 1); - usr01.setLastLoginDate(LocalDate.now()); - User usr02 = new User("usr02", LocalDate.of(2018, 6, 1), "usr02@baeldung.org", 1); - usr02.setLastLoginDate(LocalDate.of(2018, 7, 20)); - usr02.setActive(false); - - userRepository.save(usr01); - userRepository.save(usr02); - - userRepository.addDeletedColumn(); - - Query nativeQuery = entityManager.createNativeQuery("select deleted from USERS.USERS where NAME = 'usr01'"); - assertEquals(0, nativeQuery.getResultList().get(0)); - } - - @After - public void cleanUp() { - userRepository.deleteAll(); - } - } diff --git a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/util/BaeldungPostgresqlContainer.java b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/util/BaeldungPostgresqlContainer.java new file mode 100644 index 0000000000..e5ad2dd448 --- /dev/null +++ b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/util/BaeldungPostgresqlContainer.java @@ -0,0 +1,35 @@ +package com.baeldung.util; + +import org.testcontainers.containers.PostgreSQLContainer; + +public class BaeldungPostgresqlContainer extends PostgreSQLContainer { + + private static final String IMAGE_VERSION = "postgres:11.1"; + + private static BaeldungPostgresqlContainer container; + + + private BaeldungPostgresqlContainer() { + super(IMAGE_VERSION); + } + + public static BaeldungPostgresqlContainer getInstance() { + if (container == null) { + container = new BaeldungPostgresqlContainer(); + } + return container; + } + + @Override + public void start() { + super.start(); + System.setProperty("DB_URL", container.getJdbcUrl()); + System.setProperty("DB_USERNAME", container.getUsername()); + System.setProperty("DB_PASSWORD", container.getPassword()); + } + + @Override + public void stop() { + //do nothing, JVM handles shut down + } +} diff --git a/persistence-modules/spring-data-jpa/src/test/resources/application-tc-auto.properties b/persistence-modules/spring-data-jpa/src/test/resources/application-tc-auto.properties new file mode 100644 index 0000000000..c3005d861f --- /dev/null +++ b/persistence-modules/spring-data-jpa/src/test/resources/application-tc-auto.properties @@ -0,0 +1,4 @@ +# configuration for test containers testing +spring.datasource.url=${DB_URL} +spring.datasource.username=${DB_USERNAME} +spring.datasource.password=${DB_PASSWORD} diff --git a/persistence-modules/spring-data-jpa/src/test/resources/application-tc.properties b/persistence-modules/spring-data-jpa/src/test/resources/application-tc.properties new file mode 100644 index 0000000000..3bf8693d53 --- /dev/null +++ b/persistence-modules/spring-data-jpa/src/test/resources/application-tc.properties @@ -0,0 +1,4 @@ +# configuration for Test Containers testing +spring.datasource.driver-class-name=org.postgresql.Driver +spring.jpa.hibernate.ddl-auto=create-drop +spring.jpa.properties.hibernate.temp.use_jdbc_metadata_defaults=false diff --git a/persistence-modules/spring-data-mongodb/pom.xml b/persistence-modules/spring-data-mongodb/pom.xml index c1faf72103..7156cdf071 100644 --- a/persistence-modules/spring-data-mongodb/pom.xml +++ b/persistence-modules/spring-data-mongodb/pom.xml @@ -23,7 +23,6 @@ spring-data-releasetrain Lovelace-SR3 pom - import diff --git a/persistence-modules/spring-data-solr/pom.xml b/persistence-modules/spring-data-solr/pom.xml index dcba80b49a..82539b0ca8 100644 --- a/persistence-modules/spring-data-solr/pom.xml +++ b/persistence-modules/spring-data-solr/pom.xml @@ -4,8 +4,8 @@ com.baeldung spring-data-solr 0.0.1-SNAPSHOT - jar spring-data-solr + jar com.baeldung diff --git a/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaIntegrationTest.java b/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaIntegrationTest.java index 723b097305..c3805bac57 100644 --- a/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaIntegrationTest.java +++ b/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaIntegrationTest.java @@ -1,17 +1,24 @@ package com.baeldung.hibernate.criteria; import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.List; import org.hibernate.Session; +import org.hibernate.Transaction; import org.junit.Test; import com.baeldung.hibernate.criteria.model.Item; import com.baeldung.hibernate.criteria.util.HibernateUtil; import com.baeldung.hibernate.criteria.view.ApplicationView; +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.CriteriaDelete; +import javax.persistence.criteria.CriteriaUpdate; +import javax.persistence.criteria.Root; + public class HibernateCriteriaIntegrationTest { final private ApplicationView av = new ApplicationView(); @@ -179,4 +186,51 @@ public class HibernateCriteriaIntegrationTest { session.close(); assertArrayEquals(expectedPriceBetweenItems, av.betweenCriteria()); } + + @Test + public void givenNewItemPrice_whenCriteriaUpdate_thenReturnAffectedResult() { + + int oldPrice = 10, newPrice = 20; + + Session session = HibernateUtil.getHibernateSession(); + + Item item = new Item(12, "Test Item 12", "This is a description"); + item.setItemPrice(oldPrice); + session.save(item); + + CriteriaBuilder cb = session.getCriteriaBuilder(); + CriteriaUpdate criteriaUpdate = cb.createCriteriaUpdate(Item.class); + Root root = criteriaUpdate.from(Item.class); + criteriaUpdate.set("itemPrice", newPrice); + criteriaUpdate.where(cb.equal(root.get("itemPrice"), oldPrice)); + + Transaction transaction = session.beginTransaction(); + session.createQuery(criteriaUpdate).executeUpdate(); + transaction.commit(); + + Item updatedItem = session.createQuery("FROM Item WHERE itemPrice = " + newPrice, Item.class).getSingleResult(); + session.refresh(updatedItem); + assertEquals(newPrice, updatedItem.getItemPrice().intValue()); + } + + @Test + public void givenTargetItemPrice_whenCriteriaDelete_thenDeleteMatched() { + + int targetPrice = 1000; + + Session session = HibernateUtil.getHibernateSession(); + CriteriaBuilder cb = session.getCriteriaBuilder(); + CriteriaDelete criteriaDelete = cb.createCriteriaDelete(Item.class); + Root root = criteriaDelete.from(Item.class); + criteriaDelete.where(cb.greaterThan(root.get("itemPrice"), targetPrice)); + + Transaction transaction = session.beginTransaction(); + session.createQuery(criteriaDelete).executeUpdate(); + transaction.commit(); + + List deletedItem = session.createQuery("FROM Item WHERE itemPrice > " + targetPrice, Item.class).list(); + assertTrue(deletedItem.isEmpty()); + + } + } diff --git a/persistence-modules/spring-jpa/README.md b/persistence-modules/spring-jpa/README.md index e6f91ac016..23c03d3bef 100644 --- a/persistence-modules/spring-jpa/README.md +++ b/persistence-modules/spring-jpa/README.md @@ -4,8 +4,8 @@ ### Relevant Articles: -- [Spring 3 and JPA with Hibernate](http://www.baeldung.com/2011/12/13/the-persistence-layer-with-spring-3-1-and-jpa/) -- [Transactions with Spring 3 and JPA](http://www.baeldung.com/2011/12/26/transaction-configuration-with-jpa-and-spring-3-1/) +- [A Guide to JPA with Spring](https://www.baeldung.com/the-persistence-layer-with-spring-and-jpa) +- [Transactions with Spring and JPA](https://www.baeldung.com/transaction-configuration-with-jpa-and-spring) - [The DAO with JPA and Spring](http://www.baeldung.com/spring-dao-jpa) - [JPA Pagination](http://www.baeldung.com/jpa-pagination) - [Sorting with JPA](http://www.baeldung.com/jpa-sort) @@ -21,6 +21,7 @@ - [Use Criteria Queries in a Spring Data Application](https://www.baeldung.com/spring-data-criteria-queries) - [Many-To-Many Relationship in JPA](https://www.baeldung.com/jpa-many-to-many) + ### Eclipse Config After importing the project into Eclipse, you may see the following error: "No persistence xml file found in project" diff --git a/persistence-modules/spring-jpa/pom.xml b/persistence-modules/spring-jpa/pom.xml index 400811b582..29a6996791 100644 --- a/persistence-modules/spring-jpa/pom.xml +++ b/persistence-modules/spring-jpa/pom.xml @@ -3,8 +3,8 @@ 4.0.0 spring-jpa 0.1-SNAPSHOT - war spring-jpa + war com.baeldung diff --git a/pom.xml b/pom.xml index 58d57ade05..1c016a2ea9 100644 --- a/pom.xml +++ b/pom.xml @@ -750,6 +750,7 @@ spring-security-x509 spring-session spring-sleuth + spring-soap spring-social-login spring-spel spring-state-machine @@ -1003,6 +1004,7 @@ core-java-concurrency-advanced core-kotlin + core-kotlin-2 jenkins/hello-world jhipster @@ -1459,6 +1461,7 @@ spring-security-x509 spring-session spring-sleuth + spring-soap spring-social-login spring-spel spring-state-machine @@ -1554,6 +1557,7 @@ core-java core-java-concurrency-advanced core-kotlin + core-kotlin-2 jenkins/hello-world jhipster diff --git a/ratpack/pom.xml b/ratpack/pom.xml index 7de11e6955..a4389275b6 100644 --- a/ratpack/pom.xml +++ b/ratpack/pom.xml @@ -3,9 +3,9 @@ 4.0.0 com.baeldung ratpack - jar 1.0-SNAPSHOT ratpack + jar http://maven.apache.org diff --git a/resteasy/bin/pom.xml b/resteasy/bin/pom.xml index f8cdc20360..15d8b5bd18 100644 --- a/resteasy/bin/pom.xml +++ b/resteasy/bin/pom.xml @@ -2,18 +2,11 @@ 4.0.0 - com.baeldung resteasy-tutorial 1.0 war - - 3.0.19.Final - 2.5 - 1.6.1 - - com.baeldung resteasy-tutorial @@ -80,4 +73,10 @@ ${commons-io.version} + + + 3.0.19.Final + 2.5 + 1.6.1 + \ No newline at end of file diff --git a/resteasy/pom.xml b/resteasy/pom.xml index 31a6ed485a..ca4124abca 100644 --- a/resteasy/pom.xml +++ b/resteasy/pom.xml @@ -5,8 +5,8 @@ com.baeldung resteasy 1.0 - war resteasy + war com.baeldung diff --git a/restx/pom.xml b/restx/pom.xml index c6233b968c..cc503f89b6 100644 --- a/restx/pom.xml +++ b/restx/pom.xml @@ -3,17 +3,10 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - restx 0.1-SNAPSHOT - war restx-demo - - - 1.8 - 1.8 - 0.35-rc4 - + war com.baeldung @@ -106,7 +99,7 @@ ch.qos.logback logback-classic - 1.0.13 + ${logback-classic.version} io.restx @@ -117,10 +110,11 @@ junit junit - 4.11 + ${junit.version} test + @@ -152,4 +146,11 @@ + + + 1.8 + 1.8 + 0.35-rc4 + 1.0.13 + diff --git a/rsocket/pom.xml b/rsocket/pom.xml index 8b04a31583..d2182719c2 100644 --- a/rsocket/pom.xml +++ b/rsocket/pom.xml @@ -4,51 +4,61 @@ rsocket 0.0.1-SNAPSHOT rsocket + jar - + com.baeldung parent-modules 1.0.0-SNAPSHOT - jar - + io.rsocket rsocket-core - 0.11.13 + ${rsocket.version} io.rsocket rsocket-transport-netty - 0.11.13 + ${rsocket.version} junit junit - 4.12 + ${junit.version} test org.hamcrest hamcrest-core - 1.3 + ${hamcrest.version} test ch.qos.logback logback-classic - 1.2.3 + ${logback.version} ch.qos.logback logback-core - 1.2.3 + ${logback.version} org.slf4j slf4j-api - 1.7.25 + ${slf4j-api.version} - \ No newline at end of file + + + 1.8 + 1.8 + 3.0.1 + 0.11.13 + 1.3 + 1.2.3 + 1.7.25 + + diff --git a/rxjava-2/pom.xml b/rxjava-2/pom.xml index 3038c20037..2519516f45 100644 --- a/rxjava-2/pom.xml +++ b/rxjava-2/pom.xml @@ -3,7 +3,6 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - rxjava-2 1.0-SNAPSHOT diff --git a/saas/pom.xml b/saas/pom.xml index 2abc932497..35de34ea72 100644 --- a/saas/pom.xml +++ b/saas/pom.xml @@ -4,8 +4,8 @@ com.baeldung saas 0.1.0-SNAPSHOT - jar saas + jar com.baeldung diff --git a/software-security/sql-injection-samples/pom.xml b/software-security/sql-injection-samples/pom.xml index d5e64db6b3..e1590662b7 100644 --- a/software-security/sql-injection-samples/pom.xml +++ b/software-security/sql-injection-samples/pom.xml @@ -2,23 +2,18 @@ 4.0.0 - - - parent-boot-2 - com.baeldung - 0.0.1-SNAPSHOT - ../../parent-boot-2 - - com.baeldung sql-injection-samples 0.0.1-SNAPSHOT sql-injection-samples Sample SQL Injection tests - - 1.8 - + + parent-boot-2 + com.baeldung + 0.0.1-SNAPSHOT + ../../parent-boot-2 + @@ -58,4 +53,8 @@ + + 1.8 + + diff --git a/spring-4/pom.xml b/spring-4/pom.xml index 60f1555d8f..eb64c1839f 100644 --- a/spring-4/pom.xml +++ b/spring-4/pom.xml @@ -3,8 +3,8 @@ 4.0.0 spring-4 spring-4 - jar spring-4 + jar parent-boot-1 diff --git a/spring-5-mvc/pom.xml b/spring-5-mvc/pom.xml index f5346a0fa0..5fb8f66f71 100644 --- a/spring-5-mvc/pom.xml +++ b/spring-5-mvc/pom.xml @@ -5,9 +5,9 @@ com.baeldung spring-5-mvc 0.0.1-SNAPSHOT - jar spring-5-mvc spring 5 MVC sample project about new features + jar com.baeldung diff --git a/spring-5-reactive-client/pom.xml b/spring-5-reactive-client/pom.xml index 6e39743ed0..1b71815eb4 100644 --- a/spring-5-reactive-client/pom.xml +++ b/spring-5-reactive-client/pom.xml @@ -2,10 +2,9 @@ 4.0.0 - spring-5-reactive-client - jar spring-5-reactive-client + jar spring 5 sample project about new features diff --git a/spring-5-reactive-oauth/README.md b/spring-5-reactive-oauth/README.md index 0f27cf5d20..ec5176670b 100644 --- a/spring-5-reactive-oauth/README.md +++ b/spring-5-reactive-oauth/README.md @@ -1,3 +1,4 @@ ### Relevant Articles: - [Spring Security OAuth Login with WebFlux](https://www.baeldung.com/spring-oauth-login-webflux) +- [Spring WebClient and OAuth2 Support](https://www.baeldung.com/spring-webclient-oauth2) diff --git a/spring-5-reactive-oauth/pom.xml b/spring-5-reactive-oauth/pom.xml index 73809681f2..86a5233ad4 100644 --- a/spring-5-reactive-oauth/pom.xml +++ b/spring-5-reactive-oauth/pom.xml @@ -2,13 +2,11 @@ 4.0.0 - com.baeldung.reactive.oauth spring-5-reactive-oauth 1.0.0-SNAPSHOT - jar - spring-5-reactive-oauth + jar WebFluc and Spring Security OAuth @@ -18,12 +16,6 @@ - - UTF-8 - UTF-8 - 1.8 - - org.springframework.boot @@ -62,11 +54,11 @@ org.apache.maven.plugins maven-surefire-plugin - 2.20.1 true **/*IntegrationTest.java + **/*LiveTest.java @@ -74,4 +66,10 @@ + + UTF-8 + UTF-8 + 1.8 + + diff --git a/spring-5-reactive-security/pom.xml b/spring-5-reactive-security/pom.xml index 3b64b9b3ac..72a73a86ce 100644 --- a/spring-5-reactive-security/pom.xml +++ b/spring-5-reactive-security/pom.xml @@ -2,12 +2,11 @@ 4.0.0 - com.baeldung spring-5-reactive-security 0.0.1-SNAPSHOT - jar spring-5-reactive-security + jar spring 5 security sample project about new features diff --git a/spring-5-reactive/pom.xml b/spring-5-reactive/pom.xml index 63cc185afe..a1eb6f4c8a 100644 --- a/spring-5-reactive/pom.xml +++ b/spring-5-reactive/pom.xml @@ -2,12 +2,11 @@ 4.0.0 - com.baeldung spring-5-reactive 0.0.1-SNAPSHOT - jar spring-5-reactive + jar spring 5 sample project about new features diff --git a/spring-5-security-oauth/pom.xml b/spring-5-security-oauth/pom.xml index 59150a153f..d9a1e3094e 100644 --- a/spring-5-security-oauth/pom.xml +++ b/spring-5-security-oauth/pom.xml @@ -4,8 +4,8 @@ com.baeldung spring-5-security-oauth 0.0.1-SNAPSHOT - jar spring-5-security-oauth + jar spring 5 security oauth sample project diff --git a/spring-5-security/pom.xml b/spring-5-security/pom.xml index c26e370381..413337633f 100644 --- a/spring-5-security/pom.xml +++ b/spring-5-security/pom.xml @@ -4,8 +4,8 @@ com.baeldung spring-5-security 0.0.1-SNAPSHOT - jar spring-5-security + jar spring 5 security sample project @@ -16,7 +16,6 @@ - org.springframework.boot spring-boot-starter-security diff --git a/spring-5/pom.xml b/spring-5/pom.xml index 58c14475e0..701aa3831d 100644 --- a/spring-5/pom.xml +++ b/spring-5/pom.xml @@ -6,8 +6,8 @@ com.baeldung spring-5 0.0.1-SNAPSHOT - jar spring-5 + jar spring 5 sample project about new features @@ -89,6 +89,12 @@ org.junit.jupiter junit-jupiter-api + + org.awaitility + awaitility + ${awaitility.version} + test + org.springframework.restdocs @@ -156,7 +162,7 @@ 4.1 ${project.build.directory}/generated-snippets 2.21.0 - + 3.1.6 diff --git a/spring-5/src/main/java/com/baeldung/config/ScheduledConfig.java b/spring-5/src/main/java/com/baeldung/config/ScheduledConfig.java new file mode 100644 index 0000000000..b54a2b5339 --- /dev/null +++ b/spring-5/src/main/java/com/baeldung/config/ScheduledConfig.java @@ -0,0 +1,11 @@ +package com.baeldung.config; + +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.scheduling.annotation.EnableScheduling; + +@Configuration +@EnableScheduling +@ComponentScan("com.baeldung.scheduled") +public class ScheduledConfig { +} diff --git a/spring-5/src/main/java/com/baeldung/scheduled/Counter.java b/spring-5/src/main/java/com/baeldung/scheduled/Counter.java new file mode 100644 index 0000000000..17aa15b6f3 --- /dev/null +++ b/spring-5/src/main/java/com/baeldung/scheduled/Counter.java @@ -0,0 +1,20 @@ +package com.baeldung.scheduled; + +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +import java.util.concurrent.atomic.AtomicInteger; + +@Component +public class Counter { + private final AtomicInteger count = new AtomicInteger(0); + + @Scheduled(fixedDelay = 5) + public void scheduled() { + this.count.incrementAndGet(); + } + + public int getInvocationCount() { + return this.count.get(); + } +} diff --git a/spring-5/src/test/java/com/baeldung/scheduled/ScheduledAwaitilityIntegrationTest.java b/spring-5/src/test/java/com/baeldung/scheduled/ScheduledAwaitilityIntegrationTest.java new file mode 100644 index 0000000000..4883aa16c2 --- /dev/null +++ b/spring-5/src/test/java/com/baeldung/scheduled/ScheduledAwaitilityIntegrationTest.java @@ -0,0 +1,24 @@ +package com.baeldung.scheduled; + +import com.baeldung.config.ScheduledConfig; +import org.awaitility.Duration; +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.mock.mockito.SpyBean; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; + +import static org.awaitility.Awaitility.await; +import static org.mockito.Mockito.atLeast; +import static org.mockito.Mockito.verify; + +@SpringJUnitConfig(ScheduledConfig.class) +public class ScheduledAwaitilityIntegrationTest { + + @SpyBean private Counter counter; + + @Test + public void whenWaitOneSecond_thenScheduledIsCalledAtLeastTenTimes() { + await() + .atMost(Duration.ONE_SECOND) + .untilAsserted(() -> verify(counter, atLeast(10)).scheduled()); + } +} diff --git a/spring-5/src/test/java/com/baeldung/scheduled/ScheduledIntegrationTest.java b/spring-5/src/test/java/com/baeldung/scheduled/ScheduledIntegrationTest.java new file mode 100644 index 0000000000..058cd50caa --- /dev/null +++ b/spring-5/src/test/java/com/baeldung/scheduled/ScheduledIntegrationTest.java @@ -0,0 +1,22 @@ +package com.baeldung.scheduled; + +import com.baeldung.config.ScheduledConfig; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; + +import static org.assertj.core.api.Assertions.assertThat; + +@SpringJUnitConfig(ScheduledConfig.class) +public class ScheduledIntegrationTest { + + @Autowired Counter counter; + + @Test + public void givenSleepBy100ms_whenGetInvocationCount_thenIsGreaterThanZero() throws InterruptedException { + Thread.sleep(100L); + + assertThat(counter.getInvocationCount()).isGreaterThan(0); + } + +} diff --git a/spring-activiti/pom.xml b/spring-activiti/pom.xml index 4e21c5b032..3d67a2ab7b 100644 --- a/spring-activiti/pom.xml +++ b/spring-activiti/pom.xml @@ -3,8 +3,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 spring-activiti - jar spring-activiti + jar Demo project for Spring Boot diff --git a/spring-all/pom.xml b/spring-all/pom.xml index 77c7e74e08..5872fbdac5 100644 --- a/spring-all/pom.xml +++ b/spring-all/pom.xml @@ -160,12 +160,12 @@ net.javacrumbs.shedlock shedlock-spring - 2.1.0 + ${shedlock.version} net.javacrumbs.shedlock shedlock-provider-jdbc-template - 2.1.0 + ${shedlock.version} @@ -243,7 +243,7 @@ 3.6 3.6.1 6.6.0 - + 2.1.0 3.22.0-GA diff --git a/spring-amqp/pom.xml b/spring-amqp/pom.xml index e08a4243b3..c021bd49ff 100755 --- a/spring-amqp/pom.xml +++ b/spring-amqp/pom.xml @@ -4,8 +4,8 @@ com.baeldung spring-amqp 0.1-SNAPSHOT - jar spring-amqp + jar Introduction to Spring-AMQP diff --git a/spring-aop/pom.xml b/spring-aop/pom.xml index 9e2f97916a..a1e2ffd534 100644 --- a/spring-aop/pom.xml +++ b/spring-aop/pom.xml @@ -2,8 +2,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 spring-aop - war spring-aop + war parent-boot-2 diff --git a/spring-apache-camel/pom.xml b/spring-apache-camel/pom.xml index 662b3f899c..3e76c0c7f1 100644 --- a/spring-apache-camel/pom.xml +++ b/spring-apache-camel/pom.xml @@ -3,9 +3,9 @@ 4.0.0 org.apache.camel spring-apache-camel - jar 1.0-SNAPSHOT spring-apache-camel + jar http://maven.apache.org diff --git a/spring-batch/pom.xml b/spring-batch/pom.xml index cfd725b2bd..e81078568b 100644 --- a/spring-batch/pom.xml +++ b/spring-batch/pom.xml @@ -4,8 +4,8 @@ com.baeldung spring-batch 0.1-SNAPSHOT - jar spring-batch + jar http://maven.apache.org diff --git a/spring-boot-admin/spring-boot-admin-client/pom.xml b/spring-boot-admin/spring-boot-admin-client/pom.xml index ea03d6ef6d..7563a01172 100644 --- a/spring-boot-admin/spring-boot-admin-client/pom.xml +++ b/spring-boot-admin/spring-boot-admin-client/pom.xml @@ -4,9 +4,9 @@ 4.0.0 spring-boot-admin-client 0.0.1-SNAPSHOT - jar spring-boot-admin-client Spring Boot Admin Client + jar spring-boot-admin diff --git a/spring-boot-admin/spring-boot-admin-server/pom.xml b/spring-boot-admin/spring-boot-admin-server/pom.xml index d8e7bb5574..d429d9289f 100644 --- a/spring-boot-admin/spring-boot-admin-server/pom.xml +++ b/spring-boot-admin/spring-boot-admin-server/pom.xml @@ -4,9 +4,9 @@ 4.0.0 spring-boot-admin-server 0.0.1-SNAPSHOT - jar spring-boot-admin-server Spring Boot Admin Server + jar spring-boot-admin diff --git a/spring-boot-angular-ecommerce/pom.xml b/spring-boot-angular-ecommerce/pom.xml index dc92a91d02..a5296eade8 100644 --- a/spring-boot-angular-ecommerce/pom.xml +++ b/spring-boot-angular-ecommerce/pom.xml @@ -2,12 +2,10 @@ 4.0.0 - spring-boot-angular-ecommerce 0.0.1-SNAPSHOT - jar - spring-boot-angular-ecommerce + jar Spring Boot Angular E-commerce Appliciation diff --git a/spring-boot-autoconfiguration/pom.xml b/spring-boot-autoconfiguration/pom.xml index 1c3d8796ed..91692ebfff 100644 --- a/spring-boot-autoconfiguration/pom.xml +++ b/spring-boot-autoconfiguration/pom.xml @@ -4,8 +4,8 @@ com.baeldung spring-boot-autoconfiguration 0.0.1-SNAPSHOT - war spring-boot-autoconfiguration + war This is simple boot application demonstrating a custom auto-configuration diff --git a/spring-boot-bootstrap/README.md b/spring-boot-bootstrap/README.md index 76b977c129..2186aa8fec 100644 --- a/spring-boot-bootstrap/README.md +++ b/spring-boot-bootstrap/README.md @@ -5,3 +5,4 @@ - [Deploying a Spring Boot Application to Cloud Foundry](https://www.baeldung.com/spring-boot-app-deploy-to-cloud-foundry) - [Deploy a Spring Boot Application to Google App Engine](https://www.baeldung.com/spring-boot-google-app-engine) - [Deploy a Spring Boot Application to OpenShift](https://www.baeldung.com/spring-boot-deploy-openshift) +- [Deploy a Spring Boot Application to AWS Beanstalk](https://www.baeldung.com/spring-boot-deploy-aws-beanstalk) diff --git a/spring-boot-bootstrap/pom.xml b/spring-boot-bootstrap/pom.xml index 0ffc1820b8..f13801f532 100644 --- a/spring-boot-bootstrap/pom.xml +++ b/spring-boot-bootstrap/pom.xml @@ -4,16 +4,18 @@ 4.0.0 com.baeldung spring-boot-bootstrap - jar spring-boot-bootstrap Demo project for Spring Boot - + jar + + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT ../parent-boot-2 - + + org.springframework.boot spring-boot-starter-web @@ -312,7 +314,8 @@ - + + org.apache.maven.plugins @@ -325,7 +328,8 @@ - + + 4.0.0 diff --git a/spring-boot-client/pom.xml b/spring-boot-client/pom.xml index fc89931f79..4850849039 100644 --- a/spring-boot-client/pom.xml +++ b/spring-boot-client/pom.xml @@ -4,8 +4,8 @@ com.baeldung spring-boot-client 0.0.1-SNAPSHOT - war spring-boot-client + war This is simple boot client application for Spring boot actuator test diff --git a/spring-boot-jasypt/pom.xml b/spring-boot-jasypt/pom.xml index de0df92678..ae0483f107 100644 --- a/spring-boot-jasypt/pom.xml +++ b/spring-boot-jasypt/pom.xml @@ -2,11 +2,10 @@ 4.0.0 - com.example.jasypt spring-boot-jasypt - jar spring-boot-jasypt + jar Demo project for Spring Boot diff --git a/spring-boot-keycloak/pom.xml b/spring-boot-keycloak/pom.xml index 3a39d4aa94..b13805b4bf 100644 --- a/spring-boot-keycloak/pom.xml +++ b/spring-boot-keycloak/pom.xml @@ -5,9 +5,9 @@ com.baeldung.keycloak spring-boot-keycloak 0.0.1 - jar spring-boot-keycloak This is a simple application demonstrating integration between Keycloak and Spring Boot. + jar com.baeldung diff --git a/spring-boot-libraries/pom.xml b/spring-boot-libraries/pom.xml index 66aa66bdfd..b448d6fd66 100644 --- a/spring-boot-libraries/pom.xml +++ b/spring-boot-libraries/pom.xml @@ -3,8 +3,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 spring-boot-libraries - war spring-boot-libraries + war This is simple boot application for Spring boot actuator test @@ -44,12 +44,12 @@ net.javacrumbs.shedlock shedlock-spring - 2.1.0 + ${shedlock.version} net.javacrumbs.shedlock shedlock-provider-jdbc-template - 2.1.0 + ${shedlock.version} @@ -151,6 +151,7 @@ 2.2.4 2.3.2 0.23.0 + 2.1.0 diff --git a/spring-boot-libraries/src/main/java/com/baeldung/boot/problem/advice/ExceptionHandler.java b/spring-boot-libraries/src/main/java/com/baeldung/boot/problem/advice/ExceptionHandler.java index 7b4cbac7f7..18df103733 100644 --- a/spring-boot-libraries/src/main/java/com/baeldung/boot/problem/advice/ExceptionHandler.java +++ b/spring-boot-libraries/src/main/java/com/baeldung/boot/problem/advice/ExceptionHandler.java @@ -5,5 +5,12 @@ import org.zalando.problem.spring.web.advice.ProblemHandling; @ControllerAdvice public class ExceptionHandler implements ProblemHandling { + + // The causal chain of causes is disabled by default, + // but we can easily enable it by overriding the behavior: + @Override + public boolean isCausalChainsEnabled() { + return true; + } } diff --git a/spring-boot-libraries/src/main/java/com/baeldung/boot/problem/configuration/ProblemDemoConfiguration.java b/spring-boot-libraries/src/main/java/com/baeldung/boot/problem/configuration/ProblemDemoConfiguration.java index 209ff553c7..f5e6a6b99a 100644 --- a/spring-boot-libraries/src/main/java/com/baeldung/boot/problem/configuration/ProblemDemoConfiguration.java +++ b/spring-boot-libraries/src/main/java/com/baeldung/boot/problem/configuration/ProblemDemoConfiguration.java @@ -12,6 +12,8 @@ public class ProblemDemoConfiguration { @Bean public ObjectMapper objectMapper() { - return new ObjectMapper().registerModules(new ProblemModule(), new ConstraintViolationProblemModule()); + // In this example, stack traces support is enabled by default. + // If you want to disable stack traces just use new ProblemModule() instead of new ProblemModule().withStackTraces() + return new ObjectMapper().registerModules(new ProblemModule().withStackTraces(), new ConstraintViolationProblemModule()); } } diff --git a/spring-boot-libraries/src/test/java/com/baeldung/boot/problem/controller/ProblemDemoControllerIntegrationTest.java b/spring-boot-libraries/src/test/java/com/baeldung/boot/problem/controller/ProblemDemoControllerIntegrationTest.java index 3b7e43a565..5ced1034c4 100644 --- a/spring-boot-libraries/src/test/java/com/baeldung/boot/problem/controller/ProblemDemoControllerIntegrationTest.java +++ b/spring-boot-libraries/src/test/java/com/baeldung/boot/problem/controller/ProblemDemoControllerIntegrationTest.java @@ -1,6 +1,8 @@ package com.baeldung.boot.problem.controller; +import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.notNullValue; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; @@ -71,5 +73,29 @@ public class ProblemDemoControllerIntegrationTest { .andExpect(jsonPath("$.detail", equalTo("You can't delete this task"))) .andExpect(status().isForbidden()); } + + @Test + public void whenMakeGetCallWithInvalidIdFormat_thenReturnBadRequestResponseWithStackTrace() throws Exception { + mockMvc.perform(get("/tasks/invalid-id").contentType(MediaType.APPLICATION_PROBLEM_JSON_VALUE)) + .andDo(print()) + .andExpect(jsonPath("$.title", equalTo("Bad Request"))) + .andExpect(jsonPath("$.status", equalTo(400))) + .andExpect(jsonPath("$.stacktrace", notNullValue())) + .andExpect(status().isBadRequest()); + } + + @Test + public void whenMakeGetCallWithInvalidIdFormat_thenReturnBadRequestResponseWithCause() throws Exception { + mockMvc.perform(get("/tasks/invalid-id").contentType(MediaType.APPLICATION_PROBLEM_JSON_VALUE)) + .andDo(print()) + .andExpect(jsonPath("$.title", equalTo("Bad Request"))) + .andExpect(jsonPath("$.status", equalTo(400))) + .andExpect(jsonPath("$.cause", notNullValue())) + .andExpect(jsonPath("$.cause.title", equalTo("Internal Server Error"))) + .andExpect(jsonPath("$.cause.status", equalTo(500))) + .andExpect(jsonPath("$.cause.detail", containsString("For input string:"))) + .andExpect(jsonPath("$.cause.stacktrace", notNullValue())) + .andExpect(status().isBadRequest()); + } } diff --git a/spring-boot-logging-log4j2/pom.xml b/spring-boot-logging-log4j2/pom.xml index ad678a14cf..6cc60da52c 100644 --- a/spring-boot-logging-log4j2/pom.xml +++ b/spring-boot-logging-log4j2/pom.xml @@ -3,8 +3,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 spring-boot-logging-log4j2 - jar spring-boot-logging-log4j2 + jar Demo project for Spring Boot Logging with Log4J2 @@ -40,12 +40,12 @@ org.springframework.boot spring-boot-starter-log4j - 1.3.8.RELEASE + ${spring-boot-starter-log4j.version} org.graylog2 gelfj - 1.1.16 + ${gelfj.version} compile @@ -71,5 +71,7 @@ com.baeldung.springbootlogging.SpringBootLoggingApplication + 1.3.8.RELEASE + 1.1.16 diff --git a/spring-boot-mvc/README.md b/spring-boot-mvc/README.md index bf32e4fc7c..0e1ac5a8ce 100644 --- a/spring-boot-mvc/README.md +++ b/spring-boot-mvc/README.md @@ -9,4 +9,5 @@ - [Display RSS Feed with Spring MVC](http://www.baeldung.com/spring-mvc-rss-feed) - [A Controller, Service and DAO Example with Spring Boot and JSF](https://www.baeldung.com/jsf-spring-boot-controller-service-dao) - [Cache Eviction in Spring Boot](https://www.baeldung.com/spring-boot-evict-cache) -- [Setting Up Swagger 2 with a Spring REST API](http://www.baeldung.com/swagger-2-documentation-for-spring-rest-api) \ No newline at end of file +- [Setting Up Swagger 2 with a Spring REST API](http://www.baeldung.com/swagger-2-documentation-for-spring-rest-api) +- [Conditionally Enable Scheduled Jobs in Spring](https://www.baeldung.com/spring-scheduled-enabled-conditionally) diff --git a/spring-boot-mvc/pom.xml b/spring-boot-mvc/pom.xml index bb3e6312ab..e17c1d39b9 100644 --- a/spring-boot-mvc/pom.xml +++ b/spring-boot-mvc/pom.xml @@ -1,66 +1,77 @@ - - 4.0.0 - spring-boot-mvc - jar - spring-boot-mvc - Module For Spring Boot MVC + + 4.0.0 + spring-boot-mvc + spring-boot-mvc + jar + Module For Spring Boot MVC - - parent-boot-2 - com.baeldung - 0.0.1-SNAPSHOT - ../parent-boot-2 - + + parent-boot-2 + com.baeldung + 0.0.1-SNAPSHOT + ../parent-boot-2 + - + - - org.springframework.boot - spring-boot-starter-web - - - org.apache.tomcat.embed - tomcat-embed-jasper - + + org.springframework.boot + spring-boot-starter-web + + + org.apache.tomcat.embed + tomcat-embed-jasper + + + org.springframework.boot + spring-boot-starter-tomcat + provided + + + org.springframework.boot + spring-boot-starter-thymeleaf + - - - org.glassfish - javax.faces - 2.3.7 - - - - org.springframework.boot - spring-boot-starter-test - test - + + + org.glassfish + javax.faces + 2.3.7 + - - - com.rometools - rome - ${rome.version} - + + + org.springframework.boot + spring-boot-starter-test + test + - - - org.hibernate.validator - hibernate-validator - - - javax.validation - validation-api - - - org.springframework.boot - spring-boot-starter-validation - + + + com.rometools + rome + ${rome.version} + - + + + org.hibernate.validator + hibernate-validator + + + javax.validation + validation-api + + + org.springframework.boot + spring-boot-starter-validation + + + io.springfox springfox-swagger2 @@ -77,31 +88,27 @@ tomcat-embed-jasper provided - - javax.servlet - jstl - - + - - - - org.springframework.boot - spring-boot-maven-plugin - - com.baeldung.springbootmvc.SpringBootMvcApplication - JAR - - - - + + + + org.springframework.boot + spring-boot-maven-plugin + + com.baeldung.springbootmvc.SpringBootMvcApplication + JAR + + + + - - 2.9.2 - - 1.10.0 - com.baeldung.springbootmvc.SpringBootMvcApplication - + + 2.9.2 + + 1.10.0 + com.baeldung.springbootmvc.SpringBootMvcApplication + diff --git a/spring-boot-mvc/src/main/java/com/baeldung/accessparamsjs/App.java b/spring-boot-mvc/src/main/java/com/baeldung/accessparamsjs/App.java index 2ffbb354c3..c16e784dd2 100644 --- a/spring-boot-mvc/src/main/java/com/baeldung/accessparamsjs/App.java +++ b/spring-boot-mvc/src/main/java/com/baeldung/accessparamsjs/App.java @@ -9,5 +9,4 @@ public class App { public static void main(String[] args) { SpringApplication.run(App.class, args); } - } diff --git a/spring-boot-mvc/src/main/java/com/baeldung/accessparamsjs/Controller.java b/spring-boot-mvc/src/main/java/com/baeldung/accessparamsjs/Controller.java index cc838eb6a5..8759f1bcd6 100644 --- a/spring-boot-mvc/src/main/java/com/baeldung/accessparamsjs/Controller.java +++ b/spring-boot-mvc/src/main/java/com/baeldung/accessparamsjs/Controller.java @@ -23,10 +23,10 @@ public class Controller { * @return */ @RequestMapping("/index") - public ModelAndView index(Map model) { + public ModelAndView thymeleafView(Map model) { model.put("number", 1234); model.put("message", "Hello from Spring MVC"); - return new ModelAndView("/index"); + return new ModelAndView("thymeleaf/index"); } } diff --git a/spring-boot-mvc/src/main/resources/application.properties b/spring-boot-mvc/src/main/resources/application.properties index 00362e2588..6dab470c84 100644 --- a/spring-boot-mvc/src/main/resources/application.properties +++ b/spring-boot-mvc/src/main/resources/application.properties @@ -1,3 +1,2 @@ spring.main.allow-bean-definition-overriding=true -spring.mvc.view.prefix=/WEB-INF/jsp/ -spring.mvc.view.suffix=.jsp \ No newline at end of file +spring.thymeleaf.view-names=thymeleaf/* \ No newline at end of file diff --git a/spring-boot-mvc/src/main/resources/templates/thymeleaf/index.html b/spring-boot-mvc/src/main/resources/templates/thymeleaf/index.html new file mode 100644 index 0000000000..4939d0ea50 --- /dev/null +++ b/spring-boot-mvc/src/main/resources/templates/thymeleaf/index.html @@ -0,0 +1,29 @@ + + + +Access Spring MVC params + + + + + + + Number= + +
Message= + +

Data from the external JS file (due to loading order)

+
+
+

Asynchronous loading from external JS file (plain JS)

+
+
+

Asynchronous loading from external JS file (jQuery)

+
+
+ + + diff --git a/spring-boot-mvc/src/main/webapp/WEB-INF/jsp/index.jsp b/spring-boot-mvc/src/main/webapp/WEB-INF/jsp/index.jsp deleted file mode 100644 index d9f3966e82..0000000000 --- a/spring-boot-mvc/src/main/webapp/WEB-INF/jsp/index.jsp +++ /dev/null @@ -1,27 +0,0 @@ - -<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> - - -Access Spring MVC params - - - - - - -

Data from the external JS file (due to loading order)

-
-
-

Asynchronous loading from external JS file (plain JS)

-
-
-

Asynchronous loading from external JS file (jQuery)

-
-
- - - - \ No newline at end of file diff --git a/spring-boot-mvc/src/test/java/com/baeldung/accessparamsjs/ControllerUnitTest.java b/spring-boot-mvc/src/test/java/com/baeldung/accessparamsjs/ControllerUnitTest.java index 31f6c89ffe..2dc62a20f6 100644 --- a/spring-boot-mvc/src/test/java/com/baeldung/accessparamsjs/ControllerUnitTest.java +++ b/spring-boot-mvc/src/test/java/com/baeldung/accessparamsjs/ControllerUnitTest.java @@ -20,9 +20,10 @@ public class ControllerUnitTest { private MockMvc mvc; @Test - public void whenRequestIndex_thenStatusOk() throws Exception { + public void whenRequestThymeleaf_thenStatusOk() throws Exception { mvc.perform(MockMvcRequestBuilders.get("/index") .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()); } + } diff --git a/spring-boot-ops/pom.xml b/spring-boot-ops/pom.xml index 9717a352d3..625b2ad188 100644 --- a/spring-boot-ops/pom.xml +++ b/spring-boot-ops/pom.xml @@ -2,10 +2,9 @@ 4.0.0 - spring-boot-ops - war spring-boot-ops + war Demo project for Spring Boot diff --git a/spring-boot-rest/README.md b/spring-boot-rest/README.md index 15e80ec515..3fbd21f24e 100644 --- a/spring-boot-rest/README.md +++ b/spring-boot-rest/README.md @@ -4,3 +4,5 @@ Module for the articles that are part of the Spring REST E-book: 2. [Error Handling for REST with Spring](http://www.baeldung.com/exception-handling-for-rest-with-spring) 3. [REST Pagination in Spring](http://www.baeldung.com/rest-api-pagination-in-spring) 4. [Build a REST API with Spring and Java Config](http://www.baeldung.com/building-a-restful-web-service-with-spring-and-java-based-configuration) +5. [HATEOAS for a Spring REST Service](http://www.baeldung.com/rest-api-discoverability-with-spring) +6. [REST API Discoverability and HATEOAS](http://www.baeldung.com/restful-web-service-discoverability) diff --git a/spring-rest-full/src/test/java/org/baeldung/common/web/AbstractDiscoverabilityLiveTest.java b/spring-boot-rest/src/test/java/com/baeldung/common/web/AbstractDiscoverabilityLiveTest.java similarity index 95% rename from spring-rest-full/src/test/java/org/baeldung/common/web/AbstractDiscoverabilityLiveTest.java rename to spring-boot-rest/src/test/java/com/baeldung/common/web/AbstractDiscoverabilityLiveTest.java index 96d796349a..fc581f2631 100644 --- a/spring-rest-full/src/test/java/org/baeldung/common/web/AbstractDiscoverabilityLiveTest.java +++ b/spring-boot-rest/src/test/java/com/baeldung/common/web/AbstractDiscoverabilityLiveTest.java @@ -1,4 +1,4 @@ -package org.baeldung.common.web; +package com.baeldung.common.web; import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; import static org.hamcrest.Matchers.containsString; @@ -8,8 +8,8 @@ import static org.junit.Assert.assertThat; import java.io.Serializable; -import org.baeldung.persistence.model.Foo; -import org.baeldung.web.util.HTTPLinkHeaderUtil; +import com.baeldung.persistence.model.Foo; +import com.baeldung.web.util.HTTPLinkHeaderUtil; import org.hamcrest.core.AnyOf; import org.junit.Test; import org.springframework.http.MediaType; diff --git a/spring-rest-full/src/test/java/org/baeldung/web/FooDiscoverabilityLiveTest.java b/spring-boot-rest/src/test/java/com/baeldung/web/FooDiscoverabilityLiveTest.java similarity index 83% rename from spring-rest-full/src/test/java/org/baeldung/web/FooDiscoverabilityLiveTest.java rename to spring-boot-rest/src/test/java/com/baeldung/web/FooDiscoverabilityLiveTest.java index a6577e4de8..0b98edaf03 100644 --- a/spring-rest-full/src/test/java/org/baeldung/web/FooDiscoverabilityLiveTest.java +++ b/spring-boot-rest/src/test/java/com/baeldung/web/FooDiscoverabilityLiveTest.java @@ -1,10 +1,10 @@ -package org.baeldung.web; +package com.baeldung.web; import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; -import org.baeldung.common.web.AbstractDiscoverabilityLiveTest; -import org.baeldung.persistence.model.Foo; -import org.baeldung.spring.ConfigIntegrationTest; +import com.baeldung.common.web.AbstractDiscoverabilityLiveTest; +import com.baeldung.persistence.model.Foo; +import com.baeldung.spring.ConfigIntegrationTest; import org.junit.runner.RunWith; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ContextConfiguration; diff --git a/spring-boot-rest/src/test/java/com/baeldung/web/LiveTestSuiteLiveTest.java b/spring-boot-rest/src/test/java/com/baeldung/web/LiveTestSuiteLiveTest.java index 1e2ddd5ec5..b7cceb9008 100644 --- a/spring-boot-rest/src/test/java/com/baeldung/web/LiveTestSuiteLiveTest.java +++ b/spring-boot-rest/src/test/java/com/baeldung/web/LiveTestSuiteLiveTest.java @@ -1,11 +1,13 @@ package com.baeldung.web; +import com.baeldung.web.FooDiscoverabilityLiveTest; import org.junit.runner.RunWith; import org.junit.runners.Suite; @RunWith(Suite.class) @Suite.SuiteClasses({ // @formatter:off + FooDiscoverabilityLiveTest.class, FooLiveTest.class ,FooPageableLiveTest.class }) // diff --git a/spring-boot-security/pom.xml b/spring-boot-security/pom.xml index b87189757a..aaa0fbf4c7 100644 --- a/spring-boot-security/pom.xml +++ b/spring-boot-security/pom.xml @@ -3,9 +3,9 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 spring-boot-security - jar spring-boot-security Spring Boot Security Auto-Configuration + jar parent-boot-1 diff --git a/spring-boot-testing/pom.xml b/spring-boot-testing/pom.xml index c2c886a4fe..caf48276b6 100644 --- a/spring-boot-testing/pom.xml +++ b/spring-boot-testing/pom.xml @@ -3,9 +3,9 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 spring-boot-testing - war spring-boot-testing This is simple boot application for demonstrating testing features. + war parent-boot-2 diff --git a/spring-boot-vue/pom.xml b/spring-boot-vue/pom.xml index d581b11d68..4e47a98d6f 100644 --- a/spring-boot-vue/pom.xml +++ b/spring-boot-vue/pom.xml @@ -2,13 +2,11 @@ 4.0.0 - com.baeldung spring-boot-vue 0.0.1-SNAPSHOT - jar - spring-boot-vue + jar Demo project for Spring Boot Vue project @@ -18,12 +16,6 @@ ../parent-boot-2 - - UTF-8 - UTF-8 - 1.8 - - org.springframework.boot @@ -52,5 +44,10 @@ + + UTF-8 + UTF-8 + 1.8 + diff --git a/spring-boot/README.MD b/spring-boot/README.MD index 2a6a935cc1..28123687fd 100644 --- a/spring-boot/README.MD +++ b/spring-boot/README.MD @@ -35,3 +35,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Load Spring Boot Properties From a JSON File](https://www.baeldung.com/spring-boot-json-properties) - [Display Auto-Configuration Report in Spring Boot](https://www.baeldung.com/spring-boot-auto-configuration-report) - [Injecting Git Information Into Spring](https://www.baeldung.com/spring-git-information) +- [Validation in Spring Boot](https://www.baeldung.com/spring-boot-bean-validation) diff --git a/spring-boot/pom.xml b/spring-boot/pom.xml index e6866b5a8f..2e463e0189 100644 --- a/spring-boot/pom.xml +++ b/spring-boot/pom.xml @@ -3,8 +3,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 spring-boot - war spring-boot + war This is simple boot application for Spring boot actuator test diff --git a/spring-boot/src/main/java/com/baeldung/jsondateformat/Contact.java b/spring-boot/src/main/java/com/baeldung/jsondateformat/Contact.java new file mode 100644 index 0000000000..f131d17196 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/jsondateformat/Contact.java @@ -0,0 +1,70 @@ +package com.baeldung.jsondateformat; + +import com.fasterxml.jackson.annotation.JsonFormat; + +import java.time.LocalDate; +import java.time.LocalDateTime; + +public class Contact { + + private String name; + private String address; + private String phone; + + @JsonFormat(pattern="yyyy-MM-dd") + private LocalDate birthday; + + @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss") + private LocalDateTime lastUpdate; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getAddress() { + return address; + } + + public void setAddress(String address) { + this.address = address; + } + + public String getPhone() { + return phone; + } + + public void setPhone(String phone) { + this.phone = phone; + } + + public LocalDate getBirthday() { + return birthday; + } + + public void setBirthday(LocalDate birthday) { + this.birthday = birthday; + } + + public LocalDateTime getLastUpdate() { + return lastUpdate; + } + + public void setLastUpdate(LocalDateTime lastUpdate) { + this.lastUpdate = lastUpdate; + } + + public Contact() { + } + + public Contact(String name, String address, String phone, LocalDate birthday, LocalDateTime lastUpdate) { + this.name = name; + this.address = address; + this.phone = phone; + this.birthday = birthday; + this.lastUpdate = lastUpdate; + } +} diff --git a/spring-boot/src/main/java/com/baeldung/jsondateformat/ContactApp.java b/spring-boot/src/main/java/com/baeldung/jsondateformat/ContactApp.java new file mode 100644 index 0000000000..79037e1038 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/jsondateformat/ContactApp.java @@ -0,0 +1,13 @@ +package com.baeldung.jsondateformat; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ContactApp { + + public static void main(String[] args) { + SpringApplication.run(ContactApp.class, args); + } + +} diff --git a/spring-boot/src/main/java/com/baeldung/jsondateformat/ContactAppConfig.java b/spring-boot/src/main/java/com/baeldung/jsondateformat/ContactAppConfig.java new file mode 100644 index 0000000000..7a20ebfa51 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/jsondateformat/ContactAppConfig.java @@ -0,0 +1,33 @@ +package com.baeldung.jsondateformat; + +import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer; +import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; + +import java.time.format.DateTimeFormatter; + +@Configuration +public class ContactAppConfig { + + private static final String dateFormat = "yyyy-MM-dd"; + + private static final String dateTimeFormat = "yyyy-MM-dd HH:mm:ss"; + + @Bean + @ConditionalOnProperty(value = "spring.jackson.date-format", matchIfMissing = true, havingValue = "none") + public Jackson2ObjectMapperBuilderCustomizer jsonCustomizer() { + return new Jackson2ObjectMapperBuilderCustomizer() { + @Override + public void customize(Jackson2ObjectMapperBuilder builder) { + builder.simpleDateFormat(dateTimeFormat); + builder.serializers(new LocalDateSerializer(DateTimeFormatter.ofPattern(dateFormat))); + builder.serializers(new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(dateTimeFormat))); + } + }; + } + +} diff --git a/spring-boot/src/main/java/com/baeldung/jsondateformat/ContactController.java b/spring-boot/src/main/java/com/baeldung/jsondateformat/ContactController.java new file mode 100644 index 0000000000..8894d82fc7 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/jsondateformat/ContactController.java @@ -0,0 +1,77 @@ +package com.baeldung.jsondateformat; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +@RestController +@RequestMapping(value = "/contacts") +public class ContactController { + + @GetMapping + public List getContacts() { + List contacts = new ArrayList<>(); + + Contact contact1 = new Contact("John Doe", "123 Sesame Street", "123-456-789", LocalDate.now(), LocalDateTime.now()); + Contact contact2 = new Contact("John Doe 2", "124 Sesame Street", "123-456-789", LocalDate.now(), LocalDateTime.now()); + Contact contact3 = new Contact("John Doe 3", "125 Sesame Street", "123-456-789", LocalDate.now(), LocalDateTime.now()); + + contacts.add(contact1); + contacts.add(contact2); + contacts.add(contact3); + + return contacts; + } + + @GetMapping("/javaUtilDate") + public List getContactsWithJavaUtilDate() { + List contacts = new ArrayList<>(); + + ContactWithJavaUtilDate contact1 = new ContactWithJavaUtilDate("John Doe", "123 Sesame Street", "123-456-789", new Date(), new Date()); + ContactWithJavaUtilDate contact2 = new ContactWithJavaUtilDate("John Doe 2", "124 Sesame Street", "123-456-789", new Date(), new Date()); + ContactWithJavaUtilDate contact3 = new ContactWithJavaUtilDate("John Doe 3", "125 Sesame Street", "123-456-789", new Date(), new Date()); + + contacts.add(contact1); + contacts.add(contact2); + contacts.add(contact3); + + return contacts; + } + + @GetMapping("/plain") + public List getPlainContacts() { + List contacts = new ArrayList<>(); + + PlainContact contact1 = new PlainContact("John Doe", "123 Sesame Street", "123-456-789", LocalDate.now(), LocalDateTime.now()); + PlainContact contact2 = new PlainContact("John Doe 2", "124 Sesame Street", "123-456-789", LocalDate.now(), LocalDateTime.now()); + PlainContact contact3 = new PlainContact("John Doe 3", "125 Sesame Street", "123-456-789", LocalDate.now(), LocalDateTime.now()); + + contacts.add(contact1); + contacts.add(contact2); + contacts.add(contact3); + + return contacts; + } + + @GetMapping("/plainWithJavaUtilDate") + public List getPlainContactsWithJavaUtilDate() { + List contacts = new ArrayList<>(); + + PlainContactWithJavaUtilDate contact1 = new PlainContactWithJavaUtilDate("John Doe", "123 Sesame Street", "123-456-789", new Date(), new Date()); + PlainContactWithJavaUtilDate contact2 = new PlainContactWithJavaUtilDate("John Doe 2", "124 Sesame Street", "123-456-789", new Date(), new Date()); + PlainContactWithJavaUtilDate contact3 = new PlainContactWithJavaUtilDate("John Doe 3", "125 Sesame Street", "123-456-789", new Date(), new Date()); + + contacts.add(contact1); + contacts.add(contact2); + contacts.add(contact3); + + return contacts; + } + +} diff --git a/spring-boot/src/main/java/com/baeldung/jsondateformat/ContactWithJavaUtilDate.java b/spring-boot/src/main/java/com/baeldung/jsondateformat/ContactWithJavaUtilDate.java new file mode 100644 index 0000000000..5a1c508098 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/jsondateformat/ContactWithJavaUtilDate.java @@ -0,0 +1,69 @@ +package com.baeldung.jsondateformat; + +import com.fasterxml.jackson.annotation.JsonFormat; + +import java.util.Date; + +public class ContactWithJavaUtilDate { + + private String name; + private String address; + private String phone; + + @JsonFormat(pattern="yyyy-MM-dd") + private Date birthday; + + @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss") + private Date lastUpdate; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getAddress() { + return address; + } + + public void setAddress(String address) { + this.address = address; + } + + public String getPhone() { + return phone; + } + + public void setPhone(String phone) { + this.phone = phone; + } + + public Date getBirthday() { + return birthday; + } + + public void setBirthday(Date birthday) { + this.birthday = birthday; + } + + public Date getLastUpdate() { + return lastUpdate; + } + + public void setLastUpdate(Date lastUpdate) { + this.lastUpdate = lastUpdate; + } + + public ContactWithJavaUtilDate() { + } + + public ContactWithJavaUtilDate(String name, String address, String phone, Date birthday, Date lastUpdate) { + this.name = name; + this.address = address; + this.phone = phone; + this.birthday = birthday; + this.lastUpdate = lastUpdate; + } +} diff --git a/spring-boot/src/main/java/com/baeldung/jsondateformat/PlainContact.java b/spring-boot/src/main/java/com/baeldung/jsondateformat/PlainContact.java new file mode 100644 index 0000000000..7e9e53d205 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/jsondateformat/PlainContact.java @@ -0,0 +1,66 @@ +package com.baeldung.jsondateformat; + +import java.time.LocalDate; +import java.time.LocalDateTime; + +public class PlainContact { + + private String name; + private String address; + private String phone; + + private LocalDate birthday; + + private LocalDateTime lastUpdate; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getAddress() { + return address; + } + + public void setAddress(String address) { + this.address = address; + } + + public String getPhone() { + return phone; + } + + public void setPhone(String phone) { + this.phone = phone; + } + + public LocalDate getBirthday() { + return birthday; + } + + public void setBirthday(LocalDate birthday) { + this.birthday = birthday; + } + + public LocalDateTime getLastUpdate() { + return lastUpdate; + } + + public void setLastUpdate(LocalDateTime lastUpdate) { + this.lastUpdate = lastUpdate; + } + + public PlainContact() { + } + + public PlainContact(String name, String address, String phone, LocalDate birthday, LocalDateTime lastUpdate) { + this.name = name; + this.address = address; + this.phone = phone; + this.birthday = birthday; + this.lastUpdate = lastUpdate; + } +} diff --git a/spring-boot/src/main/java/com/baeldung/jsondateformat/PlainContactWithJavaUtilDate.java b/spring-boot/src/main/java/com/baeldung/jsondateformat/PlainContactWithJavaUtilDate.java new file mode 100644 index 0000000000..daefb15543 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/jsondateformat/PlainContactWithJavaUtilDate.java @@ -0,0 +1,69 @@ +package com.baeldung.jsondateformat; + +import com.fasterxml.jackson.annotation.JsonFormat; + +import java.util.Date; + +public class PlainContactWithJavaUtilDate { + + private String name; + private String address; + private String phone; + + @JsonFormat(pattern="yyyy-MM-dd") + private Date birthday; + + @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss") + private Date lastUpdate; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getAddress() { + return address; + } + + public void setAddress(String address) { + this.address = address; + } + + public String getPhone() { + return phone; + } + + public void setPhone(String phone) { + this.phone = phone; + } + + public Date getBirthday() { + return birthday; + } + + public void setBirthday(Date birthday) { + this.birthday = birthday; + } + + public Date getLastUpdate() { + return lastUpdate; + } + + public void setLastUpdate(Date lastUpdate) { + this.lastUpdate = lastUpdate; + } + + public PlainContactWithJavaUtilDate() { + } + + public PlainContactWithJavaUtilDate(String name, String address, String phone, Date birthday, Date lastUpdate) { + this.name = name; + this.address = address; + this.phone = phone; + this.birthday = birthday; + this.lastUpdate = lastUpdate; + } +} diff --git a/spring-boot/src/main/java/org/baeldung/demo/boottest/Employee.java b/spring-boot/src/main/java/org/baeldung/demo/boottest/Employee.java index c1dd109f91..645ce2838a 100644 --- a/spring-boot/src/main/java/org/baeldung/demo/boottest/Employee.java +++ b/spring-boot/src/main/java/org/baeldung/demo/boottest/Employee.java @@ -6,6 +6,7 @@ import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import javax.validation.constraints.Size; +import java.util.Date; @Entity @Table(name = "person") @@ -25,6 +26,8 @@ public class Employee { @Size(min = 3, max = 20) private String name; + private Date birthday; + public Long getId() { return id; } diff --git a/spring-boot/src/main/resources/application.properties b/spring-boot/src/main/resources/application.properties index 6a52dd1f70..00c251d823 100644 --- a/spring-boot/src/main/resources/application.properties +++ b/spring-boot/src/main/resources/application.properties @@ -73,3 +73,5 @@ chaos.monkey.watcher.repository=false #Component watcher active chaos.monkey.watcher.component=false +spring.jackson.date-format=yyyy-MM-dd HH:mm:ss +spring.jackson.time-zone=Europe/Zagreb diff --git a/spring-boot/src/test/java/com/baeldung/jsondateformat/ContactAppIntegrationTest.java b/spring-boot/src/test/java/com/baeldung/jsondateformat/ContactAppIntegrationTest.java new file mode 100644 index 0000000000..86af985d8a --- /dev/null +++ b/spring-boot/src/test/java/com/baeldung/jsondateformat/ContactAppIntegrationTest.java @@ -0,0 +1,96 @@ +package com.baeldung.jsondateformat; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.http.ResponseEntity; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit4.SpringRunner; + +import java.io.IOException; +import java.text.ParseException; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; +import java.util.List; +import java.util.Map; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.DEFINED_PORT; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = DEFINED_PORT, classes = ContactApp.class) +@TestPropertySource(properties = { + "spring.jackson.date-format=yyyy-MM-dd HH:mm:ss" +}) +public class ContactAppIntegrationTest { + + private final ObjectMapper mapper = new ObjectMapper(); + + @Autowired + TestRestTemplate restTemplate; + + @Test + public void givenJsonFormatAnnotationAndJava8DateType_whenGet_thenReturnExpectedDateFormat() throws IOException, ParseException { + ResponseEntity response = restTemplate.getForEntity("http://localhost:8080/contacts", String.class); + + assertEquals(200, response.getStatusCodeValue()); + + List> respMap = mapper.readValue(response.getBody(), new TypeReference>>(){}); + + LocalDate birthdayDate = LocalDate.parse(respMap.get(0).get("birthday"), DateTimeFormatter.ofPattern("yyyy-MM-dd")); + LocalDateTime lastUpdateTime = LocalDateTime.parse(respMap.get(0).get("lastUpdate"), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); + + assertNotNull(birthdayDate); + assertNotNull(lastUpdateTime); + } + + @Test + public void givenJsonFormatAnnotationAndLegacyDateType_whenGet_thenReturnExpectedDateFormat() throws IOException { + ResponseEntity response = restTemplate.getForEntity("http://localhost:8080/contacts/javaUtilDate", String.class); + + assertEquals(200, response.getStatusCodeValue()); + + List> respMap = mapper.readValue(response.getBody(), new TypeReference>>(){}); + + LocalDate birthdayDate = LocalDate.parse(respMap.get(0).get("birthday"), DateTimeFormatter.ofPattern("yyyy-MM-dd")); + LocalDateTime lastUpdateTime = LocalDateTime.parse(respMap.get(0).get("lastUpdate"), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); + + assertNotNull(birthdayDate); + assertNotNull(lastUpdateTime); + } + + @Test + public void givenDefaultDateFormatInAppPropertiesAndLegacyDateType_whenGet_thenReturnExpectedDateFormat() throws IOException { + ResponseEntity response = restTemplate.getForEntity("http://localhost:8080/contacts/plainWithJavaUtilDate", String.class); + + assertEquals(200, response.getStatusCodeValue()); + + List> respMap = mapper.readValue(response.getBody(), new TypeReference>>(){}); + + LocalDate birthdayDate = LocalDate.parse(respMap.get(0).get("birthday"), DateTimeFormatter.ofPattern("yyyy-MM-dd")); + LocalDateTime lastUpdateTime = LocalDateTime.parse(respMap.get(0).get("lastUpdate"), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); + + assertNotNull(birthdayDate); + assertNotNull(lastUpdateTime); + } + + @Test(expected = DateTimeParseException.class) + public void givenDefaultDateFormatInAppPropertiesAndJava8DateType_whenGet_thenNotApplyFormat() throws IOException { + ResponseEntity response = restTemplate.getForEntity("http://localhost:8080/contacts/plain", String.class); + + assertEquals(200, response.getStatusCodeValue()); + + List> respMap = mapper.readValue(response.getBody(), new TypeReference>>(){}); + + LocalDate birthdayDate = LocalDate.parse(respMap.get(0).get("birthday"), DateTimeFormatter.ofPattern("yyyy-MM-dd")); + LocalDateTime lastUpdateTime = LocalDateTime.parse(respMap.get(0).get("lastUpdate"), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); + } + +} diff --git a/spring-boot/src/test/java/com/baeldung/jsondateformat/ContactAppWithObjectMapperCustomizerIntegrationTest.java b/spring-boot/src/test/java/com/baeldung/jsondateformat/ContactAppWithObjectMapperCustomizerIntegrationTest.java new file mode 100644 index 0000000000..554283d758 --- /dev/null +++ b/spring-boot/src/test/java/com/baeldung/jsondateformat/ContactAppWithObjectMapperCustomizerIntegrationTest.java @@ -0,0 +1,63 @@ +package com.baeldung.jsondateformat; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.http.ResponseEntity; +import org.springframework.test.context.junit4.SpringRunner; + +import java.io.IOException; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.List; +import java.util.Map; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.DEFINED_PORT; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = DEFINED_PORT, classes = ContactApp.class) +public class ContactAppWithObjectMapperCustomizerIntegrationTest { + + private final ObjectMapper mapper = new ObjectMapper(); + + @Autowired + TestRestTemplate restTemplate; + + @Test + public void givenDefaultDateFormatInAppPropertiesAndLegacyDateType_whenGet_thenReturnExpectedDateFormat() throws IOException { + ResponseEntity response = restTemplate.getForEntity("http://localhost:8080/contacts/plainWithJavaUtilDate", String.class); + + assertEquals(200, response.getStatusCodeValue()); + + List> respMap = mapper.readValue(response.getBody(), new TypeReference>>(){}); + + LocalDate birthdayDate = LocalDate.parse(respMap.get(0).get("birthday"), DateTimeFormatter.ofPattern("yyyy-MM-dd")); + LocalDateTime lastUpdateTime = LocalDateTime.parse(respMap.get(0).get("lastUpdate"), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); + + assertNotNull(birthdayDate); + assertNotNull(lastUpdateTime); + } + + @Test + public void givenDefaultDateFormatInAppPropertiesAndJava8DateType_whenGet_thenReturnExpectedDateFormat() throws IOException { + ResponseEntity response = restTemplate.getForEntity("http://localhost:8080/contacts/plain", String.class); + + assertEquals(200, response.getStatusCodeValue()); + + List> respMap = mapper.readValue(response.getBody(), new TypeReference>>(){}); + + LocalDate birthdayDate = LocalDate.parse(respMap.get(0).get("birthday"), DateTimeFormatter.ofPattern("yyyy-MM-dd")); + LocalDateTime lastUpdateTime = LocalDateTime.parse(respMap.get(0).get("lastUpdate"), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); + + assertNotNull(birthdayDate); + assertNotNull(lastUpdateTime); + } + +} diff --git a/spring-cloud-bus/pom.xml b/spring-cloud-bus/pom.xml index 784e4cbae6..fdaf8c024f 100644 --- a/spring-cloud-bus/pom.xml +++ b/spring-cloud-bus/pom.xml @@ -6,8 +6,8 @@ com.baeldung.spring.cloud spring-cloud-bus 1.0.0-SNAPSHOT - pom spring-cloud-bus + pom parent-boot-1 diff --git a/spring-cloud-bus/spring-cloud-config-client/pom.xml b/spring-cloud-bus/spring-cloud-config-client/pom.xml index b2b69303bf..4994626ba5 100644 --- a/spring-cloud-bus/spring-cloud-config-client/pom.xml +++ b/spring-cloud-bus/spring-cloud-config-client/pom.xml @@ -3,9 +3,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 spring-cloud-config-client - jar - spring-cloud-config-client + jar Demo Spring Cloud Config Client diff --git a/spring-cloud-bus/spring-cloud-config-server/pom.xml b/spring-cloud-bus/spring-cloud-config-server/pom.xml index f50b78ff18..51b447161e 100644 --- a/spring-cloud-bus/spring-cloud-config-server/pom.xml +++ b/spring-cloud-bus/spring-cloud-config-server/pom.xml @@ -3,9 +3,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 spring-cloud-config-server - jar - spring-cloud-config-server + jar Demo Spring Cloud Config Server diff --git a/spring-cloud-data-flow/batch-job/pom.xml b/spring-cloud-data-flow/batch-job/pom.xml index 7bc2909f4c..04187badb4 100644 --- a/spring-cloud-data-flow/batch-job/pom.xml +++ b/spring-cloud-data-flow/batch-job/pom.xml @@ -5,9 +5,9 @@ org.baeldung.spring.cloud batch-job 0.0.1-SNAPSHOT - jar batch-job Demo project for Spring Boot + jar parent-boot-1 diff --git a/spring-cloud-data-flow/data-flow-server/pom.xml b/spring-cloud-data-flow/data-flow-server/pom.xml index a02d2984c1..cf583c216a 100644 --- a/spring-cloud-data-flow/data-flow-server/pom.xml +++ b/spring-cloud-data-flow/data-flow-server/pom.xml @@ -2,11 +2,10 @@ 4.0.0 - data-flow-server 0.0.1-SNAPSHOT - jar data-flow-server + jar Demo project for Spring Boot diff --git a/spring-cloud-data-flow/data-flow-shell/pom.xml b/spring-cloud-data-flow/data-flow-shell/pom.xml index 3b155736c3..52cb204201 100644 --- a/spring-cloud-data-flow/data-flow-shell/pom.xml +++ b/spring-cloud-data-flow/data-flow-shell/pom.xml @@ -2,11 +2,10 @@ 4.0.0 - data-flow-shell 0.0.1-SNAPSHOT - jar data-flow-shell + jar Demo project for Spring Boot diff --git a/spring-cloud-data-flow/etl/customer-mongodb-sink/pom.xml b/spring-cloud-data-flow/etl/customer-mongodb-sink/pom.xml index 1f16a02a98..c8b609fd70 100644 --- a/spring-cloud-data-flow/etl/customer-mongodb-sink/pom.xml +++ b/spring-cloud-data-flow/etl/customer-mongodb-sink/pom.xml @@ -2,11 +2,9 @@ 4.0.0 - customer-mongodb-sink - jar - customer-mongodb-sink + jar Example ETL Load Project diff --git a/spring-cloud-data-flow/etl/customer-transform/pom.xml b/spring-cloud-data-flow/etl/customer-transform/pom.xml index ed281b420a..5b2eb05fc8 100644 --- a/spring-cloud-data-flow/etl/customer-transform/pom.xml +++ b/spring-cloud-data-flow/etl/customer-transform/pom.xml @@ -2,11 +2,9 @@ 4.0.0 - customer-transform - jar - customer-transform + jar Example transform ETL step diff --git a/spring-cloud-data-flow/etl/pom.xml b/spring-cloud-data-flow/etl/pom.xml index 7d5040e8ad..55b2f34289 100644 --- a/spring-cloud-data-flow/etl/pom.xml +++ b/spring-cloud-data-flow/etl/pom.xml @@ -1,9 +1,9 @@ 4.0.0 - etl etl 0.0.1-SNAPSHOT + etl pom diff --git a/spring-cloud-data-flow/log-sink/pom.xml b/spring-cloud-data-flow/log-sink/pom.xml index 69de679c2a..ecabb91a98 100644 --- a/spring-cloud-data-flow/log-sink/pom.xml +++ b/spring-cloud-data-flow/log-sink/pom.xml @@ -2,11 +2,10 @@ 4.0.0 - log-sink 0.0.1-SNAPSHOT - jar log-sink + jar Demo project for Spring Boot diff --git a/spring-cloud-data-flow/pom.xml b/spring-cloud-data-flow/pom.xml index b5ef5d2c2a..daf8ebd2c8 100644 --- a/spring-cloud-data-flow/pom.xml +++ b/spring-cloud-data-flow/pom.xml @@ -3,8 +3,8 @@ 4.0.0 spring-cloud-data-flow 0.0.1-SNAPSHOT - pom spring-cloud-data-flow + pom com.baeldung diff --git a/spring-cloud-data-flow/time-processor/pom.xml b/spring-cloud-data-flow/time-processor/pom.xml index e630df1865..de354ca698 100644 --- a/spring-cloud-data-flow/time-processor/pom.xml +++ b/spring-cloud-data-flow/time-processor/pom.xml @@ -2,11 +2,10 @@ 4.0.0 - time-processor 0.0.1-SNAPSHOT - jar time-processor + jar Demo project for Spring Boot diff --git a/spring-cloud-data-flow/time-source/pom.xml b/spring-cloud-data-flow/time-source/pom.xml index 649af32cf0..a4d06e13d2 100644 --- a/spring-cloud-data-flow/time-source/pom.xml +++ b/spring-cloud-data-flow/time-source/pom.xml @@ -2,7 +2,6 @@ 4.0.0 - time-source 0.0.1-SNAPSHOT jar diff --git a/spring-cloud/pom.xml b/spring-cloud/pom.xml index 39cda888c5..baf86a4386 100644 --- a/spring-cloud/pom.xml +++ b/spring-cloud/pom.xml @@ -5,8 +5,8 @@ com.baeldung.spring.cloud spring-cloud 1.0.0-SNAPSHOT - pom spring-cloud + pom com.baeldung diff --git a/spring-cloud/spring-cloud-archaius/additional-sources-simple/pom.xml b/spring-cloud/spring-cloud-archaius/additional-sources-simple/pom.xml index 1ae6d543fb..cc100833cd 100644 --- a/spring-cloud/spring-cloud-archaius/additional-sources-simple/pom.xml +++ b/spring-cloud/spring-cloud-archaius/additional-sources-simple/pom.xml @@ -5,8 +5,8 @@ 4.0.0 additional-sources-simple 1.0.0-SNAPSHOT - jar additional-sources-simple + jar com.baeldung.spring.cloud diff --git a/spring-cloud/spring-cloud-archaius/basic-config/pom.xml b/spring-cloud/spring-cloud-archaius/basic-config/pom.xml index b5b091712d..be77eeb71c 100644 --- a/spring-cloud/spring-cloud-archaius/basic-config/pom.xml +++ b/spring-cloud/spring-cloud-archaius/basic-config/pom.xml @@ -5,8 +5,8 @@ 4.0.0 basic-config 1.0.0-SNAPSHOT - jar basic-config + jar com.baeldung.spring.cloud diff --git a/spring-cloud/spring-cloud-archaius/extra-configs/pom.xml b/spring-cloud/spring-cloud-archaius/extra-configs/pom.xml index 2f3f2b084a..c3c830f197 100644 --- a/spring-cloud/spring-cloud-archaius/extra-configs/pom.xml +++ b/spring-cloud/spring-cloud-archaius/extra-configs/pom.xml @@ -5,8 +5,8 @@ 4.0.0 extra-configs 1.0.0-SNAPSHOT - jar extra-configs + jar com.baeldung.spring.cloud diff --git a/spring-cloud/spring-cloud-aws/pom.xml b/spring-cloud/spring-cloud-aws/pom.xml index 7edabd03f5..26c407a77e 100644 --- a/spring-cloud/spring-cloud-aws/pom.xml +++ b/spring-cloud/spring-cloud-aws/pom.xml @@ -4,9 +4,9 @@ 4.0.0 com.baeldung.spring.cloud spring-cloud-aws - jar spring-cloud-aws Spring Cloud AWS Examples + jar parent-boot-1 diff --git a/spring-cloud/spring-cloud-consul/pom.xml b/spring-cloud/spring-cloud-consul/pom.xml index 2a2714d597..1ca3d703b5 100644 --- a/spring-cloud/spring-cloud-consul/pom.xml +++ b/spring-cloud/spring-cloud-consul/pom.xml @@ -4,8 +4,8 @@ 4.0.0 org.baeldung spring-cloud-consul - jar spring-cloud-consul + jar com.baeldung.spring.cloud diff --git a/spring-cloud/spring-cloud-contract/pom.xml b/spring-cloud/spring-cloud-contract/pom.xml index 3563d0ee58..4d4e8ad2c3 100644 --- a/spring-cloud/spring-cloud-contract/pom.xml +++ b/spring-cloud/spring-cloud-contract/pom.xml @@ -2,11 +2,11 @@ 4.0.0 - pom com.baeldung.spring.cloud spring-cloud-contract 1.0.0-SNAPSHOT spring-cloud-contract + pom com.baeldung.spring.cloud diff --git a/spring-cloud/spring-cloud-contract/spring-cloud-contract-consumer/pom.xml b/spring-cloud/spring-cloud-contract/spring-cloud-contract-consumer/pom.xml index fa9bf51bc3..7d00a9f463 100644 --- a/spring-cloud/spring-cloud-contract/spring-cloud-contract-consumer/pom.xml +++ b/spring-cloud/spring-cloud-contract/spring-cloud-contract-consumer/pom.xml @@ -2,14 +2,12 @@ 4.0.0 - com.baeldung.spring.cloud spring-cloud-contract-consumer 1.0.0-SNAPSHOT - jar - spring-cloud-contract-consumer Spring Cloud Consumer Sample + jar com.baeldung.spring.cloud @@ -18,12 +16,6 @@ .. - - UTF-8 - UTF-8 - 1.8 - - org.springframework.cloud @@ -54,4 +46,10 @@ test + + + UTF-8 + UTF-8 + 1.8 + diff --git a/spring-cloud/spring-cloud-contract/spring-cloud-contract-producer/pom.xml b/spring-cloud/spring-cloud-contract/spring-cloud-contract-producer/pom.xml index ac27dbb645..a6bd4e1be4 100644 --- a/spring-cloud/spring-cloud-contract/spring-cloud-contract-producer/pom.xml +++ b/spring-cloud/spring-cloud-contract/spring-cloud-contract-producer/pom.xml @@ -2,14 +2,12 @@ 4.0.0 - com.baeldung.spring.cloud spring-cloud-contract-producer 1.0.0-SNAPSHOT - jar - spring-cloud-contract-producer Spring Cloud Producer Sample + jar com.baeldung.spring.cloud @@ -18,13 +16,6 @@ .. - - UTF-8 - UTF-8 - 1.8 - Edgware.SR1 - - org.springframework.cloud @@ -70,5 +61,11 @@ + + UTF-8 + UTF-8 + 1.8 + Edgware.SR1 + diff --git a/spring-cloud/spring-cloud-eureka/pom.xml b/spring-cloud/spring-cloud-eureka/pom.xml index 99d8c0ed40..b59b415ee2 100644 --- a/spring-cloud/spring-cloud-eureka/pom.xml +++ b/spring-cloud/spring-cloud-eureka/pom.xml @@ -5,9 +5,9 @@ com.baeldung.spring.cloud spring-cloud-eureka 1.0.0-SNAPSHOT - pom spring-cloud-eureka Spring Cloud Eureka Server and Sample Clients + pom spring-cloud-eureka-server diff --git a/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client/pom.xml b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client/pom.xml index 5378095af0..c2d64ce237 100644 --- a/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client/pom.xml +++ b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client/pom.xml @@ -4,9 +4,9 @@ 4.0.0 spring-cloud-eureka-client 1.0.0-SNAPSHOT - jar spring-cloud-eureka-client Spring Cloud Eureka Sample Client + jar com.baeldung.spring.cloud diff --git a/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-feign-client/pom.xml b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-feign-client/pom.xml index f2057c8a76..84ba1e28fe 100644 --- a/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-feign-client/pom.xml +++ b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-feign-client/pom.xml @@ -4,9 +4,9 @@ 4.0.0 spring-cloud-eureka-feign-client 1.0.0-SNAPSHOT - jar spring-cloud-eureka-feign-client Spring Cloud Eureka - Sample Feign Client + jar com.baeldung.spring.cloud diff --git a/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-server/pom.xml b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-server/pom.xml index 587aed6c49..f51f6d229d 100644 --- a/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-server/pom.xml +++ b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-server/pom.xml @@ -4,9 +4,9 @@ 4.0.0 spring-cloud-eureka-server 1.0.0-SNAPSHOT - jar spring-cloud-eureka-server Spring Cloud Eureka Server Demo + jar com.baeldung.spring.cloud diff --git a/spring-cloud/spring-cloud-functions/pom.xml b/spring-cloud/spring-cloud-functions/pom.xml index 5686fc8c64..9396ad0a55 100644 --- a/spring-cloud/spring-cloud-functions/pom.xml +++ b/spring-cloud/spring-cloud-functions/pom.xml @@ -6,9 +6,9 @@ com.baeldung.spring spring-cloud-functions 0.0.1-SNAPSHOT - jar spring-cloud-functions Demo project for Spring Cloud Function + jar org.springframework.boot diff --git a/spring-cloud/spring-cloud-hystrix/feign-rest-consumer/pom.xml b/spring-cloud/spring-cloud-hystrix/feign-rest-consumer/pom.xml index 11b9275b46..a345d6856b 100644 --- a/spring-cloud/spring-cloud-hystrix/feign-rest-consumer/pom.xml +++ b/spring-cloud/spring-cloud-hystrix/feign-rest-consumer/pom.xml @@ -5,8 +5,8 @@ 4.0.0 feign-rest-consumer 1.0.0-SNAPSHOT - jar feign-rest-consumer + jar com.baeldung.spring.cloud diff --git a/spring-cloud/spring-cloud-hystrix/pom.xml b/spring-cloud/spring-cloud-hystrix/pom.xml index 266644b4c3..51f6a4e82b 100644 --- a/spring-cloud/spring-cloud-hystrix/pom.xml +++ b/spring-cloud/spring-cloud-hystrix/pom.xml @@ -6,8 +6,8 @@ com.baeldung.spring.cloud spring-cloud-hystrix 1.0.0-SNAPSHOT - pom spring-cloud-hystrix + pom com.baeldung.spring.cloud diff --git a/spring-cloud/spring-cloud-hystrix/rest-consumer/pom.xml b/spring-cloud/spring-cloud-hystrix/rest-consumer/pom.xml index 651f80fc92..ec2f6d1e55 100644 --- a/spring-cloud/spring-cloud-hystrix/rest-consumer/pom.xml +++ b/spring-cloud/spring-cloud-hystrix/rest-consumer/pom.xml @@ -2,11 +2,10 @@ 4.0.0 - rest-consumer 1.0.0-SNAPSHOT - jar rest-consumer + jar com.baeldung.spring.cloud diff --git a/spring-cloud/spring-cloud-hystrix/rest-producer/pom.xml b/spring-cloud/spring-cloud-hystrix/rest-producer/pom.xml index 8437ac6833..0f84fb7e23 100644 --- a/spring-cloud/spring-cloud-hystrix/rest-producer/pom.xml +++ b/spring-cloud/spring-cloud-hystrix/rest-producer/pom.xml @@ -2,12 +2,10 @@ 4.0.0 - rest-producer 1.0.0-SNAPSHOT - jar - rest-producer + jar com.baeldung.spring.cloud diff --git a/spring-cloud/spring-cloud-kubernetes/liveness-example/pom.xml b/spring-cloud/spring-cloud-kubernetes/liveness-example/pom.xml index e963dafe67..9254718c81 100644 --- a/spring-cloud/spring-cloud-kubernetes/liveness-example/pom.xml +++ b/spring-cloud/spring-cloud-kubernetes/liveness-example/pom.xml @@ -2,6 +2,9 @@ + 4.0.0 + liveness-example + 1.0-SNAPSHOT org.springframework.boot @@ -10,17 +13,6 @@ - 4.0.0 - - liveness-example - 1.0-SNAPSHOT - - - UTF-8 - UTF-8 - 1.8 - - org.springframework.boot @@ -48,4 +40,10 @@ + + UTF-8 + UTF-8 + 1.8 + + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-kubernetes/pom.xml b/spring-cloud/spring-cloud-kubernetes/pom.xml index de0718633e..51e1456358 100644 --- a/spring-cloud/spring-cloud-kubernetes/pom.xml +++ b/spring-cloud/spring-cloud-kubernetes/pom.xml @@ -5,15 +5,8 @@ com.baeldung.spring.cloud spring-cloud-kubernetes 1.0-SNAPSHOT - pom spring-cloud-kubernetes - - - demo-frontend - demo-backend - liveness-example - readiness-example - + pom parent-boot-1 @@ -21,5 +14,12 @@ 0.0.1-SNAPSHOT ../../parent-boot-1 + + + demo-frontend + demo-backend + liveness-example + readiness-example + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-kubernetes/readiness-example/pom.xml b/spring-cloud/spring-cloud-kubernetes/readiness-example/pom.xml index fa85120d21..e22bb0a9fe 100644 --- a/spring-cloud/spring-cloud-kubernetes/readiness-example/pom.xml +++ b/spring-cloud/spring-cloud-kubernetes/readiness-example/pom.xml @@ -2,22 +2,16 @@ + 4.0.0 + readiness-example + 1.0-SNAPSHOT + org.springframework.boot spring-boot-starter-parent 1.5.17.RELEASE - 4.0.0 - - readiness-example - 1.0-SNAPSHOT - - - UTF-8 - UTF-8 - 1.8 - @@ -46,4 +40,10 @@ + + UTF-8 + UTF-8 + 1.8 + + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-rest/pom.xml b/spring-cloud/spring-cloud-rest/pom.xml index f78f58caa0..7f316f47fc 100644 --- a/spring-cloud/spring-cloud-rest/pom.xml +++ b/spring-cloud/spring-cloud-rest/pom.xml @@ -5,8 +5,8 @@ org.baeldung spring-cloud-rest 1.0.0-SNAPSHOT - pom spring-cloud-rest + pom com.baeldung.spring.cloud diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-books-api/pom.xml b/spring-cloud/spring-cloud-rest/spring-cloud-rest-books-api/pom.xml index d1139b1fa4..a196ed8531 100644 --- a/spring-cloud/spring-cloud-rest/spring-cloud-rest-books-api/pom.xml +++ b/spring-cloud/spring-cloud-rest/spring-cloud-rest-books-api/pom.xml @@ -5,9 +5,9 @@ org.baeldung spring-cloud-rest-books-api 0.0.1-SNAPSHOT - jar spring-cloud-rest-books-api Simple books API + jar parent-boot-1 diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-config-server/pom.xml b/spring-cloud/spring-cloud-rest/spring-cloud-rest-config-server/pom.xml index a43829666c..7a71cdb13b 100644 --- a/spring-cloud/spring-cloud-rest/spring-cloud-rest-config-server/pom.xml +++ b/spring-cloud/spring-cloud-rest/spring-cloud-rest-config-server/pom.xml @@ -5,9 +5,9 @@ org.baeldung spring-cloud-rest-config-server 0.0.1-SNAPSHOT - jar spring-cloud-rest-config-server Spring Cloud REST configuration server + jar parent-boot-1 diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-discovery-server/pom.xml b/spring-cloud/spring-cloud-rest/spring-cloud-rest-discovery-server/pom.xml index 5b656d4342..7ce04f2815 100644 --- a/spring-cloud/spring-cloud-rest/spring-cloud-rest-discovery-server/pom.xml +++ b/spring-cloud/spring-cloud-rest/spring-cloud-rest-discovery-server/pom.xml @@ -5,9 +5,9 @@ org.baeldung spring-cloud-rest-discovery-server 0.0.1-SNAPSHOT - jar spring-cloud-rest-discovery-server Spring Cloud REST server + jar parent-boot-1 diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-reviews-api/pom.xml b/spring-cloud/spring-cloud-rest/spring-cloud-rest-reviews-api/pom.xml index ef969e04e5..cd7749460e 100644 --- a/spring-cloud/spring-cloud-rest/spring-cloud-rest-reviews-api/pom.xml +++ b/spring-cloud/spring-cloud-rest/spring-cloud-rest-reviews-api/pom.xml @@ -5,9 +5,9 @@ org.baeldung spring-cloud-rest-reviews-api 0.0.1-SNAPSHOT - jar spring-cloud-rest-reviews-api Simple reviews API + jar parent-boot-1 diff --git a/spring-cloud/spring-cloud-ribbon-client/pom.xml b/spring-cloud/spring-cloud-ribbon-client/pom.xml index 12125f4cf3..f677009a41 100644 --- a/spring-cloud/spring-cloud-ribbon-client/pom.xml +++ b/spring-cloud/spring-cloud-ribbon-client/pom.xml @@ -4,8 +4,8 @@ com.baeldung spring-cloud-ribbon-client 0.0.1-SNAPSHOT - jar spring-cloud-ribbon-client + jar Introduction to Spring Cloud Rest Client with Netflix Ribbon diff --git a/spring-cloud/spring-cloud-security/auth-client/pom.xml b/spring-cloud/spring-cloud-security/auth-client/pom.xml index 5d15c6c726..4f64f470f0 100644 --- a/spring-cloud/spring-cloud-security/auth-client/pom.xml +++ b/spring-cloud/spring-cloud-security/auth-client/pom.xml @@ -3,8 +3,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 auth-client - jar auth-client + jar Spring Cloud Security APP Client Module diff --git a/spring-cloud/spring-cloud-security/auth-resource/pom.xml b/spring-cloud/spring-cloud-security/auth-resource/pom.xml index 0367baa990..22ee0528c3 100644 --- a/spring-cloud/spring-cloud-security/auth-resource/pom.xml +++ b/spring-cloud/spring-cloud-security/auth-resource/pom.xml @@ -2,11 +2,9 @@ 4.0.0 - auth-resource - jar - auth-resource + jar Spring Cloud Security APP Resource Module diff --git a/spring-cloud/spring-cloud-security/pom.xml b/spring-cloud/spring-cloud-security/pom.xml index 1cf8751548..2eecf579a5 100644 --- a/spring-cloud/spring-cloud-security/pom.xml +++ b/spring-cloud/spring-cloud-security/pom.xml @@ -3,9 +3,9 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 spring-cloud-security - pom 1.0.0-SNAPSHOT spring-cloud-security + pom parent-boot-1 diff --git a/spring-cloud/spring-cloud-stream-starters/twitterhdfs/pom.xml b/spring-cloud/spring-cloud-stream-starters/twitterhdfs/pom.xml index 6f582576d8..8846773338 100644 --- a/spring-cloud/spring-cloud-stream-starters/twitterhdfs/pom.xml +++ b/spring-cloud/spring-cloud-stream-starters/twitterhdfs/pom.xml @@ -4,9 +4,9 @@ 4.0.0 com.baeldung.twitterhdfs twitterhdfs - jar 1.0.0-SNAPSHOT twitterhdfs + jar parent-boot-1 diff --git a/spring-cloud/spring-cloud-stream/pom.xml b/spring-cloud/spring-cloud-stream/pom.xml index d62b959131..76a51cc3ca 100644 --- a/spring-cloud/spring-cloud-stream/pom.xml +++ b/spring-cloud/spring-cloud-stream/pom.xml @@ -4,8 +4,8 @@ 4.0.0 org.baeldung spring-cloud-stream - pom spring-cloud-stream + pom com.baeldung.spring.cloud diff --git a/spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/pom.xml b/spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/pom.xml index fa14d04087..1649cfc0b5 100644 --- a/spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/pom.xml +++ b/spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/pom.xml @@ -3,9 +3,9 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 spring-cloud-stream-rabbit - jar spring-cloud-stream-rabbit Simple Spring Cloud Stream + jar org.baeldung diff --git a/spring-cloud/spring-cloud-task/pom.xml b/spring-cloud/spring-cloud-task/pom.xml index 748cc378f1..7c2c0d17f2 100644 --- a/spring-cloud/spring-cloud-task/pom.xml +++ b/spring-cloud/spring-cloud-task/pom.xml @@ -5,8 +5,8 @@ com.baeldung.spring.cloud spring-cloud-task 1.0.0-SNAPSHOT - pom spring-cloud-task + pom parent-boot-1 diff --git a/spring-cloud/spring-cloud-task/springcloudtasksink/pom.xml b/spring-cloud/spring-cloud-task/springcloudtasksink/pom.xml index ca0de342a9..03bfe7b1cb 100644 --- a/spring-cloud/spring-cloud-task/springcloudtasksink/pom.xml +++ b/spring-cloud/spring-cloud-task/springcloudtasksink/pom.xml @@ -3,8 +3,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 SpringCloudTaskSink - jar SpringCloudTaskSink + jar Demo project for Spring Boot diff --git a/spring-cloud/spring-cloud-vault/pom.xml b/spring-cloud/spring-cloud-vault/pom.xml index 363de6e107..abfb0d06f3 100644 --- a/spring-cloud/spring-cloud-vault/pom.xml +++ b/spring-cloud/spring-cloud-vault/pom.xml @@ -2,12 +2,10 @@ 4.0.0 - org.baeldung.spring.cloud spring-cloud-vault - jar - spring-cloud-vault + jar Demo project for Spring Boot diff --git a/spring-cloud/spring-cloud-zookeeper/Greeting/pom.xml b/spring-cloud/spring-cloud-zookeeper/Greeting/pom.xml index 9243766b77..2da47cf40d 100644 --- a/spring-cloud/spring-cloud-zookeeper/Greeting/pom.xml +++ b/spring-cloud/spring-cloud-zookeeper/Greeting/pom.xml @@ -3,8 +3,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 Greeting - jar Greeting + jar com.baeldung.spring.cloud diff --git a/spring-cloud/spring-cloud-zookeeper/pom.xml b/spring-cloud/spring-cloud-zookeeper/pom.xml index 9661f2b71a..4ea9b22e9d 100644 --- a/spring-cloud/spring-cloud-zookeeper/pom.xml +++ b/spring-cloud/spring-cloud-zookeeper/pom.xml @@ -3,8 +3,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 spring-cloud-zookeeper - pom spring-cloud-zookeeper + pom com.baeldung.spring.cloud diff --git a/spring-cloud/spring-cloud-zuul-eureka-integration/bin/eureka-client/pom.xml b/spring-cloud/spring-cloud-zuul-eureka-integration/bin/eureka-client/pom.xml index 6a00b279c8..9c075ebfe3 100644 --- a/spring-cloud/spring-cloud-zuul-eureka-integration/bin/eureka-client/pom.xml +++ b/spring-cloud/spring-cloud-zuul-eureka-integration/bin/eureka-client/pom.xml @@ -4,9 +4,8 @@ 4.0.0 eureka-client 1.0.0-SNAPSHOT - jar - Spring Cloud Eureka Client + jar Spring Cloud Eureka Sample Client diff --git a/spring-cloud/spring-cloud-zuul-eureka-integration/bin/eureka-server/pom.xml b/spring-cloud/spring-cloud-zuul-eureka-integration/bin/eureka-server/pom.xml index 9db3204f64..97933210de 100644 --- a/spring-cloud/spring-cloud-zuul-eureka-integration/bin/eureka-server/pom.xml +++ b/spring-cloud/spring-cloud-zuul-eureka-integration/bin/eureka-server/pom.xml @@ -2,12 +2,10 @@ 4.0.0 - eureka-server 1.0.0-SNAPSHOT - jar - Spring Cloud Eureka Server + jar Spring Cloud Eureka Server Demo @@ -27,7 +25,6 @@ commons-configuration ${commons-config.version}
- diff --git a/spring-cloud/spring-cloud-zuul-eureka-integration/bin/pom.xml b/spring-cloud/spring-cloud-zuul-eureka-integration/bin/pom.xml index 7e864499d4..fbae051277 100644 --- a/spring-cloud/spring-cloud-zuul-eureka-integration/bin/pom.xml +++ b/spring-cloud/spring-cloud-zuul-eureka-integration/bin/pom.xml @@ -1,14 +1,13 @@ - 4.0.0 - + 4.0.0 com.baeldung.spring.cloud spring-cloud-zuul-eureka-integration 1.0.0-SNAPSHOT - pom Spring Cloud Zuul and Eureka Integration Spring Cloud Zuul and Eureka Integration + pom com.baeldung.spring.cloud @@ -17,16 +16,16 @@ .. + + zuul-server + eureka-server + eureka-client + + UTF-8 3.7.0 1.4.2.RELEASE 1.10 - - - zuul-server - eureka-server - eureka-client - diff --git a/spring-cloud/spring-cloud-zuul-eureka-integration/bin/zuul-server/pom.xml b/spring-cloud/spring-cloud-zuul-eureka-integration/bin/zuul-server/pom.xml index 40462c57f4..1c2cb85da5 100644 --- a/spring-cloud/spring-cloud-zuul-eureka-integration/bin/zuul-server/pom.xml +++ b/spring-cloud/spring-cloud-zuul-eureka-integration/bin/zuul-server/pom.xml @@ -1,12 +1,14 @@ 4.0.0 + zuul-server + com.baeldung.spring.cloud spring-cloud-zuul-eureka-integration 1.0.0-SNAPSHOT - zuul-server + org.springframework.boot @@ -30,6 +32,7 @@ spring-boot-starter-security + diff --git a/spring-cloud/spring-cloud-zuul-eureka-integration/eureka-client/pom.xml b/spring-cloud/spring-cloud-zuul-eureka-integration/eureka-client/pom.xml index c4f7ae704a..0b479ec226 100644 --- a/spring-cloud/spring-cloud-zuul-eureka-integration/eureka-client/pom.xml +++ b/spring-cloud/spring-cloud-zuul-eureka-integration/eureka-client/pom.xml @@ -4,8 +4,8 @@ 4.0.0 eureka-client 1.0.0-SNAPSHOT - jar eureka-client + jar Spring Cloud Eureka Sample Client diff --git a/spring-cloud/spring-cloud-zuul-eureka-integration/eureka-server/pom.xml b/spring-cloud/spring-cloud-zuul-eureka-integration/eureka-server/pom.xml index 0256ee7000..eea22779a6 100644 --- a/spring-cloud/spring-cloud-zuul-eureka-integration/eureka-server/pom.xml +++ b/spring-cloud/spring-cloud-zuul-eureka-integration/eureka-server/pom.xml @@ -4,8 +4,8 @@ 4.0.0 eureka-server 1.0.0-SNAPSHOT - jar eureka-server + jar Spring Cloud Eureka Server Demo diff --git a/spring-cloud/spring-cloud-zuul-eureka-integration/pom.xml b/spring-cloud/spring-cloud-zuul-eureka-integration/pom.xml index edd7b9d99e..7fe0cf6ac3 100644 --- a/spring-cloud/spring-cloud-zuul-eureka-integration/pom.xml +++ b/spring-cloud/spring-cloud-zuul-eureka-integration/pom.xml @@ -6,8 +6,8 @@ com.baeldung.spring.cloud spring-cloud-zuul-eureka-integration 1.0.0-SNAPSHOT - pom spring-cloud-zuul-eureka-integration + pom Spring Cloud Zuul and Eureka Integration diff --git a/spring-cloud/spring-cloud-zuul/pom.xml b/spring-cloud/spring-cloud-zuul/pom.xml index e387bacb4e..97e67f16d8 100644 --- a/spring-cloud/spring-cloud-zuul/pom.xml +++ b/spring-cloud/spring-cloud-zuul/pom.xml @@ -2,13 +2,11 @@ 4.0.0 - com.baeldung.spring.cloud spring-cloud-zuul 0.0.1-SNAPSHOT - jar - spring-cloud-zuul + jar Demo project for Spring Boot @@ -18,13 +16,6 @@ - - UTF-8 - UTF-8 - 1.8 - Finchley.SR1 - - org.springframework.boot @@ -76,5 +67,11 @@ - + + UTF-8 + UTF-8 + 1.8 + Finchley.SR1 + + diff --git a/spring-core/README.md b/spring-core/README.md index e5c359c11b..dcc15a4cb9 100644 --- a/spring-core/README.md +++ b/spring-core/README.md @@ -22,3 +22,4 @@ - [Spring Application Context Events](https://www.baeldung.com/spring-context-events) - [Unsatisfied Dependency in Spring](https://www.baeldung.com/spring-unsatisfied-dependency) - [What is a Spring Bean?](https://www.baeldung.com/spring-bean) +- [Spring PostConstruct and PreDestroy Annotations](https://www.baeldung.com/spring-postconstruct-predestroy) diff --git a/spring-core/pom.xml b/spring-core/pom.xml index f1e2e2a748..46f777c020 100644 --- a/spring-core/pom.xml +++ b/spring-core/pom.xml @@ -5,8 +5,8 @@ com.baeldung spring-core 0.0.1-SNAPSHOT - war spring-core + war com.baeldung diff --git a/spring-core/src/main/java/com/baeldung/di/spring/Account.java b/spring-core/src/main/java/com/baeldung/di/spring/Account.java new file mode 100644 index 0000000000..6d9883bda5 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/di/spring/Account.java @@ -0,0 +1,27 @@ +package com.baeldung.di.spring; + +import org.springframework.stereotype.Component; + +@Component +public class Account { + + private String accountNumber; + private String type; + + public String getAccountNumber() { + return accountNumber; + } + + public void setAccountNumber(String accountNumber) { + this.accountNumber = accountNumber; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + +} diff --git a/spring-core/src/main/java/com/baeldung/di/spring/AccountService.java b/spring-core/src/main/java/com/baeldung/di/spring/AccountService.java new file mode 100644 index 0000000000..75ba6bb3eb --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/di/spring/AccountService.java @@ -0,0 +1,5 @@ +package com.baeldung.di.spring; + +public interface AccountService { + +} diff --git a/spring-core/src/main/java/com/baeldung/di/spring/AccountServiceImpl.java b/spring-core/src/main/java/com/baeldung/di/spring/AccountServiceImpl.java new file mode 100644 index 0000000000..4a4baf7d92 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/di/spring/AccountServiceImpl.java @@ -0,0 +1,8 @@ +package com.baeldung.di.spring; + +import org.springframework.stereotype.Component; + +@Component +public class AccountServiceImpl implements AccountService { + +} diff --git a/spring-core/src/main/java/com/baeldung/di/spring/AudioBookService.java b/spring-core/src/main/java/com/baeldung/di/spring/AudioBookService.java new file mode 100644 index 0000000000..c82e5ed282 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/di/spring/AudioBookService.java @@ -0,0 +1,5 @@ +package com.baeldung.di.spring; + +public interface AudioBookService { + +} diff --git a/spring-core/src/main/java/com/baeldung/di/spring/AudioBookServiceImpl.java b/spring-core/src/main/java/com/baeldung/di/spring/AudioBookServiceImpl.java new file mode 100644 index 0000000000..53a544b65a --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/di/spring/AudioBookServiceImpl.java @@ -0,0 +1,5 @@ +package com.baeldung.di.spring; + +public class AudioBookServiceImpl implements AudioBookService { + +} diff --git a/spring-core/src/main/java/com/baeldung/di/spring/AuthorService.java b/spring-core/src/main/java/com/baeldung/di/spring/AuthorService.java new file mode 100644 index 0000000000..cfb525ddf9 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/di/spring/AuthorService.java @@ -0,0 +1,5 @@ +package com.baeldung.di.spring; + +public interface AuthorService { + +} diff --git a/spring-core/src/main/java/com/baeldung/di/spring/AuthorServiceImpl.java b/spring-core/src/main/java/com/baeldung/di/spring/AuthorServiceImpl.java new file mode 100644 index 0000000000..007eb29930 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/di/spring/AuthorServiceImpl.java @@ -0,0 +1,5 @@ +package com.baeldung.di.spring; + +public class AuthorServiceImpl implements AuthorService { + +} diff --git a/spring-core/src/main/java/com/baeldung/di/spring/BookService.java b/spring-core/src/main/java/com/baeldung/di/spring/BookService.java new file mode 100644 index 0000000000..8e693e687d --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/di/spring/BookService.java @@ -0,0 +1,5 @@ +package com.baeldung.di.spring; + +public interface BookService { + +} diff --git a/spring-core/src/main/java/com/baeldung/di/spring/BookServiceImpl.java b/spring-core/src/main/java/com/baeldung/di/spring/BookServiceImpl.java new file mode 100644 index 0000000000..b4ea602234 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/di/spring/BookServiceImpl.java @@ -0,0 +1,10 @@ +package com.baeldung.di.spring; + +import org.springframework.beans.factory.annotation.Autowired; + +public class BookServiceImpl implements BookService { + + @Autowired(required = false) + private AuthorService authorService; + +} diff --git a/spring-core/src/main/java/com/baeldung/di/spring/Foo.java b/spring-core/src/main/java/com/baeldung/di/spring/Foo.java new file mode 100644 index 0000000000..9d9b5d0888 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/di/spring/Foo.java @@ -0,0 +1,4 @@ +package com.baeldung.di.spring; + +public class Foo { +} diff --git a/spring-core/src/main/java/com/baeldung/di/spring/FooProcessor.java b/spring-core/src/main/java/com/baeldung/di/spring/FooProcessor.java new file mode 100644 index 0000000000..9baaaef7a3 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/di/spring/FooProcessor.java @@ -0,0 +1,6 @@ +package com.baeldung.di.spring; + +public class FooProcessor { + + private Foo foo; +} \ No newline at end of file diff --git a/spring-core/src/main/java/com/baeldung/di/spring/PersonDao.java b/spring-core/src/main/java/com/baeldung/di/spring/PersonDao.java new file mode 100644 index 0000000000..8dde7ed1e0 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/di/spring/PersonDao.java @@ -0,0 +1,5 @@ +package com.baeldung.di.spring; + +public interface PersonDao { + +} diff --git a/spring-core/src/main/java/com/baeldung/di/spring/PersonDaoImpl.java b/spring-core/src/main/java/com/baeldung/di/spring/PersonDaoImpl.java new file mode 100644 index 0000000000..efcc2e0f21 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/di/spring/PersonDaoImpl.java @@ -0,0 +1,8 @@ +package com.baeldung.di.spring; + +import org.springframework.stereotype.Component; + +@Component +public class PersonDaoImpl implements PersonDao { + +} \ No newline at end of file diff --git a/spring-core/src/main/java/com/baeldung/di/spring/SpringBeansConfig.java b/spring-core/src/main/java/com/baeldung/di/spring/SpringBeansConfig.java new file mode 100644 index 0000000000..4cb6943fc9 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/di/spring/SpringBeansConfig.java @@ -0,0 +1,14 @@ +package com.baeldung.di.spring; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class SpringBeansConfig { + + @Bean + public AudioBookService audioBookServiceGenerator() { + return new AudioBookServiceImpl(); + } + +} diff --git a/spring-core/src/main/java/com/baeldung/di/spring/SpringMainConfig.java b/spring-core/src/main/java/com/baeldung/di/spring/SpringMainConfig.java new file mode 100644 index 0000000000..75066fd539 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/di/spring/SpringMainConfig.java @@ -0,0 +1,18 @@ +package com.baeldung.di.spring; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Import; + +@Configuration +@Import({ SpringBeansConfig.class }) +@ComponentScan("com.baeldung.di.spring") +public class SpringMainConfig { + + @Bean + public BookService bookServiceGenerator() { + return new BookServiceImpl(); + } + +} diff --git a/spring-core/src/main/java/com/baeldung/di/spring/SpringPersonService.java b/spring-core/src/main/java/com/baeldung/di/spring/SpringPersonService.java new file mode 100644 index 0000000000..b85c749982 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/di/spring/SpringPersonService.java @@ -0,0 +1,20 @@ +package com.baeldung.di.spring; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component +public class SpringPersonService { + + @Autowired + private PersonDao personDao; + + public PersonDao getPersonDao() { + return personDao; + } + + public void setPersonDao(PersonDao personDao) { + this.personDao = personDao; + } + +} diff --git a/spring-core/src/main/java/com/baeldung/di/spring/UserService.java b/spring-core/src/main/java/com/baeldung/di/spring/UserService.java new file mode 100644 index 0000000000..330d7f7448 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/di/spring/UserService.java @@ -0,0 +1,20 @@ +package com.baeldung.di.spring; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component +public class UserService { + + @Autowired + private AccountService accountService; + + public AccountService getAccountService() { + return accountService; + } + + public void setAccountService(AccountService accountService) { + this.accountService = accountService; + } + +} diff --git a/spring-core/src/test/java/com/baeldung/di/spring/SpringUnitTest.java b/spring-core/src/test/java/com/baeldung/di/spring/SpringUnitTest.java new file mode 100644 index 0000000000..7df8dfac89 --- /dev/null +++ b/spring-core/src/test/java/com/baeldung/di/spring/SpringUnitTest.java @@ -0,0 +1,57 @@ +package com.baeldung.di.spring; + +import static org.junit.Assert.assertNotNull; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@ContextConfiguration(classes = { SpringMainConfig.class }) +public class SpringUnitTest { + @Autowired + ApplicationContext context; + + @Test + public void givenAccountServiceAutowiredToUserService_WhenGetAccountServiceInvoked_ThenReturnValueIsNotNull() { + UserService userService = context.getBean(UserService.class); + assertNotNull(userService.getAccountService()); + } + + @Test + public void givenBookServiceIsRegisteredAsBeanInContext_WhenBookServiceIsRetrievedFromContext_ThenReturnValueIsNotNull() { + BookService bookService = context.getBean(BookService.class); + assertNotNull(bookService); + } + + @Test + public void givenBookServiceIsRegisteredAsBeanInContextByOverridingAudioBookService_WhenAudioBookServiceIsRetrievedFromContext_ThenNoSuchBeanDefinitionExceptionIsThrown() { + BookService bookService = context.getBean(BookService.class); + assertNotNull(bookService); + AudioBookService audioBookService = context.getBean(AudioBookService.class); + assertNotNull(audioBookService); + } + + @Test + public void givenAuthorServiceAutowiredToBookServiceAsOptionalDependency_WhenBookServiceIsRetrievedFromContext_ThenNoSuchBeanDefinitionExceptionIsNotThrown() { + BookService bookService = context.getBean(BookService.class); + assertNotNull(bookService); + } + + @Test + public void givenSpringPersonServiceConstructorAnnotatedByAutowired_WhenSpringPersonServiceIsRetrievedFromContext_ThenInstanceWillBeCreatedFromTheConstructor() { + SpringPersonService personService = context.getBean(SpringPersonService.class); + assertNotNull(personService); + } + + @Test + public void givenPersonDaoAutowiredToSpringPersonServiceBySetterInjection_WhenSpringPersonServiceRetrievedFromContext_ThenPersonDaoInitializedByTheSetter() { + SpringPersonService personService = context.getBean(SpringPersonService.class); + assertNotNull(personService); + assertNotNull(personService.getPersonDao()); + } + +} diff --git a/spring-cucumber/pom.xml b/spring-cucumber/pom.xml index 2bc3201775..85980fbc60 100644 --- a/spring-cucumber/pom.xml +++ b/spring-cucumber/pom.xml @@ -5,9 +5,9 @@ com.baeldung spring-cucumber 0.0.1-SNAPSHOT - jar spring-cucumber Demo project for Spring Boot + jar parent-boot-2 diff --git a/spring-data-rest/pom.xml b/spring-data-rest/pom.xml index 2fe4715bac..772d6f2553 100644 --- a/spring-data-rest/pom.xml +++ b/spring-data-rest/pom.xml @@ -5,8 +5,8 @@ com.baeldung spring-data-rest 1.0 - jar spring-data-rest + jar Intro to Spring Data REST diff --git a/spring-data-rest/src/test/java/com/baeldung/validator/SpringDataRestValidatorIntegrationTest.java b/spring-data-rest/src/test/java/com/baeldung/validator/SpringDataRestValidatorIntegrationTest.java index d41736e434..6da76d6a33 100644 --- a/spring-data-rest/src/test/java/com/baeldung/validator/SpringDataRestValidatorIntegrationTest.java +++ b/spring-data-rest/src/test/java/com/baeldung/validator/SpringDataRestValidatorIntegrationTest.java @@ -1,8 +1,12 @@ package com.baeldung.validator; -import com.baeldung.SpringDataRestApplication; -import com.baeldung.models.WebsiteUser; -import com.fasterxml.jackson.databind.ObjectMapper; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup; + import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -10,14 +14,14 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; +import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.web.context.WebApplicationContext; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup; +import com.baeldung.SpringDataRestApplication; +import com.baeldung.models.WebsiteUser; +import com.fasterxml.jackson.databind.ObjectMapper; @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = SpringDataRestApplication.class, webEnvironment = SpringBootTest.WebEnvironment.MOCK) @@ -42,6 +46,7 @@ public class SpringDataRestValidatorIntegrationTest { }; @Test + @DirtiesContext(methodMode = DirtiesContext.MethodMode.BEFORE_METHOD) public void whenAddingNewCorrectUser_thenCorrectStatusCodeAndResponse() throws Exception { WebsiteUser user = new WebsiteUser(); user.setEmail("john.doe@john.com"); @@ -83,6 +88,7 @@ public class SpringDataRestValidatorIntegrationTest { } @Test + @DirtiesContext(methodMode = DirtiesContext.MethodMode.BEFORE_METHOD) public void whenDeletingCorrectUser_thenCorrectStatusCodeAndResponse() throws Exception { WebsiteUser user = new WebsiteUser(); user.setEmail("john.doe@john.com"); @@ -92,6 +98,7 @@ public class SpringDataRestValidatorIntegrationTest { } @Test + @DirtiesContext(methodMode = DirtiesContext.MethodMode.BEFORE_METHOD) public void whenSearchingByEmail_thenCorrectStatusCodeAndResponse() throws Exception { WebsiteUser user = new WebsiteUser(); user.setEmail("john.doe@john.com"); diff --git a/spring-dispatcher-servlet/pom.xml b/spring-dispatcher-servlet/pom.xml index 7ac291740e..2eeb37eef0 100644 --- a/spring-dispatcher-servlet/pom.xml +++ b/spring-dispatcher-servlet/pom.xml @@ -4,9 +4,9 @@ 4.0.0 com.baeldung spring-dispatcher-servlet - war 1.0.0 spring-dispatcher-servlet + war com.baeldung diff --git a/spring-ejb/pom.xml b/spring-ejb/pom.xml index 688f692757..712bfc66ab 100755 --- a/spring-ejb/pom.xml +++ b/spring-ejb/pom.xml @@ -4,8 +4,8 @@ 4.0.0 com.baeldung.spring.ejb spring-ejb - pom spring-ejb + pom Spring EJB Tutorial diff --git a/spring-ejb/spring-ejb-client/pom.xml b/spring-ejb/spring-ejb-client/pom.xml index 3d8003cbba..e0348d5ae3 100644 --- a/spring-ejb/spring-ejb-client/pom.xml +++ b/spring-ejb/spring-ejb-client/pom.xml @@ -2,11 +2,9 @@ 4.0.0 - spring-ejb-client - jar - spring-ejb-client + jar Spring EJB Client diff --git a/spring-ejb/spring-ejb-remote/pom.xml b/spring-ejb/spring-ejb-remote/pom.xml index 797cc3ac68..4f4ddb0b54 100644 --- a/spring-ejb/spring-ejb-remote/pom.xml +++ b/spring-ejb/spring-ejb-remote/pom.xml @@ -3,8 +3,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 spring-ejb-remote - ejb spring-ejb-remote + ejb com.baeldung.spring.ejb diff --git a/spring-ejb/wildfly/pom.xml b/spring-ejb/wildfly/pom.xml index f50dad82f1..e2c3ffb50c 100644 --- a/spring-ejb/wildfly/pom.xml +++ b/spring-ejb/wildfly/pom.xml @@ -4,8 +4,8 @@ com.baeldung.wildfly wildfly 0.0.1-SNAPSHOT - pom wildfly + pom com.baeldung.spring.ejb diff --git a/spring-ejb/wildfly/widlfly-web/pom.xml b/spring-ejb/wildfly/widlfly-web/pom.xml index f0baac10dd..5eefada2fc 100644 --- a/spring-ejb/wildfly/widlfly-web/pom.xml +++ b/spring-ejb/wildfly/widlfly-web/pom.xml @@ -2,8 +2,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 widlfly-web - war widlfly-web + war com.baeldung.wildfly diff --git a/spring-ejb/wildfly/wildfly-ear/pom.xml b/spring-ejb/wildfly/wildfly-ear/pom.xml index 93d6df96e5..62d15a53dc 100644 --- a/spring-ejb/wildfly/wildfly-ear/pom.xml +++ b/spring-ejb/wildfly/wildfly-ear/pom.xml @@ -2,8 +2,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 wildfly-ear - ear wildfly-ear + ear com.baeldung.wildfly diff --git a/spring-ejb/wildfly/wildfly-ejb/pom.xml b/spring-ejb/wildfly/wildfly-ejb/pom.xml index 12bfc9c1bf..f03bfb341c 100644 --- a/spring-ejb/wildfly/wildfly-ejb/pom.xml +++ b/spring-ejb/wildfly/wildfly-ejb/pom.xml @@ -2,8 +2,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 wildfly-ejb - ejb wildfly-ejb + ejb com.baeldung.wildfly diff --git a/spring-freemarker/pom.xml b/spring-freemarker/pom.xml index 02f2a3fd06..c71643dc39 100644 --- a/spring-freemarker/pom.xml +++ b/spring-freemarker/pom.xml @@ -3,9 +3,9 @@ 4.0.0 com.baeldung.freemarker spring-freemarker - war 1.0-SNAPSHOT spring-freemarker + war com.baeldung diff --git a/spring-groovy/pom.xml b/spring-groovy/pom.xml index 42cdb93fd2..c26de0b6dd 100644 --- a/spring-groovy/pom.xml +++ b/spring-groovy/pom.xml @@ -1,12 +1,11 @@ 4.0.0 - com.baeldug spring-groovy 0.0.1-SNAPSHOT - jar spring-groovy + jar http://maven.apache.org diff --git a/spring-integration/pom.xml b/spring-integration/pom.xml index 8a5399ae0b..11a1e617aa 100644 --- a/spring-integration/pom.xml +++ b/spring-integration/pom.xml @@ -4,8 +4,8 @@ com.baeldung.samples.spring.integration spring-integration 1.0.0.BUILD-SNAPSHOT - jar spring-integration + jar http://www.springsource.org/spring-integration diff --git a/spring-jenkins-pipeline/pom.xml b/spring-jenkins-pipeline/pom.xml index 85336f9689..54b4cc478c 100644 --- a/spring-jenkins-pipeline/pom.xml +++ b/spring-jenkins-pipeline/pom.xml @@ -4,9 +4,9 @@ 4.0.0 spring-jenkins-pipeline 0.0.1-SNAPSHOT - jar spring-jenkins-pipeline Intro to Jenkins 2 and the power of pipelines + jar parent-boot-1 diff --git a/spring-jersey/pom.xml b/spring-jersey/pom.xml index b548de3701..c12f6a1241 100644 --- a/spring-jersey/pom.xml +++ b/spring-jersey/pom.xml @@ -5,8 +5,8 @@ com.baeldung spring-jersey 0.1-SNAPSHOT - war spring-jersey + war com.baeldung diff --git a/spring-jms/pom.xml b/spring-jms/pom.xml index 814875f77b..2ed58c0c95 100644 --- a/spring-jms/pom.xml +++ b/spring-jms/pom.xml @@ -4,8 +4,8 @@ com.baeldung spring-jms 0.0.1-SNAPSHOT - war spring-jms + war Introduction to Spring JMS diff --git a/spring-katharsis/pom.xml b/spring-katharsis/pom.xml index 756aae93d3..74786e7926 100644 --- a/spring-katharsis/pom.xml +++ b/spring-katharsis/pom.xml @@ -4,8 +4,8 @@ org.springframework.samples spring-katharsis 0.0.1-SNAPSHOT - war spring-katharsis + war parent-boot-1 diff --git a/spring-mobile/pom.xml b/spring-mobile/pom.xml index 4b04c3b8d5..71d0d05933 100644 --- a/spring-mobile/pom.xml +++ b/spring-mobile/pom.xml @@ -2,7 +2,6 @@ 4.0.0 - com.baeldung spring-mobile 1.0-SNAPSHOT diff --git a/spring-mockito/pom.xml b/spring-mockito/pom.xml index 481c818f39..766234c41b 100644 --- a/spring-mockito/pom.xml +++ b/spring-mockito/pom.xml @@ -2,13 +2,12 @@ 4.0.0 - com.baeldung spring-mockito 0.0.1-SNAPSHOT - jar spring-mockito Injecting Mockito Mocks into Spring Beans + jar parent-boot-2 diff --git a/spring-mvc-forms-thymeleaf/pom.xml b/spring-mvc-forms-thymeleaf/pom.xml index 504ad1dcb2..99bf465b44 100644 --- a/spring-mvc-forms-thymeleaf/pom.xml +++ b/spring-mvc-forms-thymeleaf/pom.xml @@ -2,10 +2,9 @@ 4.0.0 - spring-mvc-forms-thymeleaf - jar spring-mvc-forms-thymeleaf + jar spring forms examples using thymeleaf diff --git a/spring-mvc-java/pom.xml b/spring-mvc-java/pom.xml index 562df30318..552f62d9f7 100644 --- a/spring-mvc-java/pom.xml +++ b/spring-mvc-java/pom.xml @@ -5,7 +5,7 @@ spring-mvc-java 0.1-SNAPSHOT spring-mvc-java - war + war parent-spring-5 diff --git a/spring-mvc-kotlin/pom.xml b/spring-mvc-kotlin/pom.xml index 59b60ebd3c..fc76f58727 100644 --- a/spring-mvc-kotlin/pom.xml +++ b/spring-mvc-kotlin/pom.xml @@ -26,7 +26,6 @@ org.thymeleaf thymeleaf - org.thymeleaf thymeleaf-spring4 diff --git a/spring-mvc-simple/pom.xml b/spring-mvc-simple/pom.xml index 087ffea46d..8c2661cc27 100644 --- a/spring-mvc-simple/pom.xml +++ b/spring-mvc-simple/pom.xml @@ -19,11 +19,11 @@ spring-oxm ${spring-oxm.version} - - com.sun.mail - javax.mail - 1.6.1 - + + com.sun.mail + javax.mail + 1.6.1 + javax.servlet javax.servlet-api diff --git a/spring-mvc-velocity/pom.xml b/spring-mvc-velocity/pom.xml index dc5adcf3cf..60ac8b9c2f 100644 --- a/spring-mvc-velocity/pom.xml +++ b/spring-mvc-velocity/pom.xml @@ -1,9 +1,8 @@ 4.0.0 - 0.1-SNAPSHOT spring-mvc-velocity - + 0.1-SNAPSHOT spring-mvc-velocity war diff --git a/spring-mvc-xml/pom.xml b/spring-mvc-xml/pom.xml index 8e4a56c148..c6a6da406c 100644 --- a/spring-mvc-xml/pom.xml +++ b/spring-mvc-xml/pom.xml @@ -3,7 +3,6 @@ 4.0.0 0.1-SNAPSHOT spring-mvc-xml - spring-mvc-xml war diff --git a/spring-quartz/pom.xml b/spring-quartz/pom.xml index 77424c219e..58e72c1d51 100644 --- a/spring-quartz/pom.xml +++ b/spring-quartz/pom.xml @@ -2,13 +2,12 @@ 4.0.0 - com.baeldung spring-quartz spring-quartz 0.0.1-SNAPSHOT - jar Demo project for Scheduling in Spring with Quartz + jar parent-boot-2 diff --git a/spring-reactive-kotlin/pom.xml b/spring-reactive-kotlin/pom.xml index 7bd31396f7..90764111cb 100644 --- a/spring-reactive-kotlin/pom.xml +++ b/spring-reactive-kotlin/pom.xml @@ -3,8 +3,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 spring-reactive-kotlin - jar spring-reactive-kotlin + jar Demo project for Spring Boot diff --git a/spring-reactor/pom.xml b/spring-reactor/pom.xml index c6ad99aea7..051244c9db 100644 --- a/spring-reactor/pom.xml +++ b/spring-reactor/pom.xml @@ -3,9 +3,9 @@ 4.0.0 com.baeldung spring-reactor - jar 1.0-SNAPSHOT spring-reactor + jar http://maven.apache.org diff --git a/spring-remoting/pom.xml b/spring-remoting/pom.xml index 060f33837c..e11c5b06f9 100644 --- a/spring-remoting/pom.xml +++ b/spring-remoting/pom.xml @@ -4,10 +4,10 @@ 4.0.0 com.baeldung spring-remoting - pom 1.0-SNAPSHOT spring-remoting Parent for all projects related to Spring Remoting, except remoting-hessian-burlap + pom diff --git a/spring-remoting/remoting-amqp/pom.xml b/spring-remoting/remoting-amqp/pom.xml index f52959046a..901ce69d6b 100644 --- a/spring-remoting/remoting-amqp/pom.xml +++ b/spring-remoting/remoting-amqp/pom.xml @@ -1,7 +1,6 @@ 4.0.0 - remoting-amqp pom remoting-amqp diff --git a/spring-remoting/remoting-amqp/remoting-amqp-client/pom.xml b/spring-remoting/remoting-amqp/remoting-amqp-client/pom.xml index 98e0bc5df5..40b2fa7965 100644 --- a/spring-remoting/remoting-amqp/remoting-amqp-client/pom.xml +++ b/spring-remoting/remoting-amqp/remoting-amqp-client/pom.xml @@ -1,10 +1,9 @@ 4.0.0 - remoting-amqp-client - jar remoting-amqp-client + jar http://maven.apache.org diff --git a/spring-remoting/remoting-amqp/remoting-amqp-server/pom.xml b/spring-remoting/remoting-amqp/remoting-amqp-server/pom.xml index 7fe276f824..e8eb665815 100644 --- a/spring-remoting/remoting-amqp/remoting-amqp-server/pom.xml +++ b/spring-remoting/remoting-amqp/remoting-amqp-server/pom.xml @@ -1,10 +1,9 @@ 4.0.0 - remoting-amqp-server - jar remoting-amqp-server + jar http://maven.apache.org diff --git a/spring-remoting/remoting-hessian-burlap/pom.xml b/spring-remoting/remoting-hessian-burlap/pom.xml index 8c30e76296..e94d1bee82 100644 --- a/spring-remoting/remoting-hessian-burlap/pom.xml +++ b/spring-remoting/remoting-hessian-burlap/pom.xml @@ -4,9 +4,9 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 remoting-hessian-burlap - pom remoting-hessian-burlap 1.0-SNAPSHOT + pom parent-boot-1 diff --git a/spring-remoting/remoting-http/pom.xml b/spring-remoting/remoting-http/pom.xml index 886a28b886..c4ed511bb5 100644 --- a/spring-remoting/remoting-http/pom.xml +++ b/spring-remoting/remoting-http/pom.xml @@ -4,9 +4,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 remoting-http - pom - remoting-http + pom Parent for all modules related to HTTP Spring Remoting. diff --git a/spring-remoting/remoting-jms/remoting-jms-client/pom.xml b/spring-remoting/remoting-jms/remoting-jms-client/pom.xml index b7b1af5a1a..043ced8527 100644 --- a/spring-remoting/remoting-jms/remoting-jms-client/pom.xml +++ b/spring-remoting/remoting-jms/remoting-jms-client/pom.xml @@ -12,10 +12,6 @@ 1.0-SNAPSHOT - - UTF-8 - - org.springframework.boot @@ -34,4 +30,8 @@ + + UTF-8 + + \ No newline at end of file diff --git a/spring-remoting/remoting-jms/remoting-jms-server/pom.xml b/spring-remoting/remoting-jms/remoting-jms-server/pom.xml index 8a17cdb0a9..13de66977a 100644 --- a/spring-remoting/remoting-jms/remoting-jms-server/pom.xml +++ b/spring-remoting/remoting-jms/remoting-jms-server/pom.xml @@ -12,10 +12,6 @@ 1.0-SNAPSHOT - - UTF-8 - - org.springframework.boot @@ -34,4 +30,8 @@ + + UTF-8 + + \ No newline at end of file diff --git a/spring-remoting/remoting-rmi/pom.xml b/spring-remoting/remoting-rmi/pom.xml index b3b84786b8..7b6e807550 100644 --- a/spring-remoting/remoting-rmi/pom.xml +++ b/spring-remoting/remoting-rmi/pom.xml @@ -4,8 +4,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 remoting-rmi - pom remoting-rmi + pom spring-remoting diff --git a/spring-remoting/remoting-rmi/remoting-rmi-server/pom.xml b/spring-remoting/remoting-rmi/remoting-rmi-server/pom.xml index 7fb4d2c1bc..2a19ebbbf6 100644 --- a/spring-remoting/remoting-rmi/remoting-rmi-server/pom.xml +++ b/spring-remoting/remoting-rmi/remoting-rmi-server/pom.xml @@ -12,10 +12,6 @@ 1.0-SNAPSHOT - - UTF-8 - - org.springframework.boot @@ -34,4 +30,8 @@ + + UTF-8 + + \ No newline at end of file diff --git a/spring-rest-full/README.md b/spring-rest-full/README.md index 5140c4b270..b8b9034a0b 100644 --- a/spring-rest-full/README.md +++ b/spring-rest-full/README.md @@ -8,8 +8,6 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring The "Learn Spring Security" Classes: http://github.learnspringsecurity.com ### Relevant Articles: -- [HATEOAS for a Spring REST Service](http://www.baeldung.com/rest-api-discoverability-with-spring) -- [REST API Discoverability and HATEOAS](http://www.baeldung.com/restful-web-service-discoverability) - [ETags for REST with Spring](http://www.baeldung.com/etags-for-rest-with-spring) - [Integration Testing with the Maven Cargo plugin](http://www.baeldung.com/integration-testing-with-the-maven-cargo-plugin) - [Introduction to Spring Data JPA](http://www.baeldung.com/the-persistence-layer-with-spring-data-jpa) diff --git a/spring-rest-full/src/main/java/org/baeldung/web/controller/FooController.java b/spring-rest-full/src/main/java/org/baeldung/web/controller/FooController.java index 2e4dbcacc9..9cb028bfdb 100644 --- a/spring-rest-full/src/main/java/org/baeldung/web/controller/FooController.java +++ b/spring-rest-full/src/main/java/org/baeldung/web/controller/FooController.java @@ -7,7 +7,6 @@ import javax.servlet.http.HttpServletResponse; import org.baeldung.persistence.model.Foo; import org.baeldung.persistence.service.IFooService; import org.baeldung.web.hateoas.event.ResourceCreatedEvent; -import org.baeldung.web.hateoas.event.SingleResourceRetrievedEvent; import org.baeldung.web.util.RestPreconditions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationEventPublisher; @@ -53,7 +52,6 @@ public class FooController { public Foo findById(@PathVariable("id") final Long id, final HttpServletResponse response) { final Foo resourceById = RestPreconditions.checkFound(service.findOne(id)); - eventPublisher.publishEvent(new SingleResourceRetrievedEvent(this, response)); return resourceById; } diff --git a/spring-rest-full/src/main/java/org/baeldung/web/controller/RootController.java b/spring-rest-full/src/main/java/org/baeldung/web/controller/RootController.java index e23da6420d..a66f3d1893 100644 --- a/spring-rest-full/src/main/java/org/baeldung/web/controller/RootController.java +++ b/spring-rest-full/src/main/java/org/baeldung/web/controller/RootController.java @@ -1,22 +1,14 @@ package org.baeldung.web.controller; -import java.net.URI; import java.util.Map; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - import org.baeldung.web.metric.IActuatorMetricService; import org.baeldung.web.metric.IMetricService; -import org.baeldung.web.util.LinkUtil; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; -import org.springframework.web.bind.annotation.ResponseStatus; -import org.springframework.web.util.UriTemplate; @Controller @RequestMapping(value = "/auth/") @@ -34,18 +26,6 @@ public class RootController { // API - // discover - - @RequestMapping(value = "admin", method = RequestMethod.GET) - @ResponseStatus(value = HttpStatus.NO_CONTENT) - public void adminRoot(final HttpServletRequest request, final HttpServletResponse response) { - final String rootUri = request.getRequestURL().toString(); - - final URI fooUri = new UriTemplate("{rootUri}/{resource}").expand(rootUri, "foo"); - final String linkToFoo = LinkUtil.createLinkHeader(fooUri.toASCIIString(), "collection"); - response.addHeader("Link", linkToFoo); - } - @RequestMapping(value = "/metric", method = RequestMethod.GET) @ResponseBody public Map getMetric() { diff --git a/spring-rest-full/src/main/java/org/baeldung/web/hateoas/event/SingleResourceRetrievedEvent.java b/spring-rest-full/src/main/java/org/baeldung/web/hateoas/event/SingleResourceRetrievedEvent.java deleted file mode 100644 index 0c9eb889e6..0000000000 --- a/spring-rest-full/src/main/java/org/baeldung/web/hateoas/event/SingleResourceRetrievedEvent.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.baeldung.web.hateoas.event; - -import javax.servlet.http.HttpServletResponse; - -import org.springframework.context.ApplicationEvent; - -public class SingleResourceRetrievedEvent extends ApplicationEvent { - private final HttpServletResponse response; - - public SingleResourceRetrievedEvent(final Object source, final HttpServletResponse response) { - super(source); - - this.response = response; - } - - // API - - public HttpServletResponse getResponse() { - return response; - } - -} \ No newline at end of file diff --git a/spring-rest-full/src/main/java/org/baeldung/web/hateoas/listener/SingleResourceRetrievedDiscoverabilityListener.java b/spring-rest-full/src/main/java/org/baeldung/web/hateoas/listener/SingleResourceRetrievedDiscoverabilityListener.java deleted file mode 100644 index 32407e9f2b..0000000000 --- a/spring-rest-full/src/main/java/org/baeldung/web/hateoas/listener/SingleResourceRetrievedDiscoverabilityListener.java +++ /dev/null @@ -1,34 +0,0 @@ -package org.baeldung.web.hateoas.listener; - -import javax.servlet.http.HttpServletResponse; - -import org.baeldung.web.hateoas.event.SingleResourceRetrievedEvent; -import org.baeldung.web.util.LinkUtil; -import org.springframework.context.ApplicationListener; -import org.springframework.stereotype.Component; -import org.springframework.web.servlet.support.ServletUriComponentsBuilder; - -import com.google.common.base.Preconditions; -import com.google.common.net.HttpHeaders; - -@Component -class SingleResourceRetrievedDiscoverabilityListener implements ApplicationListener { - - @Override - public void onApplicationEvent(final SingleResourceRetrievedEvent resourceRetrievedEvent) { - Preconditions.checkNotNull(resourceRetrievedEvent); - - final HttpServletResponse response = resourceRetrievedEvent.getResponse(); - addLinkHeaderOnSingleResourceRetrieval(response); - } - - void addLinkHeaderOnSingleResourceRetrieval(final HttpServletResponse response) { - final String requestURL = ServletUriComponentsBuilder.fromCurrentRequestUri().build().toUri().toASCIIString(); - final int positionOfLastSlash = requestURL.lastIndexOf("/"); - final String uriForResourceCreation = requestURL.substring(0, positionOfLastSlash); - - final String linkHeaderValue = LinkUtil.createLinkHeader(uriForResourceCreation, "collection"); - response.addHeader(HttpHeaders.LINK, linkHeaderValue); - } - -} \ No newline at end of file diff --git a/spring-rest-full/src/test/java/org/baeldung/web/LiveTestSuiteLiveTest.java b/spring-rest-full/src/test/java/org/baeldung/web/LiveTestSuiteLiveTest.java index da736392c4..663935e72f 100644 --- a/spring-rest-full/src/test/java/org/baeldung/web/LiveTestSuiteLiveTest.java +++ b/spring-rest-full/src/test/java/org/baeldung/web/LiveTestSuiteLiveTest.java @@ -6,8 +6,7 @@ import org.junit.runners.Suite; @RunWith(Suite.class) @Suite.SuiteClasses({ // @formatter:off - FooDiscoverabilityLiveTest.class - ,FooLiveTest.class + FooLiveTest.class }) // public class LiveTestSuiteLiveTest { diff --git a/spring-rest-full/src/test/java/org/baeldung/web/util/HTTPLinkHeaderUtil.java b/spring-rest-full/src/test/java/org/baeldung/web/util/HTTPLinkHeaderUtil.java deleted file mode 100644 index 29f1c91ca3..0000000000 --- a/spring-rest-full/src/test/java/org/baeldung/web/util/HTTPLinkHeaderUtil.java +++ /dev/null @@ -1,36 +0,0 @@ -package org.baeldung.web.util; - -public final class HTTPLinkHeaderUtil { - - private HTTPLinkHeaderUtil() { - throw new AssertionError(); - } - - // - - public static String extractURIByRel(final String linkHeader, final String rel) { - if (linkHeader == null) { - return null; - } - - String uriWithSpecifiedRel = null; - final String[] links = linkHeader.split(", "); - String linkRelation; - for (final String link : links) { - final int positionOfSeparator = link.indexOf(';'); - linkRelation = link.substring(positionOfSeparator + 1, link.length()).trim(); - if (extractTypeOfRelation(linkRelation).equals(rel)) { - uriWithSpecifiedRel = link.substring(1, positionOfSeparator - 1); - break; - } - } - - return uriWithSpecifiedRel; - } - - private static Object extractTypeOfRelation(final String linkRelation) { - final int positionOfEquals = linkRelation.indexOf('='); - return linkRelation.substring(positionOfEquals + 2, linkRelation.length() - 1).trim(); - } - -} diff --git a/spring-rest-hal-browser/pom.xml b/spring-rest-hal-browser/pom.xml index ee0a2c043d..413aad9e8c 100644 --- a/spring-rest-hal-browser/pom.xml +++ b/spring-rest-hal-browser/pom.xml @@ -7,19 +7,6 @@ spring-rest-hal-browser 1.0-SNAPSHOT spring-rest-hal-browser - - - - - org.apache.maven.plugins - maven-compiler-plugin - - 1.8 - 1.8 - - - - @@ -46,9 +33,19 @@ h2 1.4.197 - - + + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + + + + \ No newline at end of file diff --git a/spring-rest-shell/pom.xml b/spring-rest-shell/pom.xml index 540b3d08eb..acf33cf98f 100644 --- a/spring-rest-shell/pom.xml +++ b/spring-rest-shell/pom.xml @@ -3,8 +3,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 spring-rest-shell - jar spring-rest-shell + jar A simple project to demonstrate Spring REST Shell features. diff --git a/spring-security-acl/pom.xml b/spring-security-acl/pom.xml index c87c237233..8acc39b785 100644 --- a/spring-security-acl/pom.xml +++ b/spring-security-acl/pom.xml @@ -2,12 +2,11 @@ 4.0.0 - spring-security-acl 0.0.1-SNAPSHOT - war spring-security-acl Spring Security ACL + war parent-boot-1 diff --git a/spring-security-angular/server/pom.xml b/spring-security-angular/server/pom.xml index 55269bb35f..6474bb5ed6 100644 --- a/spring-security-angular/server/pom.xml +++ b/spring-security-angular/server/pom.xml @@ -5,8 +5,8 @@ com.baeldung server 0.0.1-SNAPSHOT - jar server + jar Spring Security Angular diff --git a/spring-security-client/spring-security-jsp-authentication/pom.xml b/spring-security-client/spring-security-jsp-authentication/pom.xml index 9bb58863d9..9cb2a45331 100644 --- a/spring-security-client/spring-security-jsp-authentication/pom.xml +++ b/spring-security-client/spring-security-jsp-authentication/pom.xml @@ -5,8 +5,8 @@ com.baeldung spring-security-jsp-authentication 0.0.1-SNAPSHOT - war spring-security-jsp-authentication + war Spring Security JSP Authentication tag sample diff --git a/spring-security-client/spring-security-jsp-authorize/pom.xml b/spring-security-client/spring-security-jsp-authorize/pom.xml index 427ba7754a..ad4c9d105b 100644 --- a/spring-security-client/spring-security-jsp-authorize/pom.xml +++ b/spring-security-client/spring-security-jsp-authorize/pom.xml @@ -2,13 +2,12 @@ 4.0.0 - com.baeldung spring-security-jsp-authorize 0.0.1-SNAPSHOT - war spring-security-jsp-authorize Spring Security JSP Authorize tag sample + war parent-boot-1 diff --git a/spring-security-client/spring-security-jsp-config/pom.xml b/spring-security-client/spring-security-jsp-config/pom.xml index c0318a2c5c..02ea206738 100644 --- a/spring-security-client/spring-security-jsp-config/pom.xml +++ b/spring-security-client/spring-security-jsp-config/pom.xml @@ -5,9 +5,9 @@ com.baeldung spring-security-jsp-config 0.0.1-SNAPSHOT - war spring-security-jsp-config Spring Security JSP configuration + war parent-boot-1 diff --git a/spring-security-client/spring-security-mvc/pom.xml b/spring-security-client/spring-security-mvc/pom.xml index 6ddc6fbe65..75298026a8 100644 --- a/spring-security-client/spring-security-mvc/pom.xml +++ b/spring-security-client/spring-security-mvc/pom.xml @@ -5,9 +5,9 @@ com.baeldung spring-security-mvc 0.0.1-SNAPSHOT - war spring-security-mvc Spring Security MVC + war parent-boot-1 diff --git a/spring-security-client/spring-security-thymeleaf-authentication/pom.xml b/spring-security-client/spring-security-thymeleaf-authentication/pom.xml index 8e6a352af1..01d2c6bdbe 100644 --- a/spring-security-client/spring-security-thymeleaf-authentication/pom.xml +++ b/spring-security-client/spring-security-thymeleaf-authentication/pom.xml @@ -6,9 +6,9 @@ com.baeldung spring-security-thymeleaf-authentication 0.0.1-SNAPSHOT - war spring-security-thymeleaf-authentication Spring Security thymeleaf authentication tag sample + war parent-boot-1 diff --git a/spring-security-client/spring-security-thymeleaf-authorize/pom.xml b/spring-security-client/spring-security-thymeleaf-authorize/pom.xml index 52972c0241..8c600c1f81 100644 --- a/spring-security-client/spring-security-thymeleaf-authorize/pom.xml +++ b/spring-security-client/spring-security-thymeleaf-authorize/pom.xml @@ -6,9 +6,9 @@ com.baeldung spring-security-thymeleaf-authorize 0.0.1-SNAPSHOT - war spring-security-thymeleaf-authorize Spring Security thymeleaf authorize tag sample + war parent-boot-1 diff --git a/spring-security-client/spring-security-thymeleaf-config/pom.xml b/spring-security-client/spring-security-thymeleaf-config/pom.xml index 668f20c001..aeda999405 100644 --- a/spring-security-client/spring-security-thymeleaf-config/pom.xml +++ b/spring-security-client/spring-security-thymeleaf-config/pom.xml @@ -2,13 +2,12 @@ 4.0.0 - com.baeldung spring-security-thymeleaf-config 0.0.1-SNAPSHOT - war spring-security-thymeleaf-config Spring Security thymeleaf configuration sample project + war parent-boot-1 diff --git a/spring-security-cors/pom.xml b/spring-security-cors/pom.xml new file mode 100644 index 0000000000..0dd41e66c7 --- /dev/null +++ b/spring-security-cors/pom.xml @@ -0,0 +1,66 @@ + + + 4.0.0 + com.baeldung + spring-security-cors + 0.0.1-SNAPSHOT + jar + spring-security-cors + Spring Security CORS + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + + org.springframework.boot + spring-boot-dependencies + 2.1.2.RELEASE + pom + import + + + + + + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.security + spring-security-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + UTF-8 + UTF-8 + + + diff --git a/spring-security-cors/src/main/java/com/baeldung/springbootsecuritycors/basicauth/SpringBootSecurityApplication.java b/spring-security-cors/src/main/java/com/baeldung/springbootsecuritycors/basicauth/SpringBootSecurityApplication.java new file mode 100644 index 0000000000..89bf0dde5d --- /dev/null +++ b/spring-security-cors/src/main/java/com/baeldung/springbootsecuritycors/basicauth/SpringBootSecurityApplication.java @@ -0,0 +1,14 @@ +package com.baeldung.springbootsecuritycors.basicauth; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication(scanBasePackages = "com.baeldung.springbootsecuritycors") +@EnableAutoConfiguration +public class SpringBootSecurityApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringBootSecurityApplication.class, args); + } +} diff --git a/spring-security-cors/src/main/java/com/baeldung/springbootsecuritycors/basicauth/config/WebSecurityConfig.java b/spring-security-cors/src/main/java/com/baeldung/springbootsecuritycors/basicauth/config/WebSecurityConfig.java new file mode 100644 index 0000000000..684354bf26 --- /dev/null +++ b/spring-security-cors/src/main/java/com/baeldung/springbootsecuritycors/basicauth/config/WebSecurityConfig.java @@ -0,0 +1,19 @@ +package com.baeldung.springbootsecuritycors.basicauth.config; + +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 +public class WebSecurityConfig extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(HttpSecurity http) throws Exception { + http + .authorizeRequests() + .anyRequest().authenticated() + .and() + .httpBasic(); + http.cors(); //disable this line to reproduce the CORS 401 + } +} diff --git a/spring-security-cors/src/main/java/com/baeldung/springbootsecuritycors/controller/ResourceController.java b/spring-security-cors/src/main/java/com/baeldung/springbootsecuritycors/controller/ResourceController.java new file mode 100644 index 0000000000..7292c7f4f4 --- /dev/null +++ b/spring-security-cors/src/main/java/com/baeldung/springbootsecuritycors/controller/ResourceController.java @@ -0,0 +1,17 @@ +package com.baeldung.springbootsecuritycors.controller; + +import java.security.Principal; + +import org.springframework.web.bind.annotation.CrossOrigin; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@CrossOrigin("http://localhost:4200") +public class ResourceController { + + @GetMapping("/user") + public String user(Principal principal) { + return principal.getName(); + } +} diff --git a/spring-security-cors/src/test/java/com/baeldung/springbootsecuritycors/ResourceControllerTest.java b/spring-security-cors/src/test/java/com/baeldung/springbootsecuritycors/ResourceControllerTest.java new file mode 100644 index 0000000000..b45529ca5f --- /dev/null +++ b/spring-security-cors/src/test/java/com/baeldung/springbootsecuritycors/ResourceControllerTest.java @@ -0,0 +1,42 @@ +package com.baeldung.springbootsecuritycors; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.options; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +import com.baeldung.springbootsecuritycors.basicauth.SpringBootSecurityApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = { SpringBootSecurityApplication.class }) +public class ResourceControllerTest { + + private MockMvc mockMvc; + + @Autowired + private WebApplicationContext wac; + + @Before + public void setUp() { + this.mockMvc = MockMvcBuilders.webAppContextSetup(wac) + .apply(SecurityMockMvcConfigurers.springSecurity()) + .build(); + } + + @Test + public void givenPreFlightRequest_whenPerfomed_shouldReturnOK() throws Exception { + mockMvc.perform(options("/user") + .header("Access-Control-Request-Method", "GET") + .header("Origin", "http://localhost:4200")) + .andExpect(status().isOk()); + } +} diff --git a/spring-security-mvc-boot/pom.xml b/spring-security-mvc-boot/pom.xml index 0a40b0b324..00d8f032c2 100644 --- a/spring-security-mvc-boot/pom.xml +++ b/spring-security-mvc-boot/pom.xml @@ -2,12 +2,11 @@ 4.0.0 - com.baeldung spring-security-mvc-boot 0.0.1-SNAPSHOT - war spring-security-mvc-boot + war Spring Security MVC Boot diff --git a/spring-security-mvc-jsonview/src/main/java/com/baeldung/spring/SecurityJsonViewControllerAdvice.java b/spring-security-mvc-jsonview/src/main/java/com/baeldung/spring/SecurityJsonViewControllerAdvice.java index 66c7207e91..d6d022a110 100644 --- a/spring-security-mvc-jsonview/src/main/java/com/baeldung/spring/SecurityJsonViewControllerAdvice.java +++ b/spring-security-mvc-jsonview/src/main/java/com/baeldung/spring/SecurityJsonViewControllerAdvice.java @@ -31,6 +31,7 @@ public class SecurityJsonViewControllerAdvice extends AbstractMappingJacksonResp .collect(Collectors.toList()); if (jsonViews.size() == 1) { bodyContainer.setSerializationView(jsonViews.get(0)); + return; } throw new IllegalArgumentException("Ambiguous @JsonView declaration for roles "+ authorities.stream().map(GrantedAuthority::getAuthority).collect(Collectors.joining(","))); } diff --git a/spring-security-mvc-login/pom.xml b/spring-security-mvc-login/pom.xml index 5ee216548a..bbdff6fc2f 100644 --- a/spring-security-mvc-login/pom.xml +++ b/spring-security-mvc-login/pom.xml @@ -1,7 +1,6 @@ 4.0.0 - com.baeldung spring-security-mvc-login 0.1-SNAPSHOT diff --git a/spring-security-mvc-persisted-remember-me/pom.xml b/spring-security-mvc-persisted-remember-me/pom.xml index 8b15e658e8..c65b7a30cb 100644 --- a/spring-security-mvc-persisted-remember-me/pom.xml +++ b/spring-security-mvc-persisted-remember-me/pom.xml @@ -1,7 +1,6 @@ 4.0.0 - com.baeldung spring-security-mvc-persisted-remember-me 0.1-SNAPSHOT diff --git a/spring-security-mvc-session/pom.xml b/spring-security-mvc-session/pom.xml index 85c8475657..03c75b99e2 100644 --- a/spring-security-mvc-session/pom.xml +++ b/spring-security-mvc-session/pom.xml @@ -1,7 +1,6 @@ 4.0.0 - com.baeldung spring-security-mvc-session 0.1-SNAPSHOT diff --git a/spring-security-openid/pom.xml b/spring-security-openid/pom.xml index 4343996e02..0b5eaf6270 100644 --- a/spring-security-openid/pom.xml +++ b/spring-security-openid/pom.xml @@ -2,10 +2,9 @@ 4.0.0 - spring-security-openid - war spring-security-openid + war Spring OpenID sample project diff --git a/spring-security-react/pom.xml b/spring-security-react/pom.xml index 32817945be..eaf10791bc 100644 --- a/spring-security-react/pom.xml +++ b/spring-security-react/pom.xml @@ -3,7 +3,6 @@ 4.0.0 spring-security-react 0.1-SNAPSHOT - spring-security-react war diff --git a/spring-security-rest-custom/pom.xml b/spring-security-rest-custom/pom.xml index 66ad087bf6..8fdcb509ee 100644 --- a/spring-security-rest-custom/pom.xml +++ b/spring-security-rest-custom/pom.xml @@ -1,7 +1,6 @@ 4.0.0 - com.baeldung spring-security-rest-custom 0.1-SNAPSHOT diff --git a/spring-security-sso/pom.xml b/spring-security-sso/pom.xml index 4b297a91b5..707f516da2 100644 --- a/spring-security-sso/pom.xml +++ b/spring-security-sso/pom.xml @@ -4,7 +4,6 @@ org.baeldung spring-security-sso 1.0.0-SNAPSHOT - spring-security-sso pom diff --git a/spring-security-sso/spring-security-sso-auth-server/pom.xml b/spring-security-sso/spring-security-sso-auth-server/pom.xml index ff76f377c6..3c8f04a056 100644 --- a/spring-security-sso/spring-security-sso-auth-server/pom.xml +++ b/spring-security-sso/spring-security-sso-auth-server/pom.xml @@ -1,7 +1,6 @@ 4.0.0 - spring-security-sso-auth-server spring-security-sso-auth-server war @@ -13,12 +12,10 @@ - org.springframework.boot spring-boot-starter-web - org.springframework.security.oauth spring-security-oauth2 diff --git a/spring-security-sso/spring-security-sso-ui-2/pom.xml b/spring-security-sso/spring-security-sso-ui-2/pom.xml index e4ccb82fea..a6cf5e5386 100644 --- a/spring-security-sso/spring-security-sso-ui-2/pom.xml +++ b/spring-security-sso/spring-security-sso-ui-2/pom.xml @@ -1,7 +1,6 @@ 4.0.0 - spring-security-sso-ui-2 spring-security-sso-ui-2 war diff --git a/spring-security-sso/spring-security-sso-ui/pom.xml b/spring-security-sso/spring-security-sso-ui/pom.xml index a946db4c3b..7edcee82c8 100644 --- a/spring-security-sso/spring-security-sso-ui/pom.xml +++ b/spring-security-sso/spring-security-sso-ui/pom.xml @@ -1,7 +1,6 @@ 4.0.0 - spring-security-sso-ui spring-security-sso-ui war diff --git a/spring-security-stormpath/pom.xml b/spring-security-stormpath/pom.xml index 4f19921fbd..dd6037a22c 100644 --- a/spring-security-stormpath/pom.xml +++ b/spring-security-stormpath/pom.xml @@ -3,10 +3,11 @@ 4.0.0 com.baeldung spring-security-stormpath - war 1.0-SNAPSHOT spring-security-stormpath + war http://maven.apache.org + abhinabkanrar@gmail.com diff --git a/spring-security-thymeleaf/pom.xml b/spring-security-thymeleaf/pom.xml index d8b476683a..732eb1dc1d 100644 --- a/spring-security-thymeleaf/pom.xml +++ b/spring-security-thymeleaf/pom.xml @@ -2,12 +2,11 @@ 4.0.0 - com.baeldung spring-security-thymeleaf 0.0.1-SNAPSHOT - jar spring-security-thymeleaf + jar Spring Security with Thymeleaf tutorial diff --git a/spring-security-x509/keystore/Makefile b/spring-security-x509/keystore/Makefile index 2b5b5e8abe..2cd7c55c5b 100644 --- a/spring-security-x509/keystore/Makefile +++ b/spring-security-x509/keystore/Makefile @@ -2,6 +2,7 @@ PASSWORD=changeit KEYSTORE=keystore.jks HOSTNAME=localhost CLIENTNAME=cid +CLIENT_PRIVATE_KEY="${CLIENTNAME}_pk" # CN = Common Name # OU = Organization Unit @@ -59,12 +60,12 @@ create-truststore: export-authority add-client: # Generate client certificate - keytool -genkey -alias $(CLIENTNAME) -ext san=dns:localhost,ip:127.0.0.1 \ + keytool -genkey -alias $(CLIENT_PRIVATE_KEY) -ext san=dns:localhost,ip:127.0.0.1 \ -keyalg RSA -keysize 4096 -sigalg SHA512withRSA -keypass $(PASSWORD) \ -validity 3650 -dname $(DNAME_CLIENT) \ -keystore $(TRUSTSTORE) -storepass $(PASSWORD) # Generate a host certificate signing request - keytool -certreq -alias $(CLIENTNAME) -ext san=dns:localhost,ip:127.0.0.1 -ext BC=ca:true \ + keytool -certreq -alias $(CLIENT_PRIVATE_KEY) -ext san=dns:localhost,ip:127.0.0.1 -ext BC=ca:true \ -keyalg RSA -keysize 4096 -sigalg SHA512withRSA \ -validity 3650 -file "$(CLIENTNAME).csr" \ -keystore $(TRUSTSTORE) -storepass $(PASSWORD) @@ -78,10 +79,13 @@ add-client: -file "$(CLIENTNAME).crt" \ -keystore $(TRUSTSTORE) -storepass $(PASSWORD) # Export private certificate for importing into a browser - keytool -importkeystore -srcalias $(CLIENTNAME) -ext san=dns:localhost,ip:127.0.0.1 \ + keytool -importkeystore -srcalias $(CLIENT_PRIVATE_KEY) -ext san=dns:localhost,ip:127.0.0.1 \ -srckeystore $(TRUSTSTORE) -srcstorepass $(PASSWORD) \ -destkeystore "$(CLIENTNAME).p12" -deststorepass $(PASSWORD) \ -deststoretype PKCS12 + # Delete client private key as truststore should not contain any private keys + keytool -delete -alias $(CLIENT_PRIVATE_KEY) \ + -keystore $(TRUSTSTORE) -storepass $(PASSWORD) clean: # Remove generated artifacts diff --git a/spring-security-x509/pom.xml b/spring-security-x509/pom.xml index 658840e866..db7def0c02 100644 --- a/spring-security-x509/pom.xml +++ b/spring-security-x509/pom.xml @@ -5,8 +5,8 @@ com.baeldung spring-security-x509 0.0.1-SNAPSHOT - pom spring-security-x509 + pom parent-boot-1 diff --git a/spring-security-x509/spring-security-x509-basic-auth/pom.xml b/spring-security-x509/spring-security-x509-basic-auth/pom.xml index 5b68a8e63b..0bbd5d3d3d 100644 --- a/spring-security-x509/spring-security-x509-basic-auth/pom.xml +++ b/spring-security-x509/spring-security-x509-basic-auth/pom.xml @@ -4,8 +4,8 @@ 4.0.0 spring-security-x509-basic-auth 0.0.1-SNAPSHOT - jar spring-security-x509-basic-auth + jar Spring x.509 Authentication Demo diff --git a/spring-security-x509/spring-security-x509-client-auth/pom.xml b/spring-security-x509/spring-security-x509-client-auth/pom.xml index 47ec7f971d..3e2e18223a 100644 --- a/spring-security-x509/spring-security-x509-client-auth/pom.xml +++ b/spring-security-x509/spring-security-x509-client-auth/pom.xml @@ -4,8 +4,8 @@ 4.0.0 spring-security-x509-client-auth 0.0.1-SNAPSHOT - jar spring-security-x509-client-auth + jar Spring x.509 Client Authentication Demo diff --git a/spring-session/pom.xml b/spring-session/pom.xml index 28dde40272..bcdbaf2406 100644 --- a/spring-session/pom.xml +++ b/spring-session/pom.xml @@ -4,7 +4,6 @@ org.baeldung spring-session 1.0.0-SNAPSHOT - spring-session pom diff --git a/spring-session/spring-session-jdbc/pom.xml b/spring-session/spring-session-jdbc/pom.xml index ce6b5f5908..a98c4b3429 100644 --- a/spring-session/spring-session-jdbc/pom.xml +++ b/spring-session/spring-session-jdbc/pom.xml @@ -6,8 +6,8 @@ com.baeldung spring-session-jdbc 0.0.1-SNAPSHOT - jar spring-session-jdbc + jar Spring Session with JDBC tutorial diff --git a/spring-sleuth/pom.xml b/spring-sleuth/pom.xml index c693466ab0..2387915c79 100644 --- a/spring-sleuth/pom.xml +++ b/spring-sleuth/pom.xml @@ -5,8 +5,8 @@ com.baeldung spring-sleuth 1.0.0-SNAPSHOT - jar spring-sleuth + jar parent-boot-2 diff --git a/spring-soap/.gitignore b/spring-soap/.gitignore new file mode 100644 index 0000000000..b83d22266a --- /dev/null +++ b/spring-soap/.gitignore @@ -0,0 +1 @@ +/target/ diff --git a/spring-soap/pom.xml b/spring-soap/pom.xml new file mode 100644 index 0000000000..2865a4c3bc --- /dev/null +++ b/spring-soap/pom.xml @@ -0,0 +1,68 @@ + + + 4.0.0 + + com.baeldung + spring-soap + 1.0.0 + + + org.springframework.boot + spring-boot-starter-parent + 2.1.2.RELEASE + + + + 1.8 + + + + + + org.springframework.boot + spring-boot-starter-web-services + + + wsdl4j + wsdl4j + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + org.codehaus.mojo + jaxb2-maven-plugin + 1.6 + + + xjc + + xjc + + + + + ${project.basedir}/src/main/resources/ + ${project.basedir}/src/main/java + false + + + + + + + diff --git a/spring-soap/src/main/java/com/baeldung/springsoap/Application.java b/spring-soap/src/main/java/com/baeldung/springsoap/Application.java new file mode 100644 index 0000000000..ad9258447c --- /dev/null +++ b/spring-soap/src/main/java/com/baeldung/springsoap/Application.java @@ -0,0 +1,12 @@ +package com.baeldung.springsoap; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } +} diff --git a/spring-soap/src/main/java/com/baeldung/springsoap/CountryEndpoint.java b/spring-soap/src/main/java/com/baeldung/springsoap/CountryEndpoint.java new file mode 100644 index 0000000000..745131767a --- /dev/null +++ b/spring-soap/src/main/java/com/baeldung/springsoap/CountryEndpoint.java @@ -0,0 +1,30 @@ +package com.baeldung.springsoap; + +import com.baeldung.springsoap.gen.*; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.ws.server.endpoint.annotation.Endpoint; +import org.springframework.ws.server.endpoint.annotation.PayloadRoot; +import org.springframework.ws.server.endpoint.annotation.RequestPayload; +import org.springframework.ws.server.endpoint.annotation.ResponsePayload; + +@Endpoint +public class CountryEndpoint { + + private static final String NAMESPACE_URI = "http://www.baeldung.com/springsoap/gen"; + + private CountryRepository countryRepository; + + @Autowired + public CountryEndpoint(CountryRepository countryRepository) { + this.countryRepository = countryRepository; + } + + @PayloadRoot(namespace = NAMESPACE_URI, localPart = "getCountryRequest") + @ResponsePayload + public GetCountryResponse getCountry(@RequestPayload GetCountryRequest request) { + GetCountryResponse response = new GetCountryResponse(); + response.setCountry(countryRepository.findCountry(request.getName())); + + return response; + } +} diff --git a/spring-soap/src/main/java/com/baeldung/springsoap/CountryRepository.java b/spring-soap/src/main/java/com/baeldung/springsoap/CountryRepository.java new file mode 100644 index 0000000000..8a0f58a64e --- /dev/null +++ b/spring-soap/src/main/java/com/baeldung/springsoap/CountryRepository.java @@ -0,0 +1,47 @@ +package com.baeldung.springsoap; + +import com.baeldung.springsoap.gen.*; +import org.springframework.stereotype.Component; +import org.springframework.util.Assert; + +import javax.annotation.PostConstruct; +import java.util.HashMap; +import java.util.Map; + +@Component +public class CountryRepository { + + private static final Map countries = new HashMap<>(); + + @PostConstruct + public void initData() { + Country spain = new Country(); + spain.setName("Spain"); + spain.setCapital("Madrid"); + spain.setCurrency(Currency.EUR); + spain.setPopulation(46704314); + + countries.put(spain.getName(), spain); + + Country poland = new Country(); + poland.setName("Poland"); + poland.setCapital("Warsaw"); + poland.setCurrency(Currency.PLN); + poland.setPopulation(38186860); + + countries.put(poland.getName(), poland); + + Country uk = new Country(); + uk.setName("United Kingdom"); + uk.setCapital("London"); + uk.setCurrency(Currency.GBP); + uk.setPopulation(63705000); + + countries.put(uk.getName(), uk); + } + + public Country findCountry(String name) { + Assert.notNull(name, "The country's name must not be null"); + return countries.get(name); + } +} diff --git a/spring-soap/src/main/java/com/baeldung/springsoap/WebServiceConfig.java b/spring-soap/src/main/java/com/baeldung/springsoap/WebServiceConfig.java new file mode 100644 index 0000000000..930a961208 --- /dev/null +++ b/spring-soap/src/main/java/com/baeldung/springsoap/WebServiceConfig.java @@ -0,0 +1,41 @@ +package com.baeldung.springsoap; + +import org.springframework.boot.web.servlet.ServletRegistrationBean; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.io.ClassPathResource; +import org.springframework.ws.config.annotation.EnableWs; +import org.springframework.ws.config.annotation.WsConfigurerAdapter; +import org.springframework.ws.transport.http.MessageDispatcherServlet; +import org.springframework.ws.wsdl.wsdl11.DefaultWsdl11Definition; +import org.springframework.xml.xsd.SimpleXsdSchema; +import org.springframework.xml.xsd.XsdSchema; + +@EnableWs +@Configuration +public class WebServiceConfig extends WsConfigurerAdapter { + + @Bean + public ServletRegistrationBean messageDispatcherServlet(ApplicationContext applicationContext) { + MessageDispatcherServlet servlet = new MessageDispatcherServlet(); + servlet.setApplicationContext(applicationContext); + servlet.setTransformWsdlLocations(true); + return new ServletRegistrationBean(servlet, "/ws/*"); + } + + @Bean(name = "countries") + public DefaultWsdl11Definition defaultWsdl11Definition(XsdSchema countriesSchema) { + DefaultWsdl11Definition wsdl11Definition = new DefaultWsdl11Definition(); + wsdl11Definition.setPortTypeName("CountriesPort"); + wsdl11Definition.setLocationUri("/ws"); + wsdl11Definition.setTargetNamespace("http://www.baeldung.com/springsoap/gen"); + wsdl11Definition.setSchema(countriesSchema); + return wsdl11Definition; + } + + @Bean + public XsdSchema countriesSchema() { + return new SimpleXsdSchema(new ClassPathResource("countries.xsd")); + } +} diff --git a/spring-soap/src/main/resources/countries.xsd b/spring-soap/src/main/resources/countries.xsd new file mode 100644 index 0000000000..524e5ac2d5 --- /dev/null +++ b/spring-soap/src/main/resources/countries.xsd @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-soap/src/test/java/com/baeldung/springsoap/ApplicationIntegrationTest.java b/spring-soap/src/test/java/com/baeldung/springsoap/ApplicationIntegrationTest.java new file mode 100644 index 0000000000..3b071c286f --- /dev/null +++ b/spring-soap/src/test/java/com/baeldung/springsoap/ApplicationIntegrationTest.java @@ -0,0 +1,39 @@ +package com.baeldung.springsoap; + +import com.baeldung.springsoap.gen.GetCountryRequest; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.boot.web.server.LocalServerPort; +import org.springframework.oxm.jaxb.Jaxb2Marshaller; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.util.ClassUtils; +import org.springframework.ws.client.core.WebServiceTemplate; + +import static org.assertj.core.api.Assertions.assertThat; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) +public class ApplicationIntegrationTest { + + private Jaxb2Marshaller marshaller = new Jaxb2Marshaller(); + + @LocalServerPort private int port = 0; + + @Before + public void init() throws Exception { + marshaller.setPackagesToScan(ClassUtils.getPackageName(GetCountryRequest.class)); + marshaller.afterPropertiesSet(); + } + + @Test + public void whenSendRequest_thenResponseIsNotNull() { + WebServiceTemplate ws = new WebServiceTemplate(marshaller); + GetCountryRequest request = new GetCountryRequest(); + request.setName("Spain"); + + assertThat(ws.marshalSendAndReceive("http://localhost:" + port + "/ws", request)).isNotNull(); + } +} diff --git a/spring-soap/src/test/resources/request.xml b/spring-soap/src/test/resources/request.xml new file mode 100644 index 0000000000..7a94aeeee6 --- /dev/null +++ b/spring-soap/src/test/resources/request.xml @@ -0,0 +1,23 @@ + + + + + Spain + + + + + + + + + + Spain + 46704314 + Madrid + EUR + + + + \ No newline at end of file diff --git a/spring-social-login/pom.xml b/spring-social-login/pom.xml index 6b7b90443a..e948c908d4 100644 --- a/spring-social-login/pom.xml +++ b/spring-social-login/pom.xml @@ -1,7 +1,6 @@ 4.0.0 - spring-social-login spring-social-login war diff --git a/spring-static-resources/pom.xml b/spring-static-resources/pom.xml index 92f6616839..aedf88e384 100644 --- a/spring-static-resources/pom.xml +++ b/spring-static-resources/pom.xml @@ -5,8 +5,8 @@ com.baeldung spring-static-resources 0.1.0-SNAPSHOT - war spring-static-resources + war com.baeldung diff --git a/spring-swagger-codegen/spring-swagger-codegen-api-client/pom.xml b/spring-swagger-codegen/spring-swagger-codegen-api-client/pom.xml index c175ea48b3..320745b6e5 100644 --- a/spring-swagger-codegen/spring-swagger-codegen-api-client/pom.xml +++ b/spring-swagger-codegen/spring-swagger-codegen-api-client/pom.xml @@ -1,12 +1,12 @@ 4.0.0 - spring-swagger-codegen-api-client - jar spring-swagger-codegen-api-client https://github.com/swagger-api/swagger-codegen Swagger Java + jar + scm:git:git@github.com:swagger-api/swagger-codegen.git scm:git:git@github.com:swagger-api/swagger-codegen.git @@ -20,6 +20,7 @@ repo + Swagger diff --git a/spring-thymeleaf/pom.xml b/spring-thymeleaf/pom.xml index 78f95fe1df..cdc2ed25ae 100644 --- a/spring-thymeleaf/pom.xml +++ b/spring-thymeleaf/pom.xml @@ -4,8 +4,8 @@ com.baeldung spring-thymeleaf 0.1-SNAPSHOT - war spring-thymeleaf + war com.baeldung diff --git a/spring-vault/pom.xml b/spring-vault/pom.xml index aad6da1cc3..ccad71c024 100644 --- a/spring-vault/pom.xml +++ b/spring-vault/pom.xml @@ -4,12 +4,11 @@ xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 4.0.0 - com.baeldung spring-vault 0.0.1-SNAPSHOT - jar spring-vault + jar Spring Vault sample project diff --git a/spring-vertx/pom.xml b/spring-vertx/pom.xml index 7a0bdc81d0..1a0e1c0223 100644 --- a/spring-vertx/pom.xml +++ b/spring-vertx/pom.xml @@ -3,9 +3,9 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 spring-vertx - jar spring-vertx A demo project with vertx spring integration + jar parent-boot-2 diff --git a/spring-webflux-amqp/pom.xml b/spring-webflux-amqp/pom.xml index 0868e14717..a8346458a0 100755 --- a/spring-webflux-amqp/pom.xml +++ b/spring-webflux-amqp/pom.xml @@ -2,12 +2,11 @@ 4.0.0 - org.baeldung.spring spring-webflux-amqp 1.0.0-SNAPSHOT - jar spring-webflux-amqp + jar Spring WebFlux AMQP Sample diff --git a/spring-zuul/pom.xml b/spring-zuul/pom.xml index a8c891cd89..d00a932168 100644 --- a/spring-zuul/pom.xml +++ b/spring-zuul/pom.xml @@ -2,7 +2,6 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - com.baeldung spring-zuul 1.0.0-SNAPSHOT diff --git a/spring-zuul/spring-zuul-foos-resource/pom.xml b/spring-zuul/spring-zuul-foos-resource/pom.xml index 70e39db4aa..4fe4e1dbbc 100644 --- a/spring-zuul/spring-zuul-foos-resource/pom.xml +++ b/spring-zuul/spring-zuul-foos-resource/pom.xml @@ -1,7 +1,6 @@ 4.0.0 - spring-zuul-foos-resource spring-zuul-foos-resource war diff --git a/spring-zuul/spring-zuul-ui/pom.xml b/spring-zuul/spring-zuul-ui/pom.xml index 159decd331..619e6c6b78 100644 --- a/spring-zuul/spring-zuul-ui/pom.xml +++ b/spring-zuul/spring-zuul-ui/pom.xml @@ -1,7 +1,6 @@ 4.0.0 - spring-zuul-ui spring-zuul-ui war diff --git a/stripe/pom.xml b/stripe/pom.xml index 1e13612fb5..b0cb194bfe 100644 --- a/stripe/pom.xml +++ b/stripe/pom.xml @@ -2,13 +2,12 @@ 4.0.0 - com.baeldung.stripe stripe 0.0.1-SNAPSHOT - jar Stripe Demo project for Stripe API + jar parent-boot-1 diff --git a/struts-2/pom.xml b/struts-2/pom.xml index ac8579d9e0..7f0fba727d 100644 --- a/struts-2/pom.xml +++ b/struts-2/pom.xml @@ -4,8 +4,8 @@ com.baeldung struts-2 0.0.1-SNAPSHOT - pom struts-2 + pom com.baeldung diff --git a/testing-modules/groovy-spock/pom.xml b/testing-modules/groovy-spock/pom.xml index 3dd01c29ab..2a058e5358 100644 --- a/testing-modules/groovy-spock/pom.xml +++ b/testing-modules/groovy-spock/pom.xml @@ -5,8 +5,8 @@ org.spockframework groovy-spock 1.0-SNAPSHOT - jar groovy-spock + jar com.baeldung diff --git a/testing-modules/junit-5/README.md b/testing-modules/junit-5/README.md index 1fbd7a4a5e..4ed01e7fa9 100644 --- a/testing-modules/junit-5/README.md +++ b/testing-modules/junit-5/README.md @@ -16,3 +16,4 @@ - [Running JUnit Tests Programmatically, from a Java Application](https://www.baeldung.com/junit-tests-run-programmatically-from-java) - [Testing an Abstract Class With JUnit](https://www.baeldung.com/junit-test-abstract-class) - [A Quick JUnit vs TestNG Comparison](http://www.baeldung.com/junit-vs-testng) +- [Guide to JUnit 5 Parameterized Tests](https://www.baeldung.com/parameterized-tests-junit-5) diff --git a/testing-modules/junit5-migration/pom.xml b/testing-modules/junit5-migration/pom.xml index 9d9d418774..536953afc8 100644 --- a/testing-modules/junit5-migration/pom.xml +++ b/testing-modules/junit5-migration/pom.xml @@ -1,9 +1,7 @@ - 4.0.0 - junit5-migration 1.0-SNAPSHOT junit5-migration diff --git a/testing-modules/load-testing-comparison/pom.xml b/testing-modules/load-testing-comparison/pom.xml index 42614d310b..63472d0467 100644 --- a/testing-modules/load-testing-comparison/pom.xml +++ b/testing-modules/load-testing-comparison/pom.xml @@ -13,19 +13,6 @@ ../../pom.xml - - 1.8 - 1.8 - UTF-8 - 2.11.12 - 2.2.5 - 3.2.2 - 2.2.1 - 5.0 - 3.11 - 2.0.5.RELEASE - - io.gatling @@ -146,4 +133,18 @@ + + + 1.8 + 1.8 + UTF-8 + 2.11.12 + 2.2.5 + 3.2.2 + 2.2.1 + 5.0 + 3.11 + 2.0.5.RELEASE + + \ No newline at end of file diff --git a/testing-modules/mockito-2/pom.xml b/testing-modules/mockito-2/pom.xml index 5f60566566..e319dd9edd 100644 --- a/testing-modules/mockito-2/pom.xml +++ b/testing-modules/mockito-2/pom.xml @@ -4,8 +4,8 @@ com.baeldung mockito-2 0.0.1-SNAPSHOT - jar mockito-2 + jar com.baeldung diff --git a/testing-modules/mocks/pom.xml b/testing-modules/mocks/pom.xml index 6473f07c13..ecc8b61a6d 100644 --- a/testing-modules/mocks/pom.xml +++ b/testing-modules/mocks/pom.xml @@ -1,6 +1,9 @@ 4.0.0 + mocks + mocks + pom com.baeldung @@ -9,10 +12,6 @@ ../../ - mocks - mocks - pom - mock-comparisons jmockit diff --git a/testing-modules/parallel-tests-junit/math-test-functions/pom.xml b/testing-modules/parallel-tests-junit/math-test-functions/pom.xml index 18d2b562f3..a3569714ef 100644 --- a/testing-modules/parallel-tests-junit/math-test-functions/pom.xml +++ b/testing-modules/parallel-tests-junit/math-test-functions/pom.xml @@ -4,17 +4,16 @@ xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 4.0.0 + math-test-functions + math-test-functions + http://maven.apache.org + com.baeldung parallel-tests-junit 0.0.1-SNAPSHOT - math-test-functions - math-test-functions - http://maven.apache.org - - UTF-8 - + junit @@ -23,6 +22,7 @@ test + @@ -45,4 +45,8 @@ + + + UTF-8 + diff --git a/testing-modules/parallel-tests-junit/pom.xml b/testing-modules/parallel-tests-junit/pom.xml index ecca8b3930..f400a5ae07 100644 --- a/testing-modules/parallel-tests-junit/pom.xml +++ b/testing-modules/parallel-tests-junit/pom.xml @@ -1,14 +1,15 @@ - 4.0.0 - com.baeldung - parallel-tests-junit - 0.0.1-SNAPSHOT - pom - parallel-tests-junit - - - math-test-functions - string-test-functions - + 4.0.0 + com.baeldung + parallel-tests-junit + 0.0.1-SNAPSHOT + parallel-tests-junit + pom + + + math-test-functions + string-test-functions + + diff --git a/testing-modules/parallel-tests-junit/string-test-functions/pom.xml b/testing-modules/parallel-tests-junit/string-test-functions/pom.xml index af61cfce8e..7fa09ff493 100644 --- a/testing-modules/parallel-tests-junit/string-test-functions/pom.xml +++ b/testing-modules/parallel-tests-junit/string-test-functions/pom.xml @@ -4,17 +4,15 @@ xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 4.0.0 + string-test-functions + string-test-functions + http://maven.apache.org + com.baeldung parallel-tests-junit 0.0.1-SNAPSHOT - string-test-functions - string-test-functions - http://maven.apache.org - - UTF-8 - @@ -24,6 +22,7 @@ test + @@ -38,4 +37,8 @@ + + + UTF-8 + diff --git a/testing-modules/rest-testing/pom.xml b/testing-modules/rest-testing/pom.xml index 2fa303a98e..2b1f146f0f 100644 --- a/testing-modules/rest-testing/pom.xml +++ b/testing-modules/rest-testing/pom.xml @@ -1,7 +1,6 @@ 4.0.0 - com.baeldung rest-testing 0.1-SNAPSHOT diff --git a/testing-modules/testng/pom.xml b/testing-modules/testng/pom.xml index a9f680aafb..8389604717 100644 --- a/testing-modules/testng/pom.xml +++ b/testing-modules/testng/pom.xml @@ -4,8 +4,8 @@ 4.0.0 testng 0.1.0-SNAPSHOT - jar testng + jar com.baeldung diff --git a/undertow/pom.xml b/undertow/pom.xml index d000956aee..1c2cc3aa36 100644 --- a/undertow/pom.xml +++ b/undertow/pom.xml @@ -1,12 +1,11 @@ 4.0.0 - com.baeldung.undertow undertow - jar 1.0-SNAPSHOT undertow + jar http://maven.apache.org diff --git a/vaadin/pom.xml b/vaadin/pom.xml index c34ffa3636..d24b3dff1b 100644 --- a/vaadin/pom.xml +++ b/vaadin/pom.xml @@ -2,12 +2,11 @@ 4.0.0 - org.test vaadin - war 1.0-SNAPSHOT Vaadin + war parent-boot-2 diff --git a/vertx/pom.xml b/vertx/pom.xml index 7e494c5914..befd4c45bb 100644 --- a/vertx/pom.xml +++ b/vertx/pom.xml @@ -2,7 +2,6 @@ 4.0.0 - com.baeldung vertx 1.0-SNAPSHOT diff --git a/video-tutorials/pom.xml b/video-tutorials/pom.xml index ca3b39904f..a798f77863 100644 --- a/video-tutorials/pom.xml +++ b/video-tutorials/pom.xml @@ -1,12 +1,11 @@ 4.0.0 - com.baeldung video-tutorials 1.0.0-SNAPSHOT - pom video-tutorials + pom com.baeldung diff --git a/vraptor/pom.xml b/vraptor/pom.xml index 97005bd158..214a44cede 100644 --- a/vraptor/pom.xml +++ b/vraptor/pom.xml @@ -4,8 +4,8 @@ com.baeldung vraptor 1.0.0 - war vraptor + war A demo project to start using VRaptor 4 diff --git a/wicket/pom.xml b/wicket/pom.xml index 99be467167..80c728e3a5 100644 --- a/wicket/pom.xml +++ b/wicket/pom.xml @@ -2,12 +2,11 @@ 4.0.0 - com.baeldung.wicket.examples wicket - war 1.0-SNAPSHOT Wicket + war com.baeldung diff --git a/xstream/pom.xml b/xstream/pom.xml index 64c8198082..f75e10fc7d 100644 --- a/xstream/pom.xml +++ b/xstream/pom.xml @@ -1,7 +1,6 @@ 4.0.0 - org.baeldung xstream 0.0.1-SNAPSHOT