Merge branch 'eugenp:master' into master
This commit is contained in:
commit
44932b2cbe
|
@ -6,3 +6,4 @@ This module contains articles about AWS Lambda
|
|||
- [Using AWS Lambda with API Gateway](https://www.baeldung.com/aws-lambda-api-gateway)
|
||||
- [Introduction to AWS Serverless Application Model](https://www.baeldung.com/aws-serverless)
|
||||
- [How to Implement Hibernate in an AWS Lambda Function in Java](https://www.baeldung.com/java-aws-lambda-hibernate)
|
||||
- [Writing an Enterprise-Grade AWS Lambda in Java](https://www.baeldung.com/java-enterprise-aws-lambda)
|
||||
|
|
|
@ -0,0 +1,10 @@
|
|||
package com.baeldung.java9.interfaces;
|
||||
|
||||
public class CustomFoo implements Foo {
|
||||
|
||||
public static void main(String... args) {
|
||||
Foo customFoo = new CustomFoo();
|
||||
customFoo.bar(); // 'Hello world!'
|
||||
Foo.buzz(); // 'Hello static world!'
|
||||
}
|
||||
}
|
|
@ -0,0 +1,22 @@
|
|||
package com.baeldung.java9.interfaces;
|
||||
|
||||
public interface Foo {
|
||||
|
||||
public default void bar() {
|
||||
System.out.print("Hello");
|
||||
baz();
|
||||
}
|
||||
|
||||
public static void buzz() {
|
||||
System.out.print("Hello");
|
||||
staticBaz();
|
||||
}
|
||||
|
||||
private void baz() {
|
||||
System.out.print(" world!");
|
||||
}
|
||||
|
||||
private static void staticBaz() {
|
||||
System.out.print(" static world!");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,38 @@
|
|||
package com.baeldung.java9.interfaces;
|
||||
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.PrintStream;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
class CustomFooUnitTest {
|
||||
private ByteArrayOutputStream outContent = new ByteArrayOutputStream();
|
||||
private PrintStream originalOut = System.out;
|
||||
|
||||
@BeforeEach
|
||||
void setup() {
|
||||
System.setOut(new PrintStream(outContent));
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() {
|
||||
System.setOut(originalOut);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenACustomFooObject_whenCallingDefaultMethodBar_thenExpectedStringIsWrittenToSystemOut() {
|
||||
CustomFoo customFoo = new CustomFoo();
|
||||
customFoo.bar();
|
||||
assertThat(outContent.toString()).isEqualTo("Hello world!");
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenAFooInterface_whenCallingStaticMethodBuzz_thenExpectedStringIsWrittenToSystemOut() {
|
||||
Foo.buzz();
|
||||
assertThat(outContent.toString()).isEqualTo("Hello static world!");
|
||||
}
|
||||
}
|
|
@ -8,3 +8,4 @@ This module contains complete guides about arrays in Java
|
|||
- [What is \[Ljava.lang.Object;?](https://www.baeldung.com/java-tostring-array)
|
||||
- [Guide to ArrayStoreException](https://www.baeldung.com/java-arraystoreexception)
|
||||
- [Creating a Generic Array in Java](https://www.baeldung.com/java-generic-array)
|
||||
- [Maximum Size of Java Arrays](https://www.baeldung.com/java-arrays-max-size)
|
||||
|
|
|
@ -8,3 +8,4 @@
|
|||
- [Localizing Exception Messages in Java](https://www.baeldung.com/java-localize-exception-messages)
|
||||
- [Explanation of ClassCastException in Java](https://www.baeldung.com/java-classcastexception)
|
||||
- [NoSuchFieldError in Java](https://www.baeldung.com/java-nosuchfielderror)
|
||||
- [IllegalAccessError in Java](https://www.baeldung.com/java-illegalaccesserror)
|
||||
|
|
|
@ -5,4 +5,5 @@ This module contains articles about networking in Java
|
|||
### Relevant Articles
|
||||
|
||||
- [Finding a Free Port in Java](https://www.baeldung.com/java-free-port)
|
||||
- [Downloading Email Attachments in Java](https://www.baeldung.com/java-download-email-attachments)
|
||||
- [[<-- Prev]](/core-java-modules/core-java-networking-2)
|
||||
|
|
|
@ -5,3 +5,4 @@
|
|||
- [Checking If a Method is Static Using Reflection in Java](https://www.baeldung.com/java-check-method-is-static)
|
||||
- [Checking if a Java Class is ‘abstract’ Using Reflection](https://www.baeldung.com/java-reflection-is-class-abstract)
|
||||
- [Invoking a Private Method in Java](https://www.baeldung.com/java-call-private-method)
|
||||
- [Finding All Classes in a Java Package](https://www.baeldung.com/java-find-all-classes-in-package)
|
||||
|
|
|
@ -13,3 +13,5 @@
|
|||
- [Regular Expressions \s and \s+ in Java](https://www.baeldung.com/java-regex-s-splus)
|
||||
- [Validate Phone Numbers With Java Regex](https://www.baeldung.com/java-regex-validate-phone-numbers)
|
||||
- [How to Count the Number of Matches for a Regex?](https://www.baeldung.com/java-count-regex-matches)
|
||||
- [Find All Numbers in a String in Java](https://www.baeldung.com/java-find-numbers-in-string)
|
||||
- [Understanding the Pattern.quote Method](https://www.baeldung.com/java-pattern-quote)
|
||||
|
|
|
@ -12,7 +12,7 @@ public class IgnoringPatternMetacharactersUnitTest {
|
|||
private static final String patternStr = "$100.50";
|
||||
|
||||
@Test
|
||||
public void givenPatternStringHasMetacharacters_whenPatternMatchedWithoutEscapingMetacharacters_thenNoMatchesFound() {
|
||||
public void whenMetacharactersNotEscaped_thenNoMatchesFound() {
|
||||
Pattern pattern = Pattern.compile(patternStr);
|
||||
Matcher matcher = pattern.matcher(dollarAmounts);
|
||||
|
||||
|
@ -25,7 +25,7 @@ public class IgnoringPatternMetacharactersUnitTest {
|
|||
}
|
||||
|
||||
@Test
|
||||
public void givenPatternStringHasMetacharacters_whenPatternCompiledUsingManuallyMetaEscapedPattern_thenMatchingSuccessful() {
|
||||
public void whenMetacharactersManuallyEscaped_thenMatchingSuccessful() {
|
||||
String metaEscapedPatternStr = "\\Q" + patternStr + "\\E";
|
||||
Pattern pattern = Pattern.compile(metaEscapedPatternStr);
|
||||
Matcher matcher = pattern.matcher(dollarAmounts);
|
||||
|
@ -39,7 +39,7 @@ public class IgnoringPatternMetacharactersUnitTest {
|
|||
}
|
||||
|
||||
@Test
|
||||
public void givenPatternStringHasMetacharacters_whenPatternCompiledUsingLiteralPatternFromQuote_thenMatchingSuccessful() {
|
||||
public void whenMetacharactersEscapedUsingPatternQuote_thenMatchingSuccessful() {
|
||||
String literalPatternStr = Pattern.quote(patternStr);
|
||||
Pattern pattern = Pattern.compile(literalPatternStr);
|
||||
Matcher matcher = pattern.matcher(dollarAmounts);
|
||||
|
|
|
@ -4,5 +4,5 @@ This module contains articles about core Java Security
|
|||
|
||||
### Relevant Articles:
|
||||
|
||||
- [Secret Key and String Conversion in Java](https://www.baeldung.com/secret-key-and-string-conversion-in-java/)
|
||||
- [Secret Key and String Conversion in Java](https://www.baeldung.com/java-secret-key-to-string)
|
||||
- More articles: [[<-- prev]](/core-java-modules/core-java-security-2)
|
||||
|
|
|
@ -0,0 +1,3 @@
|
|||
### Relevant Articles:
|
||||
|
||||
- [Using Cucumber with Gradle](https://www.baeldung.com/java-cucumber-gradle)
|
|
@ -0,0 +1,54 @@
|
|||
|
||||
plugins {
|
||||
id 'java'
|
||||
id 'jacoco'
|
||||
}
|
||||
|
||||
ext {
|
||||
junitVersion = '5.7.2'
|
||||
lombokVersion = '1.18.20'
|
||||
}
|
||||
|
||||
group 'com.com.baeldung'
|
||||
version '1.0-SNAPSHOT'
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
}
|
||||
|
||||
java {
|
||||
sourceCompatibility = JavaVersion.VERSION_11
|
||||
targetCompatibility = JavaVersion.VERSION_11
|
||||
}
|
||||
|
||||
dependencies {
|
||||
testImplementation "org.junit.jupiter:junit-jupiter-api:${junitVersion}"
|
||||
testRuntimeOnly "org.junit.jupiter:junit-jupiter-engine:${junitVersion}"
|
||||
|
||||
compileOnly "org.projectlombok:lombok:${lombokVersion}"
|
||||
annotationProcessor "org.projectlombok:lombok:${lombokVersion}"
|
||||
}
|
||||
|
||||
test {
|
||||
useJUnitPlatform()
|
||||
|
||||
finalizedBy jacocoTestReport // report is always generated after tests run
|
||||
}
|
||||
|
||||
jacocoTestReport {
|
||||
dependsOn test // tests are required to run before generating the report
|
||||
|
||||
afterEvaluate {
|
||||
classDirectories.setFrom(files(classDirectories.files.collect {
|
||||
fileTree(dir: it, exclude: [
|
||||
"com/baeldung/**/ExcludedPOJO.class",
|
||||
"com/baeldung/**/*DTO.*",
|
||||
"**/config/*"
|
||||
])
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
jacoco {
|
||||
toolVersion = "0.8.6"
|
||||
}
|
Binary file not shown.
|
@ -0,0 +1,5 @@
|
|||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-6.8-bin.zip
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
|
@ -0,0 +1,185 @@
|
|||
#!/usr/bin/env sh
|
||||
|
||||
#
|
||||
# Copyright 2015 the original author or authors.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# https://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
|
||||
##############################################################################
|
||||
##
|
||||
## 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='"-Xmx64m" "-Xms64m"'
|
||||
|
||||
# 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 or MSYS, switch paths to Windows format before running java
|
||||
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; 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=`expr $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"
|
||||
|
||||
exec "$JAVACMD" "$@"
|
|
@ -0,0 +1,89 @@
|
|||
@rem
|
||||
@rem Copyright 2015 the original author or authors.
|
||||
@rem
|
||||
@rem Licensed under the Apache License, Version 2.0 (the "License");
|
||||
@rem you may not use this file except in compliance with the License.
|
||||
@rem You may obtain a copy of the License at
|
||||
@rem
|
||||
@rem https://www.apache.org/licenses/LICENSE-2.0
|
||||
@rem
|
||||
@rem Unless required by applicable law or agreed to in writing, software
|
||||
@rem distributed under the License is distributed on an "AS IS" BASIS,
|
||||
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
@rem See the License for the specific language governing permissions and
|
||||
@rem limitations under the License.
|
||||
@rem
|
||||
|
||||
@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 Resolve any "." and ".." in APP_HOME to make it shorter.
|
||||
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
|
||||
|
||||
@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="-Xmx64m" "-Xms64m"
|
||||
|
||||
@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 execute
|
||||
|
||||
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 execute
|
||||
|
||||
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
|
||||
|
||||
: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 %*
|
||||
|
||||
: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
|
|
@ -0,0 +1 @@
|
|||
lombok.addLombokGeneratedAnnotation = true
|
|
@ -0,0 +1 @@
|
|||
rootProject.name = 'gradle-jacoco'
|
|
@ -0,0 +1,11 @@
|
|||
package com.baeldung.config;
|
||||
|
||||
import com.baeldung.service.ProductService;
|
||||
|
||||
public class AppConfig {
|
||||
|
||||
public ProductService productService() {
|
||||
return new ProductService();
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,12 @@
|
|||
package com.baeldung.domain;
|
||||
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
|
||||
@Builder
|
||||
@Data
|
||||
public class Product {
|
||||
private int id;
|
||||
private String name;
|
||||
|
||||
}
|
|
@ -0,0 +1,4 @@
|
|||
package com.baeldung.dto;
|
||||
|
||||
public class ExcludedPOJO {
|
||||
}
|
|
@ -0,0 +1,4 @@
|
|||
package com.baeldung.dto;
|
||||
|
||||
public class ProductDTO {
|
||||
}
|
|
@ -0,0 +1,11 @@
|
|||
package com.baeldung.generated;
|
||||
|
||||
@Generated
|
||||
public class Customer {
|
||||
// everything in this class will be excluded from jacoco report because of @Generated
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Customer{}";
|
||||
}
|
||||
}
|
|
@ -0,0 +1,15 @@
|
|||
package com.baeldung.generated;
|
||||
|
||||
import java.lang.annotation.Documented;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
import static java.lang.annotation.ElementType.METHOD;
|
||||
import static java.lang.annotation.ElementType.TYPE;
|
||||
import static java.lang.annotation.RetentionPolicy.RUNTIME;
|
||||
|
||||
@Documented
|
||||
@Retention(RUNTIME)
|
||||
@Target({TYPE, METHOD})
|
||||
public @interface Generated {
|
||||
}
|
|
@ -0,0 +1,16 @@
|
|||
package com.baeldung.service;
|
||||
|
||||
import com.baeldung.generated.Generated;
|
||||
|
||||
public class CustomerService {
|
||||
|
||||
//this method will be excluded from coverage due to @Generated.
|
||||
@Generated
|
||||
public String getProductId() {
|
||||
return "An ID";
|
||||
}
|
||||
|
||||
public String getCustomerName() {
|
||||
return "some name";
|
||||
}
|
||||
}
|
|
@ -0,0 +1,9 @@
|
|||
package com.baeldung.service;
|
||||
|
||||
public class ProductService {
|
||||
private static final double DISCOUNT = 0.25;
|
||||
|
||||
public double getSalePrice(double originalPrice) {
|
||||
return originalPrice - originalPrice * DISCOUNT;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,14 @@
|
|||
package com.baeldung.service;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
|
||||
class CustomerServiceUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenCustomer_whenGetCustomer_thenReturnNewCustomer() {
|
||||
CustomerService customerService = new CustomerService();
|
||||
assertNotNull(customerService.getCustomerName());
|
||||
}
|
||||
}
|
|
@ -0,0 +1,15 @@
|
|||
package com.baeldung.service;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
class ProductServiceUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenOriginalPrice_whenGetSalePrice_thenReturnsDiscountedPrice() {
|
||||
ProductService productService = new ProductService();
|
||||
double salePrice = productService.getSalePrice(100);
|
||||
assertEquals(salePrice, 75);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,6 @@
|
|||
Feature: Account is credited with amount
|
||||
|
||||
Scenario: Credit amount
|
||||
Given account balance is 0.0
|
||||
When the account is credited with 10.0
|
||||
Then account should have a balance of 10.0
|
|
@ -44,6 +44,12 @@
|
|||
<version>${hamcrest.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.vavr</groupId>
|
||||
<artifactId>vavr</artifactId>
|
||||
<version>0.10.3</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
|
|
|
@ -0,0 +1,74 @@
|
|||
package com.baeldung.setiteration;
|
||||
|
||||
import com.google.common.collect.Sets;
|
||||
import io.vavr.collection.Stream;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Iterator;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
class SetIteration {
|
||||
|
||||
@Test
|
||||
void givenSet_whenIteratorUsed_shouldIterateOverElements() {
|
||||
// given
|
||||
Set<String> names = Sets.newHashSet("Tom", "Jane", "Karen");
|
||||
|
||||
// when
|
||||
Iterator<String> namesIterator1 = names.iterator();
|
||||
Iterator<String> namesIterator2 = names.iterator();
|
||||
|
||||
// then
|
||||
namesIterator1.forEachRemaining(System.out::println);
|
||||
while(namesIterator2.hasNext()) {
|
||||
System.out.println(namesIterator2.next());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenSet_whenStreamUsed_shouldIterateOverElements() {
|
||||
// given
|
||||
Set<String> names = Sets.newHashSet("Tom", "Jane", "Karen");
|
||||
|
||||
// when & then
|
||||
String namesJoined = names.stream()
|
||||
.map(String::toUpperCase)
|
||||
.peek(System.out::println)
|
||||
.collect(Collectors.joining());
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenSet_whenEnhancedLoopUsed_shouldIterateOverElements() {
|
||||
// given
|
||||
Set<String> names = Sets.newHashSet("Tom", "Jane", "Karen");
|
||||
|
||||
// when & then
|
||||
for (String name : names) {
|
||||
System.out.println(name);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenSet_whenMappedToArray_shouldIterateOverElements() {
|
||||
// given
|
||||
Set<String> names = Sets.newHashSet("Tom", "Jane", "Karen");
|
||||
|
||||
// when & then
|
||||
Object[] namesArray = names.toArray();
|
||||
for (int i = 0; i < namesArray.length; i++) {
|
||||
System.out.println(i + ": " + namesArray[i]);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenSet_whenZippedWithIndex_shouldIterateOverElements() {
|
||||
// given
|
||||
Set<String> names = Sets.newHashSet("Tom", "Jane", "Karen");
|
||||
|
||||
// when & then
|
||||
Stream.ofAll(names)
|
||||
.zipWithIndex()
|
||||
.forEach(t -> System.out.println(t._2() + ": " + t._1()));
|
||||
}
|
||||
}
|
|
@ -17,3 +17,4 @@ If you get a valid response, then you're good to go.
|
|||
- [Paging and Async Calls with the Kubernetes API](https://www.baeldung.com/java-kubernetes-paging-async)
|
||||
- [Using Watch with the Kubernetes API](https://www.baeldung.com/java-kubernetes-watch)
|
||||
- [Using Namespaces and Selectors With the Kubernetes Java API](https://www.baeldung.com/java-kubernetes-namespaces-selectors)
|
||||
- [Creating, Updating and Deleting Resources with the Java Kubernetes API](https://www.baeldung.com/java-kubernetes-api-crud)
|
||||
|
|
|
@ -3,7 +3,7 @@
|
|||
This module contains articles about libraries for data processing in Java.
|
||||
|
||||
### Relevant articles
|
||||
- [Kafka Streams vs Kafka Consumer]()
|
||||
- [Kafka Streams vs Kafka Consumer](https://www.baeldung.com/java-kafka-streams-vs-kafka-consumer)
|
||||
- More articles: [[<-- prev]](/../libraries-data-2)
|
||||
|
||||
##### Building the project
|
||||
|
|
|
@ -3,3 +3,4 @@
|
|||
- [Introduction to SLF4J](http://www.baeldung.com/slf4j-with-log4j2-logback)
|
||||
- [A Guide to Rolling File Appenders](http://www.baeldung.com/java-logging-rolling-file-appenders)
|
||||
- [Logging Exceptions Using SLF4J](https://www.baeldung.com/slf4j-log-exceptions)
|
||||
- [Log4j Warning: "No Appenders Could Be Found for Logger"](https://www.baeldung.com/log4j-no-appenders-found)
|
||||
|
|
|
@ -0,0 +1,18 @@
|
|||
package com.baeldung.log4j;
|
||||
|
||||
import org.apache.log4j.Logger;
|
||||
|
||||
public class NoAppenderExample {
|
||||
|
||||
private final static Logger logger = Logger.getLogger(NoAppenderExample.class);
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
//Setup default appender
|
||||
//BasicConfigurator.configure();
|
||||
|
||||
//Define path to configuration file
|
||||
//PropertyConfigurator.configure("src\\main\\resources\\log4j.properties");
|
||||
logger.info("Info log message");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,5 @@
|
|||
log4j.rootLogger=INFO, stdout
|
||||
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
|
||||
log4j.appender.stdout.Target=System.out
|
||||
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
|
||||
log4j.appender.stdout.layout.ConversionPattern=%d{yy/MM/dd HH:mm:ss} %p %c{2}: %m%n
|
|
@ -90,6 +90,8 @@
|
|||
<appender-ref ref="roll-by-time-and-size"/>
|
||||
</category>
|
||||
|
||||
<logger name="com.baeldung.log4j.NoAppenderExample"/>
|
||||
|
||||
<root>
|
||||
<level value="DEBUG"/>
|
||||
<appender-ref ref="stdout"/>
|
||||
|
|
|
@ -34,7 +34,12 @@
|
|||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<version>${org.projectlombok.version}</version>
|
||||
<version>${lombok.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok-mapstruct-binding</artifactId>
|
||||
<version>${lombok.mapstruct.binding.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
|
@ -63,7 +68,12 @@
|
|||
<path>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<version>${org.projectlombok.version}</version>
|
||||
<version>${lombok.version}</version>
|
||||
</path>
|
||||
<path>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok-mapstruct-binding</artifactId>
|
||||
<version>${lombok.mapstruct.binding.version}</version>
|
||||
</path>
|
||||
</annotationProcessorPaths>
|
||||
</configuration>
|
||||
|
@ -72,11 +82,11 @@
|
|||
</build>
|
||||
|
||||
<properties>
|
||||
<org.mapstruct.version>1.3.1.Final</org.mapstruct.version>
|
||||
<org.mapstruct.version>1.4.2.Final</org.mapstruct.version>
|
||||
<springframework.version>4.3.4.RELEASE</springframework.version>
|
||||
<maven.compiler.source>1.8</maven.compiler.source>
|
||||
<maven.compiler.target>1.8</maven.compiler.target>
|
||||
<org.projectlombok.version>1.18.4</org.projectlombok.version>
|
||||
<lombok.mapstruct.binding.version>0.2.0</lombok.mapstruct.binding.version>
|
||||
<assertj.version>3.16.1</assertj.version>
|
||||
</properties>
|
||||
|
||||
|
|
|
@ -0,0 +1,26 @@
|
|||
package com.baeldung.insertnull;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
|
||||
public class DBConfig {
|
||||
|
||||
private static Connection INSTANCE;
|
||||
|
||||
public static Connection getConnection() throws SQLException {
|
||||
if (INSTANCE == null) {
|
||||
INSTANCE = DriverManager.getConnection("jdbc:h2:mem:insertnull", "user", "password");
|
||||
createPersonTable();
|
||||
}
|
||||
return INSTANCE;
|
||||
}
|
||||
|
||||
private static void createPersonTable() throws SQLException {
|
||||
try(Statement statement = INSTANCE.createStatement()) {
|
||||
String sql = "CREATE TABLE Person (id INTEGER not null, name VARCHAR(50), lastName VARCHAR(50), age INTEGER, PRIMARY KEY (id))";
|
||||
statement.executeUpdate(sql);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,48 @@
|
|||
package com.baeldung.insertnull;
|
||||
|
||||
public class Person {
|
||||
|
||||
private Integer id;
|
||||
private String name;
|
||||
private String lastName;
|
||||
private Integer age;
|
||||
|
||||
public Person(Integer id, String name, String lastName, Integer age) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
this.lastName = lastName;
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public Integer getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Integer id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getLastName() {
|
||||
return lastName;
|
||||
}
|
||||
|
||||
public void setLastName(String lastName) {
|
||||
this.lastName = lastName;
|
||||
}
|
||||
|
||||
public Integer getAge() {
|
||||
return age;
|
||||
}
|
||||
|
||||
public void setAge(Integer age) {
|
||||
this.age = age;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,50 @@
|
|||
package com.baeldung.insertnull;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Types;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.equalTo;
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
|
||||
public class InsertNullUnitTest {
|
||||
|
||||
private final String SQL = "INSERT INTO Person VALUES(?,?,?,?)";
|
||||
|
||||
@Test
|
||||
public void givenNewPerson_whenSetNullIsUsed_thenNewRecordIsCreated() throws SQLException {
|
||||
Person person = new Person(1, "John", "Doe", null);
|
||||
|
||||
try (PreparedStatement preparedStatement = DBConfig.getConnection().prepareStatement(SQL)) {
|
||||
preparedStatement.setInt(1, person.getId());
|
||||
preparedStatement.setString(2, person.getName());
|
||||
preparedStatement.setString(3, person.getLastName());
|
||||
if (person.getAge() == null) {
|
||||
preparedStatement.setNull(4, Types.INTEGER);
|
||||
}
|
||||
else {
|
||||
preparedStatement.setInt(4, person.getAge());
|
||||
}
|
||||
int noOfRows = preparedStatement.executeUpdate();
|
||||
|
||||
assertThat(noOfRows, equalTo(1));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNewPerson_whenSetObjectIsUsed_thenNewRecordIsCreated() throws SQLException {
|
||||
Person person = new Person(2, "John", "Doe", null);
|
||||
|
||||
try (PreparedStatement preparedStatement = DBConfig.getConnection().prepareStatement(SQL)) {
|
||||
preparedStatement.setInt(1, person.getId());
|
||||
preparedStatement.setString(2, person.getName());
|
||||
preparedStatement.setString(3, person.getLastName());
|
||||
preparedStatement.setObject(4, person.getAge(), Types.INTEGER);
|
||||
int noOfRows = preparedStatement.executeUpdate();
|
||||
|
||||
assertThat(noOfRows, equalTo(1));
|
||||
}
|
||||
}
|
||||
}
|
|
@ -11,3 +11,5 @@ This module contains articles about the Java Persistence API (JPA) in Java.
|
|||
- [A Guide to MultipleBagFetchException in Hibernate](https://www.baeldung.com/java-hibernate-multiplebagfetchexception)
|
||||
- [How to Convert a Hibernate Proxy to a Real Entity Object](https://www.baeldung.com/hibernate-proxy-to-real-entity-object)
|
||||
- [Returning an Auto-Generated Id with JPA](https://www.baeldung.com/jpa-get-auto-generated-id)
|
||||
- [How to Return Multiple Entities In JPA Query](https://www.baeldung.com/jpa-return-multiple-entities)
|
||||
- [Defining Unique Constraints in JPA](https://www.baeldung.com/jpa-unique-constraints)
|
||||
|
|
|
@ -0,0 +1,37 @@
|
|||
package com.baeldung.jpa.uniqueconstraints;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.Table;
|
||||
|
||||
@Entity
|
||||
@Table
|
||||
public class Address implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@Id
|
||||
@GeneratedValue
|
||||
private Long id;
|
||||
|
||||
private String streetAddress;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getStreetAddress() {
|
||||
return streetAddress;
|
||||
}
|
||||
|
||||
public void setStreetAddress(String streetAddress) {
|
||||
this.streetAddress = streetAddress;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,116 @@
|
|||
package com.baeldung.jpa.uniqueconstraints;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.JoinColumn;
|
||||
import javax.persistence.Table;
|
||||
import javax.persistence.UniqueConstraint;
|
||||
|
||||
@Entity
|
||||
@Table(uniqueConstraints = { @UniqueConstraint(name = "UniqueNumberAndStatus", columnNames = { "personNumber", "isActive" }),
|
||||
@UniqueConstraint(name = "UniqueSecurityAndDepartment", columnNames = { "securityNumber", "departmentCode" }),
|
||||
@UniqueConstraint(name = "UniqueNumberAndAddress", columnNames = { "personNumber", "address" }) })
|
||||
public class Person implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@Id
|
||||
@GeneratedValue
|
||||
private Long id;
|
||||
|
||||
private String name;
|
||||
|
||||
private String password;
|
||||
|
||||
@Column(unique = true)
|
||||
private String email;
|
||||
|
||||
@Column(unique = true)
|
||||
private Long personNumber;
|
||||
|
||||
private Boolean isActive;
|
||||
|
||||
private String securityNumber;
|
||||
|
||||
private String departmentCode;
|
||||
|
||||
@Column(unique = true)
|
||||
@JoinColumn(name = "addressId", referencedColumnName = "id")
|
||||
private Address address;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
public void setEmail(String email) {
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
public Long getPersonNumber() {
|
||||
return personNumber;
|
||||
}
|
||||
|
||||
public void setPersonNumber(Long personNumber) {
|
||||
this.personNumber = personNumber;
|
||||
}
|
||||
|
||||
public Boolean getIsActive() {
|
||||
return isActive;
|
||||
}
|
||||
|
||||
public void setIsActive(Boolean isActive) {
|
||||
this.isActive = isActive;
|
||||
}
|
||||
|
||||
public String getScode() {
|
||||
return securityNumber;
|
||||
}
|
||||
|
||||
public void setScode(String scode) {
|
||||
this.securityNumber = scode;
|
||||
}
|
||||
|
||||
public String getDcode() {
|
||||
return departmentCode;
|
||||
}
|
||||
|
||||
public void setDcode(String dcode) {
|
||||
this.departmentCode = dcode;
|
||||
}
|
||||
|
||||
public Address getAddress() {
|
||||
return address;
|
||||
}
|
||||
|
||||
public void setAddress(Address address) {
|
||||
this.address = address;
|
||||
}
|
||||
}
|
|
@ -113,6 +113,22 @@
|
|||
<property name="hibernate.temp.use_jdbc_metadata_defaults" value="false"/>
|
||||
</properties>
|
||||
</persistence-unit>
|
||||
<persistence-unit name="jpa-unique-constraints">
|
||||
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
|
||||
<class>com.baeldung.jpa.uniqueconstraints.Person</class>
|
||||
<class>com.baeldung.jpa.uniqueconstraints.Address</class>
|
||||
<exclude-unlisted-classes>true</exclude-unlisted-classes>
|
||||
<properties>
|
||||
<property name="javax.persistence.jdbc.driver" value="org.h2.Driver" />
|
||||
<property name="javax.persistence.jdbc.url" value="jdbc:h2:mem:test" />
|
||||
<property name="javax.persistence.jdbc.user" value="sa" />
|
||||
<property name="javax.persistence.jdbc.password" value="" />
|
||||
<property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect" />
|
||||
<property name="hibernate.hbm2ddl.auto" value="create-drop" />
|
||||
<property name="show_sql" value="true" />
|
||||
<property name="hibernate.temp.use_jdbc_metadata_defaults" value="false" />
|
||||
</properties>
|
||||
</persistence-unit>
|
||||
<persistence-unit name="jpa-h2-return-multiple-entities">
|
||||
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
|
||||
<class>com.baeldung.jpa.returnmultipleentities.Channel</class>
|
||||
|
|
|
@ -0,0 +1,119 @@
|
|||
package com.baeldung.jpa.uniqueconstraints;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.EntityManagerFactory;
|
||||
import javax.persistence.Persistence;
|
||||
|
||||
import org.hibernate.exception.ConstraintViolationException;
|
||||
import org.junit.Assert;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class UniqueColumnIntegrationTest {
|
||||
|
||||
private static EntityManagerFactory factory;
|
||||
private static EntityManager entityManager;
|
||||
|
||||
@BeforeAll
|
||||
public static void setup() {
|
||||
factory = Persistence.createEntityManagerFactory("jpa-unique-constraints");
|
||||
entityManager = factory.createEntityManager();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPersistPersonWithSameNumber_thenConstraintViolationException() {
|
||||
Person person1 = new Person();
|
||||
person1.setPersonNumber(2000L);
|
||||
person1.setEmail("john.beth@gmail.com");
|
||||
|
||||
Person person2 = new Person();
|
||||
person2.setPersonNumber(2000L);
|
||||
person2.setEmail("anthony.green@gmail.com");
|
||||
|
||||
entityManager.getTransaction().begin();
|
||||
entityManager.persist(person1);
|
||||
entityManager.getTransaction().commit();
|
||||
|
||||
entityManager.getTransaction().begin();
|
||||
try {
|
||||
entityManager.persist(person2);
|
||||
entityManager.getTransaction().commit();
|
||||
Assert.fail("Should raise an exception - unique key violation");
|
||||
} catch (Exception ex) {
|
||||
Assert.assertTrue(Optional.of(ex)
|
||||
.map(Throwable::getCause)
|
||||
.map(Throwable::getCause)
|
||||
.filter(x -> x instanceof ConstraintViolationException)
|
||||
.isPresent());
|
||||
} finally {
|
||||
entityManager.getTransaction().rollback();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPersistPersonWithSameEmail_thenConstraintViolationException() {
|
||||
Person person1 = new Person();
|
||||
person1.setPersonNumber(4000L);
|
||||
person1.setEmail("timm.beth@gmail.com");
|
||||
|
||||
Person person2 = new Person();
|
||||
person2.setPersonNumber(3000L);
|
||||
person2.setEmail("timm.beth@gmail.com");
|
||||
|
||||
entityManager.getTransaction().begin();
|
||||
entityManager.persist(person1);
|
||||
entityManager.getTransaction().commit();
|
||||
|
||||
entityManager.getTransaction().begin();
|
||||
try {
|
||||
entityManager.persist(person2);
|
||||
entityManager.getTransaction().commit();
|
||||
Assert.fail("Should raise an exception - unique key violation");
|
||||
} catch (Exception ex) {
|
||||
Assert.assertTrue(Optional.of(ex)
|
||||
.map(Throwable::getCause)
|
||||
.map(Throwable::getCause)
|
||||
.filter(x -> x instanceof ConstraintViolationException)
|
||||
.isPresent());
|
||||
} finally {
|
||||
entityManager.getTransaction().rollback();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPersistPersonWithSameAddress_thenConstraintViolationException() {
|
||||
Person person1 = new Person();
|
||||
person1.setPersonNumber(5000L);
|
||||
person1.setEmail("chris.beck@gmail.com");
|
||||
|
||||
Address address1 = new Address();
|
||||
address1.setStreetAddress("20 Street");
|
||||
person1.setAddress(address1);
|
||||
|
||||
Person person2 = new Person();
|
||||
person2.setPersonNumber(6000L);
|
||||
person2.setEmail("mark.jonson@gmail.com");
|
||||
person2.setAddress(address1);
|
||||
|
||||
entityManager.getTransaction().begin();
|
||||
entityManager.persist(person1);
|
||||
entityManager.getTransaction().commit();
|
||||
|
||||
entityManager.getTransaction().begin();
|
||||
try {
|
||||
entityManager.persist(person2);
|
||||
entityManager.getTransaction().commit();
|
||||
Assert.fail("Should raise an exception - unique key violation");
|
||||
} catch (Exception ex) {
|
||||
Assert.assertTrue(Optional.of(ex)
|
||||
.map(Throwable::getCause)
|
||||
.map(Throwable::getCause)
|
||||
.filter(x -> x instanceof ConstraintViolationException)
|
||||
.isPresent());
|
||||
} finally {
|
||||
entityManager.getTransaction().rollback();
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,116 @@
|
|||
package com.baeldung.jpa.uniqueconstraints;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.EntityManagerFactory;
|
||||
import javax.persistence.Persistence;
|
||||
|
||||
import org.hibernate.exception.ConstraintViolationException;
|
||||
import org.junit.Assert;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class UniqueConstraintIntegrationTest {
|
||||
private static EntityManagerFactory factory;
|
||||
private static EntityManager entityManager;
|
||||
|
||||
@BeforeAll
|
||||
public static void setup() {
|
||||
factory = Persistence.createEntityManagerFactory("jpa-unique-constraints");
|
||||
entityManager = factory.createEntityManager();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPersistPersonWithSameNumberAndStatus_thenConstraintViolationException() {
|
||||
Person person1 = new Person();
|
||||
person1.setPersonNumber(12345L);
|
||||
person1.setIsActive(Boolean.TRUE);
|
||||
|
||||
Person person2 = new Person();
|
||||
person2.setPersonNumber(12345L);
|
||||
person2.setIsActive(Boolean.TRUE);
|
||||
|
||||
entityManager.getTransaction().begin();
|
||||
entityManager.persist(person1);
|
||||
entityManager.getTransaction().commit();
|
||||
|
||||
entityManager.getTransaction().begin();
|
||||
try {
|
||||
entityManager.persist(person2);
|
||||
entityManager.getTransaction().commit();
|
||||
Assert.fail("Should raise an exception - unique key violation");
|
||||
} catch (Exception ex) {
|
||||
Assert.assertTrue(Optional.of(ex)
|
||||
.map(Throwable::getCause)
|
||||
.map(Throwable::getCause)
|
||||
.filter(x -> x instanceof ConstraintViolationException)
|
||||
.isPresent());
|
||||
} finally {
|
||||
entityManager.getTransaction().rollback();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPersistPersonWithSameSCodeAndDecode_thenConstraintViolationException() {
|
||||
Person person1 = new Person();
|
||||
person1.setDcode("Sec1");
|
||||
person1.setScode("Axybg356");
|
||||
|
||||
Person person2 = new Person();
|
||||
person2.setDcode("Sec1");
|
||||
person2.setScode("Axybg356");
|
||||
|
||||
entityManager.getTransaction().begin();
|
||||
entityManager.persist(person1);
|
||||
entityManager.getTransaction().commit();
|
||||
|
||||
entityManager.getTransaction().begin();
|
||||
try {
|
||||
entityManager.persist(person2);
|
||||
entityManager.getTransaction().commit();
|
||||
Assert.fail("Should raise an exception - unique key violation");
|
||||
} catch (Exception ex) {
|
||||
Assert.assertTrue(Optional.of(ex)
|
||||
.map(Throwable::getCause)
|
||||
.map(Throwable::getCause)
|
||||
.filter(x -> x instanceof ConstraintViolationException)
|
||||
.isPresent());
|
||||
} finally {
|
||||
entityManager.getTransaction().rollback();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPersistPersonWithSameNumberAndAddress_thenConstraintViolationException() {
|
||||
Address address1 = new Address();
|
||||
address1.setStreetAddress("40 Street");
|
||||
|
||||
Person person1 = new Person();
|
||||
person1.setPersonNumber(54321L);
|
||||
person1.setAddress(address1);
|
||||
|
||||
Person person2 = new Person();
|
||||
person2.setPersonNumber(99999L);
|
||||
person2.setAddress(address1);
|
||||
|
||||
entityManager.getTransaction().begin();
|
||||
entityManager.persist(person1);
|
||||
entityManager.getTransaction().commit();
|
||||
|
||||
entityManager.getTransaction().begin();
|
||||
try {
|
||||
entityManager.persist(person2);
|
||||
entityManager.getTransaction().commit();
|
||||
Assert.fail("Should raise an exception - unique key violation");
|
||||
} catch (Exception ex) {
|
||||
Assert.assertTrue(Optional.of(ex)
|
||||
.map(Throwable::getCause)
|
||||
.map(Throwable::getCause)
|
||||
.filter(x -> x instanceof ConstraintViolationException)
|
||||
.isPresent());
|
||||
} finally {
|
||||
entityManager.getTransaction().rollback();
|
||||
}
|
||||
}
|
||||
}
|
|
@ -9,3 +9,4 @@ This module contains articles about Reactor Core.
|
|||
- [Programmatically Creating Sequences with Project Reactor](https://www.baeldung.com/flux-sequences-reactor)
|
||||
- [How to Extract a Mono’s Content in Java](https://www.baeldung.com/java-string-from-mono)
|
||||
- [How to Convert Mono<List<T\>> Into Flux<T\>](https://www.baeldung.com/java-mono-list-to-flux)
|
||||
- [Project Reactor: map() vs flatMap()](https://www.baeldung.com/java-reactor-map-flatmap)
|
||||
|
|
|
@ -73,6 +73,7 @@
|
|||
<module>spring-boot-actuator</module>
|
||||
<module>spring-boot-data-2</module>
|
||||
<module>spring-boot-react</module>
|
||||
<module>spring-boot-validation</module>
|
||||
</modules>
|
||||
|
||||
<dependencyManagement>
|
||||
|
|
|
@ -5,3 +5,4 @@ This module contains articles about Spring Boot Exceptions
|
|||
### Relevant Articles:
|
||||
|
||||
- [The BeanDefinitionOverrideException in Spring Boot](https://www.baeldung.com/spring-boot-bean-definition-override-exception)
|
||||
- [Spring Boot Error ApplicationContextException](https://www.baeldung.com/spring-boot-application-context-exception)
|
||||
|
|
|
@ -15,6 +15,14 @@
|
|||
<relativePath>../</relativePath>
|
||||
</parent>
|
||||
|
||||
<!-- Added in order to produce ApplicationContextException error -->
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>spring-boot-exceptions</finalName>
|
||||
<resources>
|
||||
|
|
|
@ -0,0 +1,14 @@
|
|||
package com.baeldung.applicationcontextexception;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
//Remove this annotation to produce ApplicationContextException error
|
||||
@SpringBootApplication
|
||||
public class MainEntryPoint {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(MainEntryPoint.class, args);
|
||||
}
|
||||
|
||||
}
|
|
@ -76,7 +76,7 @@
|
|||
</build>
|
||||
|
||||
<properties>
|
||||
<keycloak-adapter-bom.version>11.0.2</keycloak-adapter-bom.version>
|
||||
<keycloak-adapter-bom.version>13.0.1</keycloak-adapter-bom.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -147,6 +147,7 @@
|
|||
<spock.version>1.2-groovy-2.4</spock.version>
|
||||
<gmavenplus-plugin.version>1.6</gmavenplus-plugin.version>
|
||||
<redis.version>0.7.2</redis.version>
|
||||
<spring-boot.version>2.5.0</spring-boot.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,63 @@
|
|||
# Created by https://www.gitignore.io/api/eclipse
|
||||
|
||||
### Eclipse ###
|
||||
|
||||
.metadata
|
||||
target/
|
||||
bin/
|
||||
tmp/
|
||||
*.tmp
|
||||
*.bak
|
||||
*.swp
|
||||
*~.nib
|
||||
local.properties
|
||||
.settings/
|
||||
.loadpath
|
||||
.recommenders
|
||||
|
||||
# External tool builders
|
||||
.externalToolBuilders/
|
||||
|
||||
# Locally stored "Eclipse launch configurations"
|
||||
*.launch
|
||||
|
||||
# PyDev specific (Python IDE for Eclipse)
|
||||
*.pydevproject
|
||||
|
||||
# CDT-specific (C/C++ Development Tooling)
|
||||
.cproject
|
||||
|
||||
# Java annotation processor (APT)
|
||||
.factorypath
|
||||
|
||||
# PDT-specific (PHP Development Tools)
|
||||
.buildpath
|
||||
|
||||
# sbteclipse plugin
|
||||
.target
|
||||
|
||||
# Tern plugin
|
||||
.tern-project
|
||||
|
||||
# TeXlipse plugin
|
||||
.texlipse
|
||||
|
||||
# STS (Spring Tool Suite)
|
||||
.springBeans
|
||||
|
||||
# Code Recommenders
|
||||
.recommenders/
|
||||
|
||||
# Scala IDE specific (Scala & Java development for Eclipse)
|
||||
.cache-main
|
||||
.scala_dependencies
|
||||
.worksheet
|
||||
|
||||
### Eclipse Patch ###
|
||||
# Eclipse Core
|
||||
.project
|
||||
|
||||
# JDT-specific (Eclipse Java Development Tools)
|
||||
.classpath
|
||||
|
||||
# End of https://www.gitignore.io/api/eclipse
|
|
@ -0,0 +1,3 @@
|
|||
### Relevant Articles
|
||||
|
||||
- [Spring Validation in the Service Layer](https://www.baeldung.com/spring-service-layer-validation)
|
|
@ -0,0 +1,41 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
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">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>spring-boot-validation</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-boot-2</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../../parent-boot-2</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.hibernate.validator</groupId>
|
||||
<artifactId>hibernate-validator</artifactId>
|
||||
</dependency>
|
||||
|
||||
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
|
@ -0,0 +1,13 @@
|
|||
package com.baeldung.spring.servicevalidation;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class SpringServiceLayerValidationApp {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(SpringServiceLayerValidationApp.class, args);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,22 @@
|
|||
package com.baeldung.spring.servicevalidation.controller;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import com.baeldung.spring.servicevalidation.domain.UserAccount;
|
||||
import com.baeldung.spring.servicevalidation.service.UserAccountService;
|
||||
|
||||
@RestController
|
||||
public class UserAccountController {
|
||||
|
||||
@Autowired
|
||||
private UserAccountService service;
|
||||
|
||||
@PostMapping("/addUserAccount")
|
||||
public Object addUserAccount(@RequestBody UserAccount userAccount) {
|
||||
return service.addUserAccount(userAccount);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,31 @@
|
|||
package com.baeldung.spring.servicevalidation.dao;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import com.baeldung.spring.servicevalidation.domain.UserAccount;
|
||||
|
||||
@Service
|
||||
public class UserAccountDao {
|
||||
|
||||
private Map<String, UserAccount> DB = new HashMap<String, UserAccount>();
|
||||
|
||||
public String addUserAccount(UserAccount useraccount) {
|
||||
DB.put(useraccount.getName(), useraccount);
|
||||
return "success";
|
||||
}
|
||||
|
||||
public Collection<UserAccount> getAllUserAccounts() {
|
||||
|
||||
Collection<UserAccount> list = DB.values();
|
||||
if (list.isEmpty()) {
|
||||
list.addAll(DB.values());
|
||||
}
|
||||
return list;
|
||||
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,77 @@
|
|||
package com.baeldung.spring.servicevalidation.domain;
|
||||
|
||||
import javax.validation.Valid;
|
||||
import javax.validation.constraints.Min;
|
||||
import javax.validation.constraints.NotBlank;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import javax.validation.constraints.Size;
|
||||
|
||||
public class UserAccount {
|
||||
|
||||
@NotNull(message = "Password must be between 4 to 15 characters")
|
||||
@Size(min = 4, max = 15)
|
||||
private String password;
|
||||
|
||||
@NotBlank(message = "Name must not be blank")
|
||||
private String name;
|
||||
|
||||
@Min(value = 18, message = "Age should not be less than 18")
|
||||
private int age;
|
||||
|
||||
@NotBlank(message = "Phone must not be blank")
|
||||
private String phone;
|
||||
|
||||
@Valid
|
||||
@NotNull(message = "UserAddress must not be blank")
|
||||
private UserAddress useraddress;
|
||||
|
||||
public UserAddress getUseraddress() {
|
||||
return useraddress;
|
||||
}
|
||||
|
||||
public void setUseraddress(UserAddress useraddress) {
|
||||
this.useraddress = useraddress;
|
||||
}
|
||||
|
||||
public UserAccount() {
|
||||
|
||||
}
|
||||
|
||||
public UserAccount(String email, String password, String name, int age) {
|
||||
this.password = password;
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
public int getAge() {
|
||||
return age;
|
||||
}
|
||||
|
||||
public void setAge(int age) {
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public String getPhone() {
|
||||
return phone;
|
||||
}
|
||||
|
||||
public void setPhone(String phone) {
|
||||
this.phone = phone;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,18 @@
|
|||
package com.baeldung.spring.servicevalidation.domain;
|
||||
|
||||
import javax.validation.constraints.NotBlank;
|
||||
|
||||
public class UserAddress {
|
||||
|
||||
@NotBlank
|
||||
private String countryCode;
|
||||
|
||||
public String getCountryCode() {
|
||||
return countryCode;
|
||||
}
|
||||
|
||||
public void setCountryCode(String countryCode) {
|
||||
this.countryCode = countryCode;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,42 @@
|
|||
package com.baeldung.spring.servicevalidation.service;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
import javax.validation.ConstraintViolation;
|
||||
import javax.validation.ConstraintViolationException;
|
||||
import javax.validation.Validator;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import com.baeldung.spring.servicevalidation.dao.UserAccountDao;
|
||||
import com.baeldung.spring.servicevalidation.domain.UserAccount;
|
||||
|
||||
@Service
|
||||
public class UserAccountService {
|
||||
|
||||
@Autowired
|
||||
private Validator validator;
|
||||
|
||||
@Autowired
|
||||
private UserAccountDao dao;
|
||||
|
||||
public String addUserAccount(UserAccount useraccount) {
|
||||
|
||||
Set<ConstraintViolation<UserAccount>> violations = validator.validate(useraccount);
|
||||
|
||||
if (!violations.isEmpty()) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (ConstraintViolation<UserAccount> constraintViolation : violations) {
|
||||
sb.append(constraintViolation.getMessage());
|
||||
}
|
||||
|
||||
dao.addUserAccount(useraccount);
|
||||
|
||||
throw new ConstraintViolationException("Error occurred: " + sb.toString(), violations);
|
||||
}
|
||||
|
||||
return "Account for " + useraccount.getName() + " Added!";
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,14 @@
|
|||
package com.baeldung;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
|
||||
import com.baeldung.spring.servicevalidation.SpringServiceLayerValidationApp;
|
||||
|
||||
@SpringBootTest(classes = SpringServiceLayerValidationApp.class)
|
||||
public class SpringContextTest {
|
||||
|
||||
@Test
|
||||
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
|
||||
}
|
||||
}
|
|
@ -3,3 +3,4 @@
|
|||
- [Introduction to Spring Cloud OpenFeign](https://www.baeldung.com/spring-cloud-openfeign)
|
||||
- [Differences Between Netflix Feign and OpenFeign](https://www.baeldung.com/netflix-feign-vs-openfeign)
|
||||
- [File Upload With Open Feign](https://www.baeldung.com/java-feign-file-upload)
|
||||
- [Feign Logging Configuration](https://www.baeldung.com/java-feign-logging)
|
||||
|
|
|
@ -3,3 +3,4 @@
|
|||
- [Guide to the System Rules Library](https://www.baeldung.com/java-system-rules-junit)
|
||||
- [Guide to the System Stubs Library](https://www.baeldung.com/java-system-stubs)
|
||||
- [Code Coverage with SonarQube and JaCoCo](https://www.baeldung.com/sonarqube-jacoco-code-coverage)
|
||||
- [Exclusions from Jacoco Report](https://www.baeldung.com/jacoco-report-exclude)
|
||||
|
|
|
@ -0,0 +1 @@
|
|||
lombok.addLombokGeneratedAnnotation = true
|
|
@ -13,6 +13,12 @@
|
|||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<version>${lombok.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
|
@ -85,6 +91,13 @@
|
|||
<groupId>org.jacoco</groupId>
|
||||
<artifactId>jacoco-maven-plugin</artifactId>
|
||||
<version>${jacoco.version}</version>
|
||||
<configuration>
|
||||
<excludes>
|
||||
<exclude>com/baeldung/**/ExcludedPOJO.class</exclude>
|
||||
<exclude>com/baeldung/**/*DTO.*</exclude>
|
||||
<exclude>**/config/*</exclude>
|
||||
</excludes>
|
||||
</configuration>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>jacoco-initialize</id>
|
||||
|
|
|
@ -0,0 +1,11 @@
|
|||
package com.baeldung.jacocoexclusions.config;
|
||||
|
||||
import com.baeldung.jacocoexclusions.service.ProductService;
|
||||
|
||||
public class AppConfig {
|
||||
|
||||
public ProductService productService() {
|
||||
return new ProductService();
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,12 @@
|
|||
package com.baeldung.jacocoexclusions.domain;
|
||||
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
|
||||
@Builder
|
||||
@Data
|
||||
public class Product {
|
||||
private int id;
|
||||
private String name;
|
||||
|
||||
}
|
|
@ -0,0 +1,4 @@
|
|||
package com.baeldung.jacocoexclusions.dto;
|
||||
|
||||
public class ExcludedPOJO {
|
||||
}
|
|
@ -0,0 +1,4 @@
|
|||
package com.baeldung.jacocoexclusions.dto;
|
||||
|
||||
public class ProductDTO {
|
||||
}
|
|
@ -0,0 +1,11 @@
|
|||
package com.baeldung.jacocoexclusions.generated;
|
||||
|
||||
@Generated
|
||||
public class Customer {
|
||||
// everything in this class will be excluded from jacoco report because of @Generated
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Customer{}";
|
||||
}
|
||||
}
|
|
@ -0,0 +1,15 @@
|
|||
package com.baeldung.jacocoexclusions.generated;
|
||||
|
||||
import java.lang.annotation.Documented;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
import static java.lang.annotation.ElementType.METHOD;
|
||||
import static java.lang.annotation.ElementType.TYPE;
|
||||
import static java.lang.annotation.RetentionPolicy.RUNTIME;
|
||||
|
||||
@Documented
|
||||
@Retention(RUNTIME)
|
||||
@Target({TYPE, METHOD})
|
||||
public @interface Generated {
|
||||
}
|
|
@ -0,0 +1,16 @@
|
|||
package com.baeldung.jacocoexclusions.service;
|
||||
|
||||
import com.baeldung.jacocoexclusions.generated.Generated;
|
||||
|
||||
public class CustomerService {
|
||||
|
||||
//this method will be excluded from coverage due to @Generated.
|
||||
@Generated
|
||||
public String getProductId() {
|
||||
return "An ID";
|
||||
}
|
||||
|
||||
public String getCustomerName() {
|
||||
return "some name";
|
||||
}
|
||||
}
|
|
@ -0,0 +1,9 @@
|
|||
package com.baeldung.jacocoexclusions.service;
|
||||
|
||||
public class ProductService {
|
||||
private static final double DISCOUNT = 0.25;
|
||||
|
||||
public double getSalePrice(double originalPrice) {
|
||||
return originalPrice - originalPrice * DISCOUNT;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,14 @@
|
|||
package com.baeldung.jacocoexclusions.service;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
|
||||
class CustomerServiceUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenCustomer_whenGetCustomer_thenReturnNewCustomer() {
|
||||
CustomerService customerService = new CustomerService();
|
||||
assertNotNull(customerService.getCustomerName());
|
||||
}
|
||||
}
|
|
@ -0,0 +1,15 @@
|
|||
package com.baeldung.jacocoexclusions.service;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
class ProductServiceUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenOriginalPrice_whenGetSalePrice_thenReturnsDiscountedPrice() {
|
||||
ProductService productService = new ProductService();
|
||||
double salePrice = productService.getSalePrice(100);
|
||||
assertEquals(salePrice, 75);
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue