diff --git a/core-java-modules/core-java-9-jigsaw/README.md b/core-java-modules/core-java-9-jigsaw/README.md index b1a401d48c..cfffb86588 100644 --- a/core-java-modules/core-java-9-jigsaw/README.md +++ b/core-java-modules/core-java-9-jigsaw/README.md @@ -7,5 +7,6 @@ This module contains articles about Project Jigsaw and the Java Platform Module - [Introduction to Project Jigsaw](http://www.baeldung.com/project-jigsaw-java-modularity) - [A Guide to Java 9 Modularity](https://www.baeldung.com/java-9-modularity) - [Java 9 java.lang.Module API](https://www.baeldung.com/java-9-module-api) +- [Java 9 Illegal Reflective Access Warning](https://www.baeldung.com/java-illegal-reflective-access) diff --git a/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/A01-compile-and-package-baeldung-agent.sh b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/A01-compile-and-package-baeldung-agent.sh new file mode 100644 index 0000000000..959fa66ec4 --- /dev/null +++ b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/A01-compile-and-package-baeldung-agent.sh @@ -0,0 +1,11 @@ +#!/bin/bash + +DIR=baeldung-agent + +# compile +mkdir -p out/${DIR} +javac -d out/${DIR} $(find ${DIR} -type f -name "*.java") + +# package +mkdir -p mods +jar --create --file=mods/${DIR}.jar --manifest=${DIR}/manifest.txt -C out/${DIR} . diff --git a/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/A02-compile-and-package-baeldung-reflected.sh b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/A02-compile-and-package-baeldung-reflected.sh new file mode 100644 index 0000000000..fa922c54df --- /dev/null +++ b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/A02-compile-and-package-baeldung-reflected.sh @@ -0,0 +1,11 @@ +#!/bin/bash + +DIR=baeldung-reflected + +# compile +mkdir -p out/${DIR} +javac -d out/${DIR} $(find ${DIR} -type f -name "*.java") + +# package +mkdir -p mods +jar --create --file=mods/${DIR}.jar -C out/${DIR} . diff --git a/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/A03-compile-and-package-baeldung-intermedium.sh b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/A03-compile-and-package-baeldung-intermedium.sh new file mode 100644 index 0000000000..af76ff5a2e --- /dev/null +++ b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/A03-compile-and-package-baeldung-intermedium.sh @@ -0,0 +1,11 @@ +#!/bin/bash + +DIR=baeldung-intermedium + +# compile +mkdir -p out/${DIR} +javac -d out/${DIR} $(find ${DIR} -type f -name "*.java") + +# package +mkdir -p mods +jar --create --file=mods/${DIR}.jar -C out/${DIR} . diff --git a/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/A04-compile-and-package-baeldung-reflecting-named.sh b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/A04-compile-and-package-baeldung-reflecting-named.sh new file mode 100644 index 0000000000..f3f91c9f04 --- /dev/null +++ b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/A04-compile-and-package-baeldung-reflecting-named.sh @@ -0,0 +1,11 @@ +#!/bin/bash + +DIR=baeldung-reflecting-named + +# compile +mkdir -p out/${DIR} +javac -d out/${DIR} --module-path mods $(find ${DIR} -type f -name "*.java") + +# package +mkdir -p mods +jar --create --file=mods/${DIR}.jar -C out/${DIR} . diff --git a/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/A05-compile-and-package-baeldung-reflecting-unnamed.sh b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/A05-compile-and-package-baeldung-reflecting-unnamed.sh new file mode 100644 index 0000000000..deb0a8aaea --- /dev/null +++ b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/A05-compile-and-package-baeldung-reflecting-unnamed.sh @@ -0,0 +1,11 @@ +#!/bin/bash + +DIR=baeldung-reflecting-unnamed + +# compile +mkdir -p out/${DIR} +javac -d out/${DIR} $(find ${DIR} -type f -name "*.java") + +# package +mkdir -p mods +jar --create --file=mods/${DIR}.jar -C out/${DIR} . diff --git a/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/B01-runtime-baeldung-reflecting-named-using-add-opens.sh b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/B01-runtime-baeldung-reflecting-named-using-add-opens.sh new file mode 100644 index 0000000000..720ad69003 --- /dev/null +++ b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/B01-runtime-baeldung-reflecting-named-using-add-opens.sh @@ -0,0 +1,4 @@ +#!/bin/bash +java --module-path mods \ + --add-opens baeldung.reflected/com.baeldung.reflected.internal=baeldung.reflecting.named \ + --module baeldung.reflecting.named/com.baeldung.reflecting.named.Main diff --git a/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/B02-runtime-baeldung-reflecting-named-using-forward-opens.sh b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/B02-runtime-baeldung-reflecting-named-using-forward-opens.sh new file mode 100644 index 0000000000..9b5f9cb094 --- /dev/null +++ b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/B02-runtime-baeldung-reflecting-named-using-forward-opens.sh @@ -0,0 +1,4 @@ +#!/bin/bash +java --module-path mods \ + --add-opens baeldung.reflected/com.baeldung.reflected.internal=baeldung.intermedium \ + --module baeldung.reflecting.named/com.baeldung.reflecting.named.MainWithForwardOpen diff --git a/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/B03-runtime-baeldung-reflecting-named-using-java-agent.sh b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/B03-runtime-baeldung-reflecting-named-using-java-agent.sh new file mode 100644 index 0000000000..cf66dd778f --- /dev/null +++ b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/B03-runtime-baeldung-reflecting-named-using-java-agent.sh @@ -0,0 +1,4 @@ +#!/bin/bash +java --module-path mods \ + -javaagent:mods/baeldung-agent.jar=com.baeldung.reflected.internal.InternalNonPublicClass,com.baeldung.reflecting.named.Main \ + --module baeldung.reflecting.named/com.baeldung.reflecting.named.Main diff --git a/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/B04-runtime-baeldung-reflecting-unnamed-with-warning.sh b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/B04-runtime-baeldung-reflecting-unnamed-with-warning.sh new file mode 100644 index 0000000000..525b8dc58c --- /dev/null +++ b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/B04-runtime-baeldung-reflecting-unnamed-with-warning.sh @@ -0,0 +1,2 @@ +#!/bin/bash +java -cp "mods/*" com.baeldung.reflecting.unnamed.Main diff --git a/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/B05-runtime-baeldung-reflecting-unnamed-using-add-opens.sh b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/B05-runtime-baeldung-reflecting-unnamed-using-add-opens.sh new file mode 100644 index 0000000000..f7f5f16237 --- /dev/null +++ b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/B05-runtime-baeldung-reflecting-unnamed-using-add-opens.sh @@ -0,0 +1,2 @@ +#!/bin/bash +java -cp "mods/*" --add-opens java.base/java.lang=ALL-UNNAMED com.baeldung.reflecting.unnamed.Main \ No newline at end of file diff --git a/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/B06-runtime-baeldung-reflecting-unnamed-using-java-agent.sh b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/B06-runtime-baeldung-reflecting-unnamed-using-java-agent.sh new file mode 100644 index 0000000000..4b30ae1a5c --- /dev/null +++ b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/B06-runtime-baeldung-reflecting-unnamed-using-java-agent.sh @@ -0,0 +1,2 @@ +#!/bin/bash +java -cp "mods/*" -javaagent:mods/baeldung-agent.jar com.baeldung.reflecting.unnamed.Main diff --git a/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/C01-clean.sh b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/C01-clean.sh new file mode 100644 index 0000000000..98707f810f --- /dev/null +++ b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/C01-clean.sh @@ -0,0 +1,4 @@ +#!/bin/bash + +rm -rf out +rm -rf mods diff --git a/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-agent/com/baeldung/agent/LoadTimeAgent.java b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-agent/com/baeldung/agent/LoadTimeAgent.java new file mode 100644 index 0000000000..33d9a231ea --- /dev/null +++ b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-agent/com/baeldung/agent/LoadTimeAgent.java @@ -0,0 +1,69 @@ +package com.baeldung.agent; + +import java.lang.instrument.Instrumentation; +import java.util.*; + +public class LoadTimeAgent { + public static void premain(String agentArgs, Instrumentation inst) { + System.out.println("agentArgs: " + agentArgs); + + if (agentArgs != null) { + addExportsAndOpensByClassName(inst, agentArgs); + } + else { + addExportsAndOpensToUnnamedModule(inst); + } + } + + private static void addExportsAndOpensByClassName(Instrumentation inst, String agentArgs) { + String[] array = agentArgs.split(","); + try { + String className1 = array[0]; + String className2 = array[1]; + Class clazz1 = Class.forName(className1); + Class clazz2 = Class.forName(className2); + + Module srcModule = clazz1.getModule(); + Module targetModule = clazz2.getModule(); + redefineModule(inst, srcModule, targetModule); + } catch (ClassNotFoundException e) { + e.printStackTrace(); + } + } + + private static void addExportsAndOpensToUnnamedModule(Instrumentation inst) { + Module unnamedModule = ClassLoader.getSystemClassLoader().getUnnamedModule(); + Set modules = ModuleLayer.boot().modules(); + + for (Module m : modules) { + redefineModule(inst, m, unnamedModule); + } + } + + private static void redefineModule(Instrumentation inst, Module src, Module target) { + // prepare extra reads + Set extraReads = Collections.singleton(target); + + // prepare extra exports + Set packages = src.getPackages(); + Map> extraExports = new HashMap<>(); + for (String pkg : packages) { + extraExports.put(pkg, extraReads); + } + + // prepare extra opens + Map> extraOpens = new HashMap<>(); + for (String pkg : packages) { + extraOpens.put(pkg, extraReads); + } + + // prepare extra uses + Set> extraUses = Collections.emptySet(); + + // prepare extra provides + Map, List>> extraProvides = Collections.emptyMap(); + + // redefine module + inst.redefineModule(src, extraReads, extraExports, extraOpens, extraUses, extraProvides); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-agent/manifest.txt b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-agent/manifest.txt new file mode 100644 index 0000000000..3dc9de7ba5 --- /dev/null +++ b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-agent/manifest.txt @@ -0,0 +1,3 @@ +Premain-Class: com.baeldung.agent.LoadTimeAgent +Can-Redefine-Classes: true +Can-Retransform-Classes: true diff --git a/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-agent/module-info.java b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-agent/module-info.java new file mode 100644 index 0000000000..c976de2881 --- /dev/null +++ b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-agent/module-info.java @@ -0,0 +1,3 @@ +module baeldung.agent { + requires java.instrument; +} \ No newline at end of file diff --git a/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-intermedium/com/baeldung/intermedium/ForwardOpen.java b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-intermedium/com/baeldung/intermedium/ForwardOpen.java new file mode 100644 index 0000000000..db031e2cfc --- /dev/null +++ b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-intermedium/com/baeldung/intermedium/ForwardOpen.java @@ -0,0 +1,15 @@ +package com.baeldung.intermedium; + +public class ForwardOpen { + public static void addOpens(Class clazz1, Class clazz2) { + Module currentModule = ForwardOpen.class.getModule(); + Module srcModule = clazz1.getModule(); + Module targetModule = clazz2.getModule(); + + System.out.println("current module: " + currentModule.getName()); + System.out.println("source module: " + srcModule.getName()); + System.out.println("target module: " + targetModule.getName()); + + srcModule.addOpens(clazz1.getPackageName(), targetModule); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-intermedium/module-info.java b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-intermedium/module-info.java new file mode 100644 index 0000000000..9ca6cbce43 --- /dev/null +++ b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-intermedium/module-info.java @@ -0,0 +1,3 @@ +module baeldung.intermedium { + exports com.baeldung.intermedium; +} \ No newline at end of file diff --git a/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-reflected/com/baeldung/reflected/exported/ExportedNonPublicClass.java b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-reflected/com/baeldung/reflected/exported/ExportedNonPublicClass.java new file mode 100644 index 0000000000..c95e17ec1f --- /dev/null +++ b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-reflected/com/baeldung/reflected/exported/ExportedNonPublicClass.java @@ -0,0 +1,11 @@ +package com.baeldung.reflected.exported; + +class ExportedNonPublicClass { + public static void testPublicStaticMethod() { + System.out.println("ExportedNonPublicClass.testPublicStaticMethod()"); + } + + private static void testPrivateStaticMethod() { + System.out.println("ExportedNonPublicClass.testPrivateStaticMethod()"); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-reflected/com/baeldung/reflected/exported/ExportedPublicClass.java b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-reflected/com/baeldung/reflected/exported/ExportedPublicClass.java new file mode 100644 index 0000000000..3bbfca209c --- /dev/null +++ b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-reflected/com/baeldung/reflected/exported/ExportedPublicClass.java @@ -0,0 +1,11 @@ +package com.baeldung.reflected.exported; + +public class ExportedPublicClass { + public static void testPublicStaticMethod() { + System.out.println("ExportedPublicClass.testPublicStaticMethod()"); + } + + private static void testPrivateStaticMethod() { + System.out.println("ExportedPublicClass.testPrivateStaticMethod()"); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-reflected/com/baeldung/reflected/internal/InternalNonPublicClass.java b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-reflected/com/baeldung/reflected/internal/InternalNonPublicClass.java new file mode 100644 index 0000000000..052ecbea9e --- /dev/null +++ b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-reflected/com/baeldung/reflected/internal/InternalNonPublicClass.java @@ -0,0 +1,11 @@ +package com.baeldung.reflected.internal; + +class InternalNonPublicClass { + public static void testPublicStaticMethod() { + System.out.println("InternalNonPublicClass.testPublicStaticMethod()"); + } + + private static void testPrivateStaticMethod() { + System.out.println("InternalNonPublicClass.testPrivateStaticMethod()"); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-reflected/com/baeldung/reflected/internal/InternalPublicClass.java b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-reflected/com/baeldung/reflected/internal/InternalPublicClass.java new file mode 100644 index 0000000000..8f7a20698f --- /dev/null +++ b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-reflected/com/baeldung/reflected/internal/InternalPublicClass.java @@ -0,0 +1,11 @@ +package com.baeldung.reflected.internal; + +public class InternalPublicClass { + public static void testPublicStaticMethod() { + System.out.println("InternalPublicClass.testPublicStaticMethod()"); + } + + private static void testPrivateStaticMethod() { + System.out.println("InternalPublicClass.testPrivateStaticMethod()"); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-reflected/com/baeldung/reflected/opened/OpenedNonPublicClass.java b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-reflected/com/baeldung/reflected/opened/OpenedNonPublicClass.java new file mode 100644 index 0000000000..99f9850cc1 --- /dev/null +++ b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-reflected/com/baeldung/reflected/opened/OpenedNonPublicClass.java @@ -0,0 +1,11 @@ +package com.baeldung.reflected.opened; + +class OpenedNonPublicClass { + public static void testPublicStaticMethod() { + System.out.println("OpenedNonPublicClass.testPublicStaticMethod()"); + } + + private static void testPrivateStaticMethod() { + System.out.println("OpenedNonPublicClass.testPrivateStaticMethod()"); + } +} diff --git a/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-reflected/com/baeldung/reflected/opened/OpenedPublicClass.java b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-reflected/com/baeldung/reflected/opened/OpenedPublicClass.java new file mode 100644 index 0000000000..f9a56ca26b --- /dev/null +++ b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-reflected/com/baeldung/reflected/opened/OpenedPublicClass.java @@ -0,0 +1,11 @@ +package com.baeldung.reflected.opened; + +public class OpenedPublicClass { + public static void testPublicStaticMethod() { + System.out.println("OpenedPublicClass.testPublicStaticMethod()"); + } + + private static void testPrivateStaticMethod() { + System.out.println("OpenedPublicClass.testPrivateStaticMethod()"); + } +} diff --git a/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-reflected/module-info.java b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-reflected/module-info.java new file mode 100644 index 0000000000..e2164415cf --- /dev/null +++ b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-reflected/module-info.java @@ -0,0 +1,4 @@ +module baeldung.reflected { + exports com.baeldung.reflected.exported; + opens com.baeldung.reflected.opened; +} \ No newline at end of file diff --git a/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-reflecting-named/com/baeldung/reflecting/named/Main.java b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-reflecting-named/com/baeldung/reflecting/named/Main.java new file mode 100644 index 0000000000..c0fa4010ab --- /dev/null +++ b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-reflecting-named/com/baeldung/reflecting/named/Main.java @@ -0,0 +1,12 @@ +package com.baeldung.reflecting.named; + +import java.lang.reflect.Method; + +public class Main { + public static void main(String[] args) throws Exception { + Class clazz = Class.forName("com.baeldung.reflected.internal.InternalNonPublicClass"); + Method method = clazz.getDeclaredMethod("testPrivateStaticMethod"); + method.setAccessible(true); + method.invoke(null); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-reflecting-named/com/baeldung/reflecting/named/MainWithForwardOpen.java b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-reflecting-named/com/baeldung/reflecting/named/MainWithForwardOpen.java new file mode 100644 index 0000000000..fad8a9ddce --- /dev/null +++ b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-reflecting-named/com/baeldung/reflecting/named/MainWithForwardOpen.java @@ -0,0 +1,18 @@ +package com.baeldung.reflecting.named; + +import com.baeldung.intermedium.ForwardOpen; + +import java.lang.reflect.Method; + +public class MainWithForwardOpen { + public static void main(String[] args) throws Exception { + Class currentClass = Main.class; + Class clazz = Class.forName("com.baeldung.reflected.internal.InternalNonPublicClass"); + + ForwardOpen.addOpens(clazz, currentClass); + + Method method = clazz.getDeclaredMethod("testPrivateStaticMethod"); + method.setAccessible(true); + method.invoke(null); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-reflecting-named/module-info.java b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-reflecting-named/module-info.java new file mode 100644 index 0000000000..936f53cd6e --- /dev/null +++ b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-reflecting-named/module-info.java @@ -0,0 +1,4 @@ +module baeldung.reflecting.named { + requires baeldung.intermedium; + requires baeldung.reflected; +} \ No newline at end of file diff --git a/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-reflecting-unnamed/com/baeldung/reflecting/unnamed/Main.java b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-reflecting-unnamed/com/baeldung/reflecting/unnamed/Main.java new file mode 100644 index 0000000000..37bdc57eaf --- /dev/null +++ b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-reflecting-unnamed/com/baeldung/reflecting/unnamed/Main.java @@ -0,0 +1,13 @@ +package com.baeldung.reflecting.unnamed; + +import java.lang.reflect.Field; + +public class Main { + public static void main(String[] args) throws Exception { + Class clazz = StringBuilder.class; + Field f = clazz.getDeclaredField("serialVersionUID"); + f.setAccessible(true); + Object value = f.get(null); + System.out.println(value); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-collections-list-3/src/main/java/com/baeldung/list/listvsarraylist/ArrayListDemo.java b/core-java-modules/core-java-collections-list-3/src/main/java/com/baeldung/list/listvsarraylist/ArrayListDemo.java new file mode 100644 index 0000000000..f425f19189 --- /dev/null +++ b/core-java-modules/core-java-collections-list-3/src/main/java/com/baeldung/list/listvsarraylist/ArrayListDemo.java @@ -0,0 +1,51 @@ +package com.baeldung.list.listvsarraylist; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Locale; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +public class ArrayListDemo { + + private ArrayList passengers = new ArrayList<>(20); +// private LinkedList passengers = new LinkedList<>(); // compile time error + + public ArrayList addPassenger(Passenger passenger) { + passengers.add(passenger); + return passengers; + } + + public ArrayList removePassenger(Passenger passenger) { + passengers.remove(passenger); + return passengers; + } + + public ArrayList getPassengersBySource(String source) { + return new ArrayList(passengers.stream() + .filter(it -> it.getSource().equals(source)) + .collect(Collectors.toList())); + } + + public ArrayList getPassengersByDestination(String destination) { + return new ArrayList (passengers.stream() + .filter(it -> it.getDestination().equals(destination)) + .collect(Collectors.toList())); + } + + public long getKidsCount(ArrayList passengerList) { + return passengerList.stream() + .filter(it -> (it.getAge() <= 10)) + .count(); + } + + public ArrayList getFinalPassengersList() { + return new ArrayList (Collections.unmodifiableList(passengers)); + } + + public ArrayList getServicedCountries() { + return new ArrayList (Stream.of(Locale.getISOCountries()) + .collect(Collectors.toList())); + } + +} diff --git a/core-java-modules/core-java-collections-list-3/src/main/java/com/baeldung/list/listvsarraylist/ListDemo.java b/core-java-modules/core-java-collections-list-3/src/main/java/com/baeldung/list/listvsarraylist/ListDemo.java new file mode 100644 index 0000000000..a9a182d21e --- /dev/null +++ b/core-java-modules/core-java-collections-list-3/src/main/java/com/baeldung/list/listvsarraylist/ListDemo.java @@ -0,0 +1,53 @@ +package com.baeldung.list.listvsarraylist; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedList; +import java.util.List; +import java.util.Locale; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +public class ListDemo { + + private List passengers = new ArrayList<>(20); +// private List passengers = new LinkedList<>(); // No compile time error + + public List addPassenger(Passenger passenger) { + passengers.add(passenger); + return passengers; + } + + public List removePassenger(Passenger passenger) { + passengers.remove(passenger); + return passengers; + } + + public List getPassengersBySource(String source) { + return passengers.stream() + .filter(it -> it.getSource().equals(source)) + .collect(Collectors.toList()); + } + + public List getPassengersByDestination(String destination) { + return passengers.stream() + .filter(it -> it.getDestination().equals(destination)) + .collect(Collectors.toList()); + } + + public long getKidsCount(List passengerList) { + return passengerList.stream() + .filter(it -> (it.getAge() <= 10)) + .count(); + } + + public List getFinalPassengersList() { + return Collections.unmodifiableList(passengers); + } + + public List getServicedCountries() { + return Stream.of(Locale.getISOCountries()) + .collect(Collectors.toList()); + } + +} diff --git a/core-java-modules/core-java-collections-list-3/src/main/java/com/baeldung/list/listvsarraylist/Passenger.java b/core-java-modules/core-java-collections-list-3/src/main/java/com/baeldung/list/listvsarraylist/Passenger.java new file mode 100644 index 0000000000..9c61b70aa6 --- /dev/null +++ b/core-java-modules/core-java-collections-list-3/src/main/java/com/baeldung/list/listvsarraylist/Passenger.java @@ -0,0 +1,49 @@ +package com.baeldung.list.listvsarraylist; + +public class Passenger { + + private String name; + private int age; + private String source; + private String destination; + + public Passenger(String name, int age, String source, String destination) { + this.name = name; + this.age = age; + this.source = source; + this.destination = destination; + } + + 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; + } + + public String getSource() { + return source; + } + + public void setSource(String source) { + this.source = source; + } + + public String getDestination() { + return destination; + } + + public void setDestination(String destination) { + this.destination = destination; + } + +} diff --git a/core-java-modules/core-java-collections-list-3/src/test/java/com/baeldung/list/listvsarraylist/ArrayListDemoUnitTest.java b/core-java-modules/core-java-collections-list-3/src/test/java/com/baeldung/list/listvsarraylist/ArrayListDemoUnitTest.java new file mode 100644 index 0000000000..59094ab562 --- /dev/null +++ b/core-java-modules/core-java-collections-list-3/src/test/java/com/baeldung/list/listvsarraylist/ArrayListDemoUnitTest.java @@ -0,0 +1,91 @@ +package com.baeldung.list.listvsarraylist; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertNotNull; + +import java.util.ArrayList; +import java.util.Locale; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class ArrayListDemoUnitTest { + + ArrayListDemo application = new ArrayListDemo(); + + Passenger passenger1; + Passenger passenger2; + Passenger passenger3; + + @BeforeEach + protected void setUp() { + passenger1 = new Passenger("Anna", 25, "London", "New York"); + passenger2 = new Passenger("Binny", 35, "New York", "London"); + passenger3 = new Passenger("Chandra", 8, "Paris", "New Delhi"); + application.addPassenger(passenger1); + application.addPassenger(passenger2); + application.addPassenger(passenger3); + } + + @Test + public void givenEmptyList_whenAddedPassenger_thenReturnCurrentPassengerList() { + ArrayList list = application.addPassenger(new Passenger("David", 54, "Milan", "Paris")); + + assertNotNull(list); + assertThat(list).hasSize(4); + } + + @Test + public void givenPassengerList_whenRemovedPassenger_thenReturnCurrentPassengerList() { + ArrayList list = application.removePassenger(passenger3); + + assertNotNull(list); + assertThat(list).hasSize(2); + } + + @Test + public void givenPassengerList_whenPassedWithSourceCity_thenReturnMatchingPassengerList() { + ArrayList list = application.getPassengersBySource("Singapore"); + ArrayList list2 = application.getPassengersBySource("London"); + + assertThat(list).isEmpty(); + assertThat(list2.get(0)).isEqualTo(passenger1); + } + + @Test + public void givenPassengerList_whenPassedWithDestinationCity_thenReturnMatchingPassengerList() { + ArrayList list = application.getPassengersByDestination("Singapore"); + ArrayList list2 = application.getPassengersByDestination("London"); + + assertThat(list).isEmpty(); + assertThat(list2.get(0)).isEqualTo(passenger2); + } + + @Test + public void givenPassengerList_whenFindKidsByAge_thenReturnKidsList() { + ArrayList list = new ArrayList<>(); + list.add(passenger1); + list.add(passenger2); + list.add(passenger3); + long count = application.getKidsCount(list); + + assertThat(count).isEqualTo(1); + } + + @Test + public void givenPassengerList_whenCalledWithCollectionsFunction_thenReturnsListType() { + ArrayList list = application.getFinalPassengersList(); + + assertNotNull(list); + assertThat(list).hasSize(3); + } + + @Test + public void givenCurrentLocale_whenUsingStreams_thenReturnsListType() { + ArrayList servicedCountries = application.getServicedCountries(); + + assertNotNull(servicedCountries); + assertThat(servicedCountries).hasSize(Locale.getISOCountries().length); + } + +} diff --git a/core-java-modules/core-java-collections-list-3/src/test/java/com/baeldung/list/listvsarraylist/ListDemoUnitTest.java b/core-java-modules/core-java-collections-list-3/src/test/java/com/baeldung/list/listvsarraylist/ListDemoUnitTest.java new file mode 100644 index 0000000000..cf239a79ce --- /dev/null +++ b/core-java-modules/core-java-collections-list-3/src/test/java/com/baeldung/list/listvsarraylist/ListDemoUnitTest.java @@ -0,0 +1,92 @@ +package com.baeldung.list.listvsarraylist; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertNotNull; + +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class ListDemoUnitTest { + + ListDemo application = new ListDemo(); + + Passenger passenger1; + Passenger passenger2; + Passenger passenger3; + + @BeforeEach + protected void setUp() { + passenger1 = new Passenger("Anna", 25, "London", "New York"); + passenger2 = new Passenger("Binny", 35, "New York", "London"); + passenger3 = new Passenger("Chandra", 8, "Paris", "New Delhi"); + application.addPassenger(passenger1); + application.addPassenger(passenger2); + application.addPassenger(passenger3); + } + + @Test + public void givenEmptyList_whenAddedPassenger_thenReturnCurrentPassengerList() { + List list = application.addPassenger(new Passenger("David", 54, "Milan", "Paris")); + + assertNotNull(list); + assertThat(list).hasSize(4); + } + + @Test + public void givenPresentList_whenRemovedPassenger_thenReturnCurrentPassengerList() { + List list = application.removePassenger(passenger3); + + assertNotNull(list); + assertThat(list).hasSize(2); + } + + @Test + public void givenPresentList_whenPassedWithSourceCity_thenReturnMatchingPassengerList() { + List list = application.getPassengersBySource("Singapore"); + List list2 = application.getPassengersBySource("London"); + + assertThat(list).isEmpty(); + assertThat(list2.get(0)).isEqualTo(passenger1); + } + + @Test + public void givenPresentList_whenPassedWithDestinationCity_thenReturnMatchingPassengerList() { + List list = application.getPassengersByDestination("Singapore"); + List list2 = application.getPassengersByDestination("London"); + + assertThat(list).isEmpty(); + assertThat(list2.get(0)).isEqualTo(passenger2); + } + + @Test + public void givenPassengerList_whenFindKidsByAge_thenReturnKidsList() { + List list = new ArrayList<>(); + list.add(passenger1); + list.add(passenger2); + list.add(passenger3); + long count = application.getKidsCount(list); + + assertThat(count).isEqualTo(1); + } + + @Test + public void givenPresentList_whenCalledWithCollectionsFunction_thenReturnsListType() { + List list = application.getFinalPassengersList(); + + assertNotNull(list); + assertThat(list).hasSize(3); + } + + @Test + public void givenCurrentLocale_whenUsingStreams_thenReturnsListType() { + List servicedCountries = application.getServicedCountries(); + + assertNotNull(servicedCountries); + assertThat(servicedCountries).hasSize(Locale.getISOCountries().length); + } + +} diff --git a/core-java-modules/core-java-collections-list/src/test/java/com/baeldung/list/listOfHashMaps/ListOfHashMapsUnitTest.java b/core-java-modules/core-java-collections-list/src/test/java/com/baeldung/list/listOfHashMaps/ListOfHashMapsUnitTest.java new file mode 100644 index 0000000000..39110aedd3 --- /dev/null +++ b/core-java-modules/core-java-collections-list/src/test/java/com/baeldung/list/listOfHashMaps/ListOfHashMapsUnitTest.java @@ -0,0 +1,36 @@ +package test.java.com.baeldung.list.listOfHashMaps; + +import org.junit.Test; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.stream.Collectors; + +import static org.junit.Assert.assertTrue; + +public class ListOfHashMapsUnitTest { + List>> booksAuthorsMapsList = new ArrayList<>(); + + @Test + public void givenMaps_whenAddToList_thenListContainsMaps() { + HashMap> javaBooksAuthorsMap = new HashMap<>(); + HashMap> phpBooksAuthorsMap = new HashMap<>(); + javaBooksAuthorsMap.put("Head First Java", Arrays.asList("Kathy Sierra", "Bert Bates")); + javaBooksAuthorsMap.put("Effective Java", Arrays.asList("Joshua Bloch")); + javaBooksAuthorsMap.put("OCA Java SE 8", + Arrays.asList("Kathy Sierra", "Bert Bates", "Elisabeth Robson")); + phpBooksAuthorsMap.put("The Joy of PHP", Arrays.asList("Alan Forbes")); + phpBooksAuthorsMap.put("Head First PHP & MySQL", + Arrays.asList("Lynn Beighley", "Michael Morrison")); + + booksAuthorsMapsList.add(javaBooksAuthorsMap); + booksAuthorsMapsList.add(phpBooksAuthorsMap); + + assertTrue(booksAuthorsMapsList.get(0).keySet().containsAll + (javaBooksAuthorsMap.keySet().stream().collect(Collectors.toList()))); + assertTrue(booksAuthorsMapsList.get(1).keySet().containsAll + (phpBooksAuthorsMap.keySet().stream().collect(Collectors.toList()))); + } +} diff --git a/core-java-modules/core-java-regex-2/regexMatchToArray/src/regex/array/RegexMatches.java b/core-java-modules/core-java-regex-2/regexMatchToArray/src/regex/array/RegexMatches.java new file mode 100644 index 0000000000..d7b50d95ca --- /dev/null +++ b/core-java-modules/core-java-regex-2/regexMatchToArray/src/regex/array/RegexMatches.java @@ -0,0 +1,24 @@ +package regex.array; + +import java.util.ArrayList; +import java.util.List; +import java.util.regex.*; + +class RegexMatches { + + String[] regexMatch(String strSearch) + { + List matchesList = new ArrayList(); + String stringToSearch = strSearch; + Pattern p1 = Pattern.compile("780{1}\\d{7}"); + Matcher m1 = p1.matcher(stringToSearch); + while (m1.find()) + { + matchesList.add(m1.group()); + } + int sizeOfNewArray = matchesList.size(); + String newArrayOfMatches[] = new String[sizeOfNewArray]; + matchesList.toArray(newArrayOfMatches); + return newArrayOfMatches; + } +} diff --git a/core-java-modules/core-java-regex-2/regexMatchToArray/test/regex/array/RegexMatchesUnitTest.java b/core-java-modules/core-java-regex-2/regexMatchToArray/test/regex/array/RegexMatchesUnitTest.java new file mode 100644 index 0000000000..3e8f23c4bb --- /dev/null +++ b/core-java-modules/core-java-regex-2/regexMatchToArray/test/regex/array/RegexMatchesUnitTest.java @@ -0,0 +1,33 @@ +package regex.array; + +import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; + +import regex.array.RegexMatches; + +class RegexMatchesUnitTest { + + @Test + void whenFourNums_thenFourMatches() { + RegexMatches rm = new RegexMatches(); + String actual[] = rm.regexMatch("7801111211fsdafasdfa 7802222222 sadfsadfsda7803333333 sadfdasfasd 7804444444"); + + assertArrayEquals(new String[] {"7801111211", "7802222222", "7803333333", "7804444444"}, actual, "success"); + } + + @Test + void whenThreeNums_thenThreeMatches() { + RegexMatches rm = new RegexMatches(); + String actual[] = rm.regexMatch("7801111211fsdafasdfa 780222222 sadfsadfsda7803333333 sadfdasfasd 7804444444"); + + assertArrayEquals(new String[] {"7801111211", "7803333333", "7804444444"}, actual, "success"); + } + + @Test + void whenZeroNums_thenZeroMatches() { + RegexMatches rm = new RegexMatches(); + String actual[] = rm.regexMatch("78011111fsdafasdfa 780222222 sadfsadfsda78033333 sadfdasfasd 7804444"); + + assertArrayEquals(new String[] {}, actual, "success"); + } +} diff --git a/graphql/graphql-error-handling/pom.xml b/graphql/graphql-error-handling/pom.xml new file mode 100644 index 0000000000..0cd00df3b9 --- /dev/null +++ b/graphql/graphql-error-handling/pom.xml @@ -0,0 +1,97 @@ + + + 4.0.0 + com.baeldung.graphql + graphql-error-handling + 1.0 + jar + graphql-error-handling + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + + 1.8 + 1.18.18 + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + org.springframework.boot + spring-boot-starter-web + + + + com.graphql-java + graphql-spring-boot-starter + 5.0.2 + + + + com.graphql-java + graphql-java-tools + 5.2.4 + + + + org.projectlombok + lombok + ${lombok.version} + + + + com.h2database + h2 + ${h2.version} + + + + org.springframework.boot + spring-boot-test + test + 2.6.4 + + + + com.graphql-java + graphql-spring-boot-starter-test + test + 5.0.2 + + + + org.assertj + assertj-core + 3.22.0 + test + + + + org.skyscreamer + jsonassert + 1.5.0 + test + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + \ No newline at end of file diff --git a/graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/GraphQLErrorHandlerApplication.java b/graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/GraphQLErrorHandlerApplication.java new file mode 100644 index 0000000000..565c9e0a15 --- /dev/null +++ b/graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/GraphQLErrorHandlerApplication.java @@ -0,0 +1,46 @@ +package com.baeldung.graphql.error.handling; + +import com.baeldung.graphql.error.handling.exception.GraphQLErrorAdapter; +import graphql.ExceptionWhileDataFetching; +import graphql.GraphQLError; +import graphql.servlet.GraphQLErrorHandler; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +@SpringBootApplication +public class GraphQLErrorHandlerApplication { + public static void main(String[] args) { + SpringApplication.run(GraphQLErrorHandlerApplication.class, args); + } + + @Bean + public GraphQLErrorHandler errorHandler() { + return new GraphQLErrorHandler() { + @Override + public List processErrors(List errors) { + List clientErrors = errors.stream() + .filter(this::isClientError) + .collect(Collectors.toList()); + + List serverErrors = errors.stream() + .filter(e -> !isClientError(e)) + .map(GraphQLErrorAdapter::new) + .collect(Collectors.toList()); + + List e = new ArrayList<>(); + e.addAll(clientErrors); + e.addAll(serverErrors); + return e; + } + + private boolean isClientError(GraphQLError error) { + return !(error instanceof ExceptionWhileDataFetching || error instanceof Throwable); + } + }; + } +} diff --git a/graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/domain/Location.java b/graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/domain/Location.java new file mode 100644 index 0000000000..815bf3a26a --- /dev/null +++ b/graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/domain/Location.java @@ -0,0 +1,29 @@ +package com.baeldung.graphql.error.handling.domain; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.persistence.Entity; +import javax.persistence.FetchType; +import javax.persistence.Id; +import javax.persistence.OneToMany; +import java.util.ArrayList; +import java.util.List; + +@Data +@Entity +@Builder +@AllArgsConstructor +@NoArgsConstructor +public class Location { + @Id + private String zipcode; + + private String city; + private String state; + + @OneToMany(mappedBy = "location", fetch = FetchType.EAGER) + private List vehicles = new ArrayList<>(); +} diff --git a/graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/domain/Vehicle.java b/graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/domain/Vehicle.java new file mode 100644 index 0000000000..e206bdb009 --- /dev/null +++ b/graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/domain/Vehicle.java @@ -0,0 +1,26 @@ +package com.baeldung.graphql.error.handling.domain; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.persistence.*; + +@Data +@Entity +@Builder +@AllArgsConstructor +@NoArgsConstructor +public class Vehicle { + @Id + private String vin; + private Integer year; + private String make; + private String model; + private String trim; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "fk_location") + private Location location; +} diff --git a/graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/exception/AbstractGraphQLException.java b/graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/exception/AbstractGraphQLException.java new file mode 100644 index 0000000000..4e7be50ae4 --- /dev/null +++ b/graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/exception/AbstractGraphQLException.java @@ -0,0 +1,44 @@ +package com.baeldung.graphql.error.handling.exception; + +import graphql.ErrorType; +import graphql.GraphQLError; +import graphql.language.SourceLocation; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class AbstractGraphQLException extends RuntimeException implements GraphQLError { + private Map parameters = new HashMap(); + + public AbstractGraphQLException(String message) { + super(message); + } + + public AbstractGraphQLException(String message, Map additionParams) { + this(message); + if (additionParams != null) { + parameters = additionParams; + } + } + + @Override + public String getMessage() { + return super.getMessage(); + } + + @Override + public List getLocations() { + return null; + } + + @Override + public ErrorType getErrorType() { + return null; + } + + @Override + public Map getExtensions() { + return this.parameters; + } +} diff --git a/graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/exception/GraphQLErrorAdapter.java b/graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/exception/GraphQLErrorAdapter.java new file mode 100644 index 0000000000..d982f98db3 --- /dev/null +++ b/graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/exception/GraphQLErrorAdapter.java @@ -0,0 +1,48 @@ +package com.baeldung.graphql.error.handling.exception; + +import graphql.ErrorType; +import graphql.ExceptionWhileDataFetching; +import graphql.GraphQLError; +import graphql.language.SourceLocation; + +import java.util.List; +import java.util.Map; + +public class GraphQLErrorAdapter implements GraphQLError { + + private GraphQLError error; + + public GraphQLErrorAdapter(GraphQLError error) { + this.error = error; + } + + @Override + public Map getExtensions() { + return error.getExtensions(); + } + + @Override + public List getLocations() { + return error.getLocations(); + } + + @Override + public ErrorType getErrorType() { + return error.getErrorType(); + } + + @Override + public List getPath() { + return error.getPath(); + } + + @Override + public Map toSpecification() { + return error.toSpecification(); + } + + @Override + public String getMessage() { + return (error instanceof ExceptionWhileDataFetching) ? ((ExceptionWhileDataFetching) error).getException().getMessage() : error.getMessage(); + } +} \ No newline at end of file diff --git a/graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/exception/InvalidInputException.java b/graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/exception/InvalidInputException.java new file mode 100644 index 0000000000..78c8e83e27 --- /dev/null +++ b/graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/exception/InvalidInputException.java @@ -0,0 +1,7 @@ +package com.baeldung.graphql.error.handling.exception; + +public class InvalidInputException extends RuntimeException { + public InvalidInputException(String message) { + super(message); + } +} diff --git a/graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/exception/VehicleAlreadyPresentException.java b/graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/exception/VehicleAlreadyPresentException.java new file mode 100644 index 0000000000..8f6f0ce615 --- /dev/null +++ b/graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/exception/VehicleAlreadyPresentException.java @@ -0,0 +1,14 @@ +package com.baeldung.graphql.error.handling.exception; + +import java.util.Map; + +public class VehicleAlreadyPresentException extends AbstractGraphQLException { + + public VehicleAlreadyPresentException(String message) { + super(message); + } + + public VehicleAlreadyPresentException(String message, Map additionParams) { + super(message, additionParams); + } +} diff --git a/graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/exception/VehicleNotFoundException.java b/graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/exception/VehicleNotFoundException.java new file mode 100644 index 0000000000..0d2ad8c597 --- /dev/null +++ b/graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/exception/VehicleNotFoundException.java @@ -0,0 +1,14 @@ +package com.baeldung.graphql.error.handling.exception; + +import java.util.Map; + +public class VehicleNotFoundException extends AbstractGraphQLException { + + public VehicleNotFoundException(String message) { + super(message); + } + + public VehicleNotFoundException(String message, Map params) { + super(message, params); + } +} diff --git a/graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/repository/InventoryRepository.java b/graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/repository/InventoryRepository.java new file mode 100644 index 0000000000..f4a0043408 --- /dev/null +++ b/graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/repository/InventoryRepository.java @@ -0,0 +1,9 @@ +package com.baeldung.graphql.error.handling.repository; + +import com.baeldung.graphql.error.handling.domain.Vehicle; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface InventoryRepository extends JpaRepository { +} diff --git a/graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/repository/LocationRepository.java b/graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/repository/LocationRepository.java new file mode 100644 index 0000000000..716b8d3ef3 --- /dev/null +++ b/graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/repository/LocationRepository.java @@ -0,0 +1,9 @@ +package com.baeldung.graphql.error.handling.repository; + +import com.baeldung.graphql.error.handling.domain.Location; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface LocationRepository extends JpaRepository { +} diff --git a/graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/resolver/Mutation.java b/graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/resolver/Mutation.java new file mode 100644 index 0000000000..8463ebf8eb --- /dev/null +++ b/graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/resolver/Mutation.java @@ -0,0 +1,20 @@ +package com.baeldung.graphql.error.handling.resolver; + +import com.baeldung.graphql.error.handling.domain.Location; +import com.baeldung.graphql.error.handling.domain.Vehicle; +import com.baeldung.graphql.error.handling.service.InventoryService; +import com.coxautodev.graphql.tools.GraphQLMutationResolver; +import org.springframework.stereotype.Component; + +@Component +public class Mutation implements GraphQLMutationResolver { + private InventoryService inventoryService; + + public Mutation(InventoryService inventoryService) { + this.inventoryService = inventoryService; + } + + public Vehicle addVehicle(String vin, Integer year, String make, String model, String trim, Location location) { + return this.inventoryService.addVehicle(vin, year, make, model, trim, location); + } +} diff --git a/graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/resolver/Query.java b/graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/resolver/Query.java new file mode 100644 index 0000000000..ece018464a --- /dev/null +++ b/graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/resolver/Query.java @@ -0,0 +1,29 @@ +package com.baeldung.graphql.error.handling.resolver; + +import com.baeldung.graphql.error.handling.domain.Vehicle; +import com.baeldung.graphql.error.handling.service.InventoryService; +import com.coxautodev.graphql.tools.GraphQLQueryResolver; +import org.springframework.stereotype.Component; + +import java.util.List; + +@Component +public class Query implements GraphQLQueryResolver { + private final InventoryService inventoryService; + + public Query(InventoryService inventoryService) { + this.inventoryService = inventoryService; + } + + public List searchAll() { + return this.inventoryService.searchAll(); + } + + public List searchByLocation(String zipcode) { + return this.inventoryService.searchByLocation(zipcode); + } + + public Vehicle searchByVin(String vin) { + return this.inventoryService.searchByVin(vin); + } +} diff --git a/graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/service/InventoryService.java b/graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/service/InventoryService.java new file mode 100644 index 0000000000..7064b08760 --- /dev/null +++ b/graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/service/InventoryService.java @@ -0,0 +1,67 @@ +package com.baeldung.graphql.error.handling.service; + +import com.baeldung.graphql.error.handling.domain.Location; +import com.baeldung.graphql.error.handling.domain.Vehicle; +import com.baeldung.graphql.error.handling.exception.InvalidInputException; +import com.baeldung.graphql.error.handling.exception.VehicleAlreadyPresentException; +import com.baeldung.graphql.error.handling.exception.VehicleNotFoundException; +import com.baeldung.graphql.error.handling.repository.InventoryRepository; +import com.baeldung.graphql.error.handling.repository.LocationRepository; +import org.apache.commons.lang3.StringUtils; +import org.springframework.stereotype.Service; + +import javax.transaction.Transactional; +import java.util.*; + +@Service +public class InventoryService { + private InventoryRepository inventoryRepository; + private LocationRepository locationRepository; + + public InventoryService(InventoryRepository inventoryRepository, LocationRepository locationRepository) { + this.inventoryRepository = inventoryRepository; + this.locationRepository = locationRepository; + } + + @Transactional + public Vehicle addVehicle(String vin, Integer year, String make, String model, String trim, Location location) { + Optional existingVehicle = this.inventoryRepository.findById(vin); + if (existingVehicle.isPresent()) { + Map params = new HashMap<>(); + params.put("vin", vin); + throw new VehicleAlreadyPresentException("Failed to add vehicle. Vehicle with vin " + vin + " already present.", params); + } + Vehicle vehicle = Vehicle.builder() + .vin(vin) + .year(year) + .make(make) + .model(model) + .location(location) + .trim(trim) + .build(); + + this.locationRepository.save(location); + return this.inventoryRepository.save(vehicle); + } + + public List searchAll() { + return this.inventoryRepository.findAll(); + } + + public List searchByLocation(String zipcode) { + if (StringUtils.isEmpty(zipcode) || zipcode.length() != 5) { + throw new InvalidInputException("Invalid zipcode " + zipcode + " provided."); + } + return this.locationRepository.findById(zipcode) + .map(Location::getVehicles) + .orElse(new ArrayList<>()); + } + + public Vehicle searchByVin(String vin) { + return this.inventoryRepository.findById(vin).orElseThrow(() -> { + Map params = new HashMap<>(); + params.put("vin", vin); + return new VehicleNotFoundException("Vehicle with vin " + vin + " not found.", params); + }); + } +} diff --git a/graphql/graphql-error-handling/src/main/resources/application.yml b/graphql/graphql-error-handling/src/main/resources/application.yml new file mode 100644 index 0000000000..155e133a62 --- /dev/null +++ b/graphql/graphql-error-handling/src/main/resources/application.yml @@ -0,0 +1,23 @@ +graphql: + servlet: + mapping: /graphql + +spring: + datasource: + url: "jdbc:h2:mem:graphqldb" + driverClassName: "org.h2.Driver" + username: sa + password: + + initialization-mode: always + platform: h2 + + jpa: + show-sql: true + properties: + hibernate: + dialect: org.hibernate.dialect.H2Dialect + ddl-auto: none + + h2: + console.enabled: true \ No newline at end of file diff --git a/graphql/graphql-error-handling/src/main/resources/graphql/inventory.graphqls b/graphql/graphql-error-handling/src/main/resources/graphql/inventory.graphqls new file mode 100644 index 0000000000..7dcb5403c1 --- /dev/null +++ b/graphql/graphql-error-handling/src/main/resources/graphql/inventory.graphqls @@ -0,0 +1,23 @@ +type Vehicle { + vin: ID! + year: Int! + make: String! + model: String! + trim: String! +} + +input Location { + city: String + state: String + zipcode: String! +} + +type Query { + searchAll: [Vehicle]! + searchByLocation(zipcode: String!): [Vehicle]! + searchByVin(vin: String!): Vehicle +} + +type Mutation { + addVehicle(vin: ID!, year: Int!, make: String!, model: String!, trim: String, location: Location): Vehicle! +} \ No newline at end of file diff --git a/graphql/graphql-error-handling/src/main/resources/import.sql b/graphql/graphql-error-handling/src/main/resources/import.sql new file mode 100644 index 0000000000..62907a86c3 --- /dev/null +++ b/graphql/graphql-error-handling/src/main/resources/import.sql @@ -0,0 +1,7 @@ +insert into LOCATION values('07092', 'Mountainside', 'NJ'); +insert into LOCATION values ('94118', 'San Francisco', 'CA'); +insert into LOCATION values ('10002', 'New York', 'NY'); + +insert into VEHICLE (vin, year, make, model, trim, fk_location) values('KM8JN72DX7U587496', 2007, 'Hyundai', 'Tucson', null, '07092'); +insert into VEHICLE (vin, year, make, model, trim, fk_location) values('JTKKU4B41C1023346', 2012, 'Toyota', 'Scion', 'Xd', '94118'); +insert into VEHICLE (vin, year, make, model, trim, fk_location) values('1G1JC1444PZ215071', 2000, 'Chevrolet', 'CAVALIER VL', 'RS', '07092'); \ No newline at end of file diff --git a/graphql/graphql-error-handling/src/test/java/com/baeldung/graphql/error/handling/GraphQLErrorHandlerApplicationIntegrationTest.java b/graphql/graphql-error-handling/src/test/java/com/baeldung/graphql/error/handling/GraphQLErrorHandlerApplicationIntegrationTest.java new file mode 100644 index 0000000000..069a08ce02 --- /dev/null +++ b/graphql/graphql-error-handling/src/test/java/com/baeldung/graphql/error/handling/GraphQLErrorHandlerApplicationIntegrationTest.java @@ -0,0 +1,55 @@ +package com.baeldung.graphql.error.handling; + +import com.graphql.spring.boot.test.GraphQLResponse; +import com.graphql.spring.boot.test.GraphQLTestTemplate; +import org.json.JSONException; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.skyscreamer.jsonassert.JSONAssert; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.test.context.junit4.SpringRunner; + +import java.io.IOException; + +import static com.baeldung.graphql.error.handling.TestUtils.readFile; +import static java.lang.String.format; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = GraphQLErrorHandlerApplication.class) +public class GraphQLErrorHandlerApplicationIntegrationTest { + + @Autowired + private GraphQLTestTemplate graphQLTestTemplate; + + private static final String GRAPHQL_TEST_REQUEST_PATH = "graphql/request/%s.graphql"; + private static final String GRAPHQL_TEST_RESPONSE_PATH = "graphql/response/%s.json"; + + @Test + public void whenUnknownOperation_thenRespondWithRequestError() throws IOException, JSONException { + String graphqlName = "request_error_unknown_operation"; + GraphQLResponse actualResponse = graphQLTestTemplate.postForResource(format(GRAPHQL_TEST_REQUEST_PATH, graphqlName)); + String expectedResponse = readFile(format(GRAPHQL_TEST_RESPONSE_PATH, graphqlName)); + + JSONAssert.assertEquals(expectedResponse, actualResponse.getRawResponse().getBody(), true); + } + + @Test + public void whenInvalidSyntaxRequest_thenRespondWithRequestError() throws IOException, JSONException { + String graphqlName = "request_error_invalid_request_syntax"; + GraphQLResponse actualResponse = graphQLTestTemplate.postForResource(format(GRAPHQL_TEST_REQUEST_PATH, graphqlName)); + String expectedResponse = readFile(format(GRAPHQL_TEST_RESPONSE_PATH, graphqlName)); + + JSONAssert.assertEquals(expectedResponse, actualResponse.getRawResponse().getBody(), true); + } + + @Test + public void whenRequestAllNonNullField_thenRespondPartialDataWithFieldError() throws IOException, JSONException { + String graphqlName = "field_error_request_non_null_fields_partial_response"; + GraphQLResponse actualResponse = graphQLTestTemplate.postForResource(format(GRAPHQL_TEST_REQUEST_PATH, graphqlName)); + String expectedResponse = readFile(format(GRAPHQL_TEST_RESPONSE_PATH, graphqlName)); + + JSONAssert.assertEquals(expectedResponse, actualResponse.getRawResponse().getBody(), true); + } +} diff --git a/graphql/graphql-error-handling/src/test/java/com/baeldung/graphql/error/handling/TestUtils.java b/graphql/graphql-error-handling/src/test/java/com/baeldung/graphql/error/handling/TestUtils.java new file mode 100644 index 0000000000..557f1d9c91 --- /dev/null +++ b/graphql/graphql-error-handling/src/test/java/com/baeldung/graphql/error/handling/TestUtils.java @@ -0,0 +1,15 @@ +package com.baeldung.graphql.error.handling; + +import org.apache.commons.io.IOUtils; +import org.springframework.core.io.ClassPathResource; + +import java.io.IOException; +import java.nio.charset.Charset; + +public class TestUtils { + public static String readFile(String path) throws IOException { + return IOUtils.toString( + new ClassPathResource(path).getInputStream(), Charset.defaultCharset() + ); + } +} diff --git a/graphql/graphql-error-handling/src/test/resources/graphql/request/field_error_request_non_null_fields_partial_response.graphql b/graphql/graphql-error-handling/src/test/resources/graphql/request/field_error_request_non_null_fields_partial_response.graphql new file mode 100644 index 0000000000..17affc50cb --- /dev/null +++ b/graphql/graphql-error-handling/src/test/resources/graphql/request/field_error_request_non_null_fields_partial_response.graphql @@ -0,0 +1,10 @@ +# trim is non null but one of the record has null value for trim +query { + searchAll { + vin + year + make + model + trim + } +} \ No newline at end of file diff --git a/graphql/graphql-error-handling/src/test/resources/graphql/request/request_error_invalid_request_syntax.graphql b/graphql/graphql-error-handling/src/test/resources/graphql/request/request_error_invalid_request_syntax.graphql new file mode 100644 index 0000000000..98920eb17a --- /dev/null +++ b/graphql/graphql-error-handling/src/test/resources/graphql/request/request_error_invalid_request_syntax.graphql @@ -0,0 +1,9 @@ +query { + searchByVin(vin: "error) { + vin + year + make + model + trim + } +} \ No newline at end of file diff --git a/graphql/graphql-error-handling/src/test/resources/graphql/request/request_error_unknown_operation.graphql b/graphql/graphql-error-handling/src/test/resources/graphql/request/request_error_unknown_operation.graphql new file mode 100644 index 0000000000..fb6c3d1039 --- /dev/null +++ b/graphql/graphql-error-handling/src/test/resources/graphql/request/request_error_unknown_operation.graphql @@ -0,0 +1,9 @@ +subscription { + searchByVin(vin: "75024") { + vin + year + make + model + trim + } +} \ No newline at end of file diff --git a/graphql/graphql-error-handling/src/test/resources/graphql/response/field_error_request_non_null_fields_partial_response.json b/graphql/graphql-error-handling/src/test/resources/graphql/response/field_error_request_non_null_fields_partial_response.json new file mode 100644 index 0000000000..760190128e --- /dev/null +++ b/graphql/graphql-error-handling/src/test/resources/graphql/response/field_error_request_non_null_fields_partial_response.json @@ -0,0 +1,34 @@ +{ + "data": { + "searchAll": [ + null, + { + "vin": "JTKKU4B41C1023346", + "year": 2012, + "make": "Toyota", + "model": "Scion", + "trim": "Xd" + }, + { + "vin": "1G1JC1444PZ215071", + "year": 2000, + "make": "Chevrolet", + "model": "CAVALIER VL", + "trim": "RS" + } + ] + }, + "errors": [ + { + "message": "Cannot return null for non-nullable type: 'String' within parent 'Vehicle' (/searchAll[0]/trim)", + "path": [ + "searchAll", + 0, + "trim" + ], + "errorType": "DataFetchingException", + "locations": null, + "extensions": null + } + ] +} \ No newline at end of file diff --git a/graphql/graphql-error-handling/src/test/resources/graphql/response/request_error_invalid_request_syntax.json b/graphql/graphql-error-handling/src/test/resources/graphql/response/request_error_invalid_request_syntax.json new file mode 100644 index 0000000000..2835b42133 --- /dev/null +++ b/graphql/graphql-error-handling/src/test/resources/graphql/response/request_error_invalid_request_syntax.json @@ -0,0 +1,18 @@ +{ + "data": null, + "errors": [ + { + "message": "Invalid Syntax", + "locations": [ + { + "line": 5, + "column": 8, + "sourceName": null + } + ], + "errorType": "InvalidSyntax", + "path": null, + "extensions": null + } + ] +} \ No newline at end of file diff --git a/graphql/graphql-error-handling/src/test/resources/graphql/response/request_error_unknown_operation.json b/graphql/graphql-error-handling/src/test/resources/graphql/response/request_error_unknown_operation.json new file mode 100644 index 0000000000..b5872fc80f --- /dev/null +++ b/graphql/graphql-error-handling/src/test/resources/graphql/response/request_error_unknown_operation.json @@ -0,0 +1,18 @@ +{ + "data": null, + "errors": [ + { + "errorType": "OperationNotSupported", + "locations": [ + { + "line": 1, + "column": 1, + "sourceName": null + } + ], + "extensions": null, + "message": "Schema is not configured for subscriptions.", + "path": null + } + ] +} \ No newline at end of file diff --git a/graphql/graphql-error-handling/src/test/resources/init_script.sql b/graphql/graphql-error-handling/src/test/resources/init_script.sql new file mode 100644 index 0000000000..e69de29bb2 diff --git a/graphql/graphql-java/pom.xml b/graphql/graphql-java/pom.xml index f2733bf671..5808dd17fb 100644 --- a/graphql/graphql-java/pom.xml +++ b/graphql/graphql-java/pom.xml @@ -12,7 +12,7 @@ com.baeldung parent-modules 1.0.0-SNAPSHOT - ../../ + ../../pom.xml @@ -36,51 +36,15 @@ graphql-java-annotations ${graphql-java-annotations.version} - - io.ratpack - ratpack-core - ${ratpack-core.version} - - - com.github.americanexpress.nodes - nodes - 0.5.0 - - - com.graphql-java - graphql-java - 9.2 - com.graphql-java graphql-java-tools - 5.2.4 + ${graphql-java-tools.version} com.graphql-java graphql-java-servlet - 6.1.3 - - - javax.servlet - javax.servlet-api - 3.0.1 - provided - - - org.apache.commons - commons-lang3 - 3.12.0 - - - org.mock-server - mockserver-netty - 5.11.2 - - - org.mock-server - mockserver-client-java - 5.11.2 + ${graphql-java-servlet.version} com.graphql-java-generator @@ -88,15 +52,47 @@ ${graphql.java.generator.version} - org.junit.jupiter - junit-jupiter-engine - 5.8.2 + javax.servlet + javax.servlet-api + ${javax.servlet-api.version} + provided + + + com.fasterxml.jackson.core + jackson-core + ${jackson.version} + + + io.ratpack + ratpack-core + ${ratpack-core.version} + + + com.github.americanexpress.nodes + nodes + ${nodes.version} + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + org.apache.httpcomponents + httpclient + ${httpclient.version} + + + + org.mock-server + mockserver-netty + ${mockserver-netty.version} test - org.assertj - assertj-core - 3.22.0 + org.mock-server + mockserver-client-java + ${mockserver-client-java.version} test @@ -115,11 +111,11 @@ org.eclipse.jetty jetty-maven-plugin - 10.0.7 + ${jetty-maven-plugin.version} maven-war-plugin - 3.1.0 + ${maven-war-plugin.version} com.graphql-java-generator @@ -143,12 +139,21 @@ + 5.2.4 + 6.1.3 3.0.3 - 1.4.6 - 3.1 + 1.18 + 1.9.0 + 0.5.0 + 4.5.13 + + 5.13.2 + 5.13.2 + + 10.0.7 + 1.8 1.8 - 1.18 \ No newline at end of file diff --git a/graphql/graphql-java/src/main/java/com/baeldung/graphql/handler/UserHandler.java b/graphql/graphql-java/src/main/java/com/baeldung/graphql/handler/UserHandler.java index a6d474a70d..eb7cf021c6 100644 --- a/graphql/graphql-java/src/main/java/com/baeldung/graphql/handler/UserHandler.java +++ b/graphql/graphql-java/src/main/java/com/baeldung/graphql/handler/UserHandler.java @@ -19,24 +19,27 @@ import com.baeldung.graphql.utils.SchemaUtils; import static ratpack.jackson.Jackson.json; public class UserHandler implements Handler { + private static final Logger LOGGER = Logger.getLogger(UserHandler.class.getSimpleName()); - private GraphQL graphql; - private static List users = new ArrayList<>(); + + private static final List USERS = new ArrayList<>(); + + private final GraphQL graphql; public UserHandler() throws Exception { - graphql = new GraphQL(new UserSchema().getSchema()); + graphql = GraphQL.newGraphQL(new UserSchema().getSchema()).build(); } @Override - public void handle(Context context) throws Exception { + public void handle(Context context) { context.parse(Map.class) .then(payload -> { Map parameters = (Map) payload.get("parameters"); ExecutionResult executionResult = graphql.execute(payload.get(SchemaUtils.QUERY) .toString(), null, this, parameters); + Map result = new LinkedHashMap<>(); - if (executionResult.getErrors() - .isEmpty()) { + if (executionResult.getErrors().isEmpty()) { result.put(SchemaUtils.DATA, executionResult.getData()); } else { result.put(SchemaUtils.ERRORS, executionResult.getErrors()); @@ -46,8 +49,8 @@ public class UserHandler implements Handler { }); } - public static List getUsers() { - return users; + public List getUsers() { + return USERS; } public static List getUsers(DataFetchingEnvironment env) { diff --git a/httpclient-2/README.md b/httpclient-2/README.md index 49adf470e9..2e101a0609 100644 --- a/httpclient-2/README.md +++ b/httpclient-2/README.md @@ -12,5 +12,6 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Reading an HTTP Response Body as a String in Java](https://www.baeldung.com/java-http-response-body-as-string) - [How To Get Cookies From the Apache HttpClient Response](https://www.baeldung.com/java-apache-httpclient-cookies) - [Enabling Logging for Apache HttpClient](https://www.baeldung.com/apache-httpclient-enable-logging) -- [Unshorten URLs with HttpClient](https://www.baeldung.com/unshorten-url-httpclient) +- [Expand Shortened URLs with Apache HttpClient](https://www.baeldung.com/apache-httpclient-expand-url) +- [Apache HttpClient vs. CloseableHttpClient](https://www.baeldung.com/apache-httpclient-vs-closeablehttpclient) - More articles: [[<-- prev]](../httpclient) diff --git a/httpclient-2/src/test/java/com/baeldung/httpclient/rare/HttpClientUnshortenLiveTest.java b/httpclient-2/src/test/java/com/baeldung/httpclient/expandurl/HttpClientExpandUrlLiveTest.java similarity index 89% rename from httpclient-2/src/test/java/com/baeldung/httpclient/rare/HttpClientUnshortenLiveTest.java rename to httpclient-2/src/test/java/com/baeldung/httpclient/expandurl/HttpClientExpandUrlLiveTest.java index efa7953ba8..5a8c87f4aa 100644 --- a/httpclient-2/src/test/java/com/baeldung/httpclient/rare/HttpClientUnshortenLiveTest.java +++ b/httpclient-2/src/test/java/com/baeldung/httpclient/expandurl/HttpClientExpandUrlLiveTest.java @@ -1,4 +1,4 @@ -package com.baeldung.httpclient.rare; +package com.baeldung.httpclient.expandurl; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; @@ -22,35 +22,29 @@ import java.util.List; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat; -public class HttpClientUnshortenLiveTest { +public class HttpClientExpandUrlLiveTest { private CloseableHttpClient client; - // fixtures - @Before public final void before() { client = HttpClientBuilder.create().disableRedirectHandling().build(); } - // tests - @Test - public final void givenShortenedOnce_whenUrlIsUnshortened_thenCorrectResult() throws IOException { - final String expectedResult = "http://www.baeldung.com/rest-versioning"; - final String actualResult = expandSingleLevel("http://bit.ly/13jEoS1"); + public final void givenShortenedOnce_whenUrlIsExpanded_thenCorrectResult() throws IOException { + final String expectedResult = "https://www.baeldung.com/rest-versioning"; + final String actualResult = expandSingleLevel("http://bit.ly/3LScTri"); assertThat(actualResult, equalTo(expectedResult)); } @Test - public final void givenShortenedMultiple_whenUrlIsUnshortened_thenCorrectResult() throws IOException { - final String expectedResult = "http://www.baeldung.com/rest-versioning"; + public final void givenShortenedMultiple_whenUrlIsExpanded_thenCorrectResult() throws IOException { + final String expectedResult = "https://www.baeldung.com/rest-versioning"; final String actualResult = expand("http://t.co/e4rDDbnzmk"); assertThat(actualResult, equalTo(expectedResult)); } - // API - private String expand(final String urlArg) throws IOException { String originalUrl = urlArg; String newUrl = expandSingleLevel(originalUrl); diff --git a/immutables/README.md b/immutables/README.md deleted file mode 100644 index a93a342f9c..0000000000 --- a/immutables/README.md +++ /dev/null @@ -1,6 +0,0 @@ -## Immutables - -This module contains articles about the Immutables library. - -### Relevant Articles: -- [Introduction to Immutables](https://www.baeldung.com/immutables) diff --git a/immutables/pom.xml b/immutables/pom.xml deleted file mode 100644 index 7704cddbb6..0000000000 --- a/immutables/pom.xml +++ /dev/null @@ -1,34 +0,0 @@ - - - 4.0.0 - immutables - immutables - - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - - - - - org.immutables - value - ${immutables.version} - - - org.mutabilitydetector - MutabilityDetector - ${mutabilitydetector.version} - test - - - - - 2.5.6 - 0.9.6 - - - \ No newline at end of file diff --git a/jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/deductionbasedpolymorphism/Character.java b/jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/deductionbasedpolymorphism/Character.java new file mode 100644 index 0000000000..6be7483cc2 --- /dev/null +++ b/jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/deductionbasedpolymorphism/Character.java @@ -0,0 +1,12 @@ +package com.baeldung.jackson.deductionbasedpolymorphism; + +import com.fasterxml.jackson.annotation.JsonSubTypes; +import com.fasterxml.jackson.annotation.JsonSubTypes.Type; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeInfo.Id; + +@JsonTypeInfo(use = Id.DEDUCTION) +@JsonSubTypes({ @Type(ImperialSpy.class), @Type(King.class), @Type(Knight.class) }) +public interface Character { + +} diff --git a/jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/deductionbasedpolymorphism/ControlledCharacter.java b/jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/deductionbasedpolymorphism/ControlledCharacter.java new file mode 100644 index 0000000000..9f6f03954e --- /dev/null +++ b/jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/deductionbasedpolymorphism/ControlledCharacter.java @@ -0,0 +1,14 @@ +package com.baeldung.jackson.deductionbasedpolymorphism; + +public class ControlledCharacter { + + private Character character; + + public Character getCharacter() { + return character; + } + + public void setCharacter(Character character) { + this.character = character; + } +} diff --git a/jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/deductionbasedpolymorphism/ImperialSpy.java b/jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/deductionbasedpolymorphism/ImperialSpy.java new file mode 100644 index 0000000000..ff86966e38 --- /dev/null +++ b/jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/deductionbasedpolymorphism/ImperialSpy.java @@ -0,0 +1,5 @@ +package com.baeldung.jackson.deductionbasedpolymorphism; + +public class ImperialSpy implements Character { + +} diff --git a/jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/deductionbasedpolymorphism/King.java b/jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/deductionbasedpolymorphism/King.java new file mode 100644 index 0000000000..3270d92b3a --- /dev/null +++ b/jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/deductionbasedpolymorphism/King.java @@ -0,0 +1,14 @@ +package com.baeldung.jackson.deductionbasedpolymorphism; + +public class King extends NamedCharacter { + + private String land; + + public String getLand() { + return land; + } + + public void setLand(String land) { + this.land = land; + } +} diff --git a/jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/deductionbasedpolymorphism/Knight.java b/jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/deductionbasedpolymorphism/Knight.java new file mode 100644 index 0000000000..197d3b758b --- /dev/null +++ b/jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/deductionbasedpolymorphism/Knight.java @@ -0,0 +1,14 @@ +package com.baeldung.jackson.deductionbasedpolymorphism; + +public class Knight extends NamedCharacter { + + private String weapon; + + public String getWeapon() { + return weapon; + } + + public void setWeapon(String weapon) { + this.weapon = weapon; + } +} diff --git a/jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/deductionbasedpolymorphism/NamedCharacter.java b/jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/deductionbasedpolymorphism/NamedCharacter.java new file mode 100644 index 0000000000..15892f8659 --- /dev/null +++ b/jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/deductionbasedpolymorphism/NamedCharacter.java @@ -0,0 +1,14 @@ +package com.baeldung.jackson.deductionbasedpolymorphism; + +public class NamedCharacter implements Character { + + private String name; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/jackson-modules/jackson-annotations/src/test/java/com/baeldung/jackson/deductionbasedpolymorphism/CaseInsensitiveInferenceUnitTest.java b/jackson-modules/jackson-annotations/src/test/java/com/baeldung/jackson/deductionbasedpolymorphism/CaseInsensitiveInferenceUnitTest.java new file mode 100644 index 0000000000..cad9e73091 --- /dev/null +++ b/jackson-modules/jackson-annotations/src/test/java/com/baeldung/jackson/deductionbasedpolymorphism/CaseInsensitiveInferenceUnitTest.java @@ -0,0 +1,33 @@ +package com.baeldung.jackson.deductionbasedpolymorphism; + +import static com.baeldung.jackson.deductionbasedpolymorphism.JsonStringFormatterUtil.formatJson; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; + +import com.fasterxml.jackson.databind.MapperFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.json.JsonMapper; + +class CaseInsensitiveInferenceUnitTest { + + private final ObjectMapper objectMapper = JsonMapper.builder() + .configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true) + .build(); + + @Test + void givenACaseInsensitiveKnight_whenMapping_thenExpectKnight() throws Exception { + String knightJson = formatJson("{'NaMe':'Ostrava, of Boletaria', 'WeaPON':'Rune Sword'}"); + + Character character = objectMapper.readValue(knightJson, Character.class); + + assertTrue(character instanceof Knight); + assertSame(character.getClass(), Knight.class); + Knight knight = (Knight) character; + assertEquals("Ostrava, of Boletaria", knight.getName()); + assertEquals("Rune Sword", knight.getWeapon()); + } + +} diff --git a/jackson-modules/jackson-annotations/src/test/java/com/baeldung/jackson/deductionbasedpolymorphism/ContainedInferenceUnitTest.java b/jackson-modules/jackson-annotations/src/test/java/com/baeldung/jackson/deductionbasedpolymorphism/ContainedInferenceUnitTest.java new file mode 100644 index 0000000000..810051f2ab --- /dev/null +++ b/jackson-modules/jackson-annotations/src/test/java/com/baeldung/jackson/deductionbasedpolymorphism/ContainedInferenceUnitTest.java @@ -0,0 +1,73 @@ +package com.baeldung.jackson.deductionbasedpolymorphism; + +import static com.baeldung.jackson.deductionbasedpolymorphism.JsonStringFormatterUtil.formatJson; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.json.JsonMapper; + +class ContainedInferenceUnitTest { + + private final ObjectMapper objectMapper = JsonMapper.builder() + .build(); + + @Test + void givenAKnightControlledCharacter_whenMapping_thenExpectAControlledCharacterWithKnight() throws Exception { + String controlledCharacterJson = formatJson("{'character': {'name': 'Ostrava, of Boletaria', 'weapon': 'Rune Sword'}}"); + + ControlledCharacter controlledCharacter = objectMapper.readValue(controlledCharacterJson, ControlledCharacter.class); + Character character = controlledCharacter.getCharacter(); + + assertTrue(character instanceof Knight); + assertSame(character.getClass(), Knight.class); + Knight knight = (Knight) character; + assertEquals("Ostrava, of Boletaria", knight.getName()); + assertEquals("Rune Sword", knight.getWeapon()); + } + + @Test + void givenAKingControlledCharacter_whenMapping_thenExpectAControlledCharacterWithKing() throws Exception { + String controlledCharacterJson = formatJson("{'character': {'name': 'King Allant', 'land': 'Boletaria'}}"); + + ControlledCharacter controlledCharacter = objectMapper.readValue(controlledCharacterJson, ControlledCharacter.class); + Character character = controlledCharacter.getCharacter(); + + assertTrue(character instanceof King); + assertSame(character.getClass(), King.class); + King king = (King) character; + assertEquals("King Allant", king.getName()); + assertEquals("Boletaria", king.getLand()); + } + + @Test + void givenAnEmptySubtype_whenMapping_thenExpectImperialSpy() throws Exception { + String controlledCharacterJson = formatJson("{'character': {}}"); + + ControlledCharacter controlledCharacter = objectMapper.readValue(controlledCharacterJson, ControlledCharacter.class); + + assertTrue(controlledCharacter.getCharacter() instanceof ImperialSpy); + } + + @Test + void givenANullCharacter_whenMapping_thenExpectNullCharacter() throws Exception { + String controlledCharacterJson = formatJson("{'character': null}"); + + ControlledCharacter controlledCharacter = objectMapper.readValue(controlledCharacterJson, ControlledCharacter.class); + + assertNull(controlledCharacter.getCharacter()); + } + + @Test + void givenAAnAbsentCharacter_whenMapping_thenExpectNullCharacter() throws Exception { + String controlledCharacterJson = formatJson("{}"); + + ControlledCharacter controlledCharacter = objectMapper.readValue(controlledCharacterJson, ControlledCharacter.class); + + assertNull(controlledCharacter.getCharacter()); + } +} diff --git a/jackson-modules/jackson-annotations/src/test/java/com/baeldung/jackson/deductionbasedpolymorphism/JsonStringFormatterUtil.java b/jackson-modules/jackson-annotations/src/test/java/com/baeldung/jackson/deductionbasedpolymorphism/JsonStringFormatterUtil.java new file mode 100644 index 0000000000..948b264c45 --- /dev/null +++ b/jackson-modules/jackson-annotations/src/test/java/com/baeldung/jackson/deductionbasedpolymorphism/JsonStringFormatterUtil.java @@ -0,0 +1,9 @@ +package com.baeldung.jackson.deductionbasedpolymorphism; + +public class JsonStringFormatterUtil { + + public static String formatJson(String input) { + return input.replaceAll("'", "\""); + } + +} diff --git a/jackson-modules/jackson-annotations/src/test/java/com/baeldung/jackson/deductionbasedpolymorphism/SimpleInferenceUnitTest.java b/jackson-modules/jackson-annotations/src/test/java/com/baeldung/jackson/deductionbasedpolymorphism/SimpleInferenceUnitTest.java new file mode 100644 index 0000000000..5e63e95289 --- /dev/null +++ b/jackson-modules/jackson-annotations/src/test/java/com/baeldung/jackson/deductionbasedpolymorphism/SimpleInferenceUnitTest.java @@ -0,0 +1,61 @@ +package com.baeldung.jackson.deductionbasedpolymorphism; + +import static com.baeldung.jackson.deductionbasedpolymorphism.JsonStringFormatterUtil.formatJson; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.json.JsonMapper; + +class SimpleInferenceUnitTest { + + private final ObjectMapper objectMapper = JsonMapper.builder() + .build(); + + @Test + void givenAKnight_whenMapping_thenExpectAKnightType() throws Exception { + String knightJson = formatJson("{'name':'Ostrava, of Boletaria', 'weapon':'Rune Sword'}"); + + Character character = objectMapper.readValue(knightJson, Character.class); + + assertTrue(character instanceof Knight); + assertSame(character.getClass(), Knight.class); + Knight king = (Knight) character; + assertEquals("Ostrava, of Boletaria", king.getName()); + assertEquals("Rune Sword", king.getWeapon()); + } + + @Test + void givenAKing_whenMapping_thenExpectAKingType() throws Exception { + String kingJson = formatJson("{'name':'Old King Allant', 'land':'Boletaria'}"); + + Character character = objectMapper.readValue(kingJson, Character.class); + + assertTrue(character instanceof King); + assertSame(character.getClass(), King.class); + King king = (King) character; + assertEquals("Old King Allant", king.getName()); + assertEquals("Boletaria", king.getLand()); + } + + @Test + void givenAnEmptyObject_whenMapping_thenExpectAnImperialSpy() throws Exception { + String imperialSpyJson = "{}"; + + Character character = objectMapper.readValue(imperialSpyJson, Character.class); + + assertTrue(character instanceof ImperialSpy); + } + + @Test + void givenANullObject_whenMapping_thenExpectANullObject() throws Exception { + Character character = objectMapper.readValue("null", Character.class); + + assertNull(character); + } + +} diff --git a/java-numbers-4/README.md b/java-numbers-4/README.md index a6d866218c..95d46203ab 100644 --- a/java-numbers-4/README.md +++ b/java-numbers-4/README.md @@ -5,3 +5,4 @@ - [Determine if an Integer’s Square Root Is an Integer in Java](https://www.baeldung.com/java-find-if-square-root-is-integer) - [Guide to Java BigInteger](https://www.baeldung.com/java-biginteger) - [Automorphic Numbers in Java](https://www.baeldung.com/java-automorphic-numbers) +- [Convert Byte Size Into a Human-Readable Format in Java](https://www.baeldung.com/java-human-readable-byte-size) diff --git a/jmeter/README.md b/jmeter/README.md index 6fdc79a2ce..23614307bd 100644 --- a/jmeter/README.md +++ b/jmeter/README.md @@ -53,3 +53,4 @@ Enjoy it :) - [Intro to Performance Testing using JMeter](https://www.baeldung.com/jmeter) - [Configure Jenkins to Run and Show JMeter Tests](https://www.baeldung.com/ops/jenkins-and-jmeter) - [Write Extracted Data to a File Using JMeter](https://www.baeldung.com/jmeter-write-to-file) +- [Basic Authentication in JMeter](https://www.baeldung.com/jmeter-basic-auth) diff --git a/libraries-3/README.md b/libraries-3/README.md index 047d6738a1..b267e82ed9 100644 --- a/libraries-3/README.md +++ b/libraries-3/README.md @@ -17,4 +17,5 @@ Remember, for advanced libraries like [Jackson](/jackson) and [JUnit](/testing-m - [Using NullAway to Avoid NullPointerExceptions](https://www.baeldung.com/java-nullaway) - [Introduction to Alibaba Arthas](https://www.baeldung.com/java-alibaba-arthas-intro) - [Introduction to Structurizr](https://www.baeldung.com/structurizr) +- [Introduction to Immutables](https://www.baeldung.com/immutables) - More articles [[<-- prev]](../libraries-2) [[next -->]](../libraries-4) diff --git a/libraries-3/pom.xml b/libraries-3/pom.xml index e38aecd879..c51b264e83 100644 --- a/libraries-3/pom.xml +++ b/libraries-3/pom.xml @@ -112,6 +112,17 @@ structurizr-plantuml ${structurizr.version} + + org.immutables + value + ${immutables.version} + + + org.mutabilitydetector + MutabilityDetector + ${mutabilitydetector.version} + test + @@ -256,6 +267,8 @@ 2.8 2.1.3 1.0.0 + 2.5.6 + 0.9.6 \ No newline at end of file diff --git a/immutables/src/main/java/com/baeldung/immutable/Address.java b/libraries-3/src/main/java/com/baeldung/immutable/Address.java similarity index 100% rename from immutables/src/main/java/com/baeldung/immutable/Address.java rename to libraries-3/src/main/java/com/baeldung/immutable/Address.java diff --git a/immutables/src/main/java/com/baeldung/immutable/Person.java b/libraries-3/src/main/java/com/baeldung/immutable/Person.java similarity index 100% rename from immutables/src/main/java/com/baeldung/immutable/Person.java rename to libraries-3/src/main/java/com/baeldung/immutable/Person.java diff --git a/immutables/src/main/java/com/baeldung/immutable/auxiliary/Person.java b/libraries-3/src/main/java/com/baeldung/immutable/auxiliary/Person.java similarity index 100% rename from immutables/src/main/java/com/baeldung/immutable/auxiliary/Person.java rename to libraries-3/src/main/java/com/baeldung/immutable/auxiliary/Person.java diff --git a/immutables/src/main/java/com/baeldung/immutable/default_/Person.java b/libraries-3/src/main/java/com/baeldung/immutable/default_/Person.java similarity index 100% rename from immutables/src/main/java/com/baeldung/immutable/default_/Person.java rename to libraries-3/src/main/java/com/baeldung/immutable/default_/Person.java diff --git a/immutables/src/main/java/com/baeldung/immutable/parameter/Person.java b/libraries-3/src/main/java/com/baeldung/immutable/parameter/Person.java similarity index 100% rename from immutables/src/main/java/com/baeldung/immutable/parameter/Person.java rename to libraries-3/src/main/java/com/baeldung/immutable/parameter/Person.java diff --git a/immutables/src/main/java/com/baeldung/immutable/prehash/Person.java b/libraries-3/src/main/java/com/baeldung/immutable/prehash/Person.java similarity index 100% rename from immutables/src/main/java/com/baeldung/immutable/prehash/Person.java rename to libraries-3/src/main/java/com/baeldung/immutable/prehash/Person.java diff --git a/immutables/src/test/java/com/baeldung/immutable/ImmutablePersonUnitTest.java b/libraries-3/src/test/java/com/baeldung/immutable/ImmutablePersonUnitTest.java similarity index 100% rename from immutables/src/test/java/com/baeldung/immutable/ImmutablePersonUnitTest.java rename to libraries-3/src/test/java/com/baeldung/immutable/ImmutablePersonUnitTest.java diff --git a/immutables/src/test/java/com/baeldung/immutable/auxiliary/ImmutablePersonAuxiliaryUnitTest.java b/libraries-3/src/test/java/com/baeldung/immutable/auxiliary/ImmutablePersonAuxiliaryUnitTest.java similarity index 100% rename from immutables/src/test/java/com/baeldung/immutable/auxiliary/ImmutablePersonAuxiliaryUnitTest.java rename to libraries-3/src/test/java/com/baeldung/immutable/auxiliary/ImmutablePersonAuxiliaryUnitTest.java diff --git a/immutables/src/test/java/com/baeldung/immutable/default_/ImmutablePersonDefaultUnitTest.java b/libraries-3/src/test/java/com/baeldung/immutable/default_/ImmutablePersonDefaultUnitTest.java similarity index 100% rename from immutables/src/test/java/com/baeldung/immutable/default_/ImmutablePersonDefaultUnitTest.java rename to libraries-3/src/test/java/com/baeldung/immutable/default_/ImmutablePersonDefaultUnitTest.java diff --git a/persistence-modules/hibernate-annotations/pom.xml b/persistence-modules/hibernate-annotations/pom.xml index ed158216fb..023e5aa30f 100644 --- a/persistence-modules/hibernate-annotations/pom.xml +++ b/persistence-modules/hibernate-annotations/pom.xml @@ -82,7 +82,7 @@ 5.0.2.RELEASE 1.10.6.RELEASE - 5.4.7.Final + 5.6.7.Final true 2.1.7.RELEASE 1.4.200 diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/config/HibernateAnnotationUtil.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/config/HibernateAnnotationUtil.java index 46e6824f42..6c94d34339 100644 --- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/config/HibernateAnnotationUtil.java +++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/config/HibernateAnnotationUtil.java @@ -1,34 +1,51 @@ package com.baeldung.hibernate.oneToMany.config; +import com.baeldung.hibernate.oneToMany.model.Cart; +import com.baeldung.hibernate.oneToMany.model.CartOIO; +import com.baeldung.hibernate.oneToMany.model.Item; +import com.baeldung.hibernate.oneToMany.model.ItemOIO; import org.hibernate.SessionFactory; import org.hibernate.boot.Metadata; import org.hibernate.boot.MetadataSources; +import org.hibernate.boot.model.naming.ImplicitNamingStrategyJpaCompliantImpl; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.service.ServiceRegistry; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class HibernateAnnotationUtil { + private static final Logger LOGGER = LoggerFactory.getLogger(HibernateAnnotationUtil.class); + private static SessionFactory sessionFactory; + public static SessionFactory getSessionFactory() { + if (sessionFactory == null) { + sessionFactory = buildSessionFactory(); + } + return sessionFactory; + } + private static SessionFactory buildSessionFactory() { try { - // Create the SessionFactory from hibernate-annotation.cfg.xml - ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().configure("hibernate-annotation.cfg.xml").build(); - Metadata metadata = new MetadataSources(serviceRegistry).getMetadataBuilder().build(); - SessionFactory sessionFactory = metadata.getSessionFactoryBuilder().build(); + ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() + .configure("hibernate-annotation.cfg.xml") + .build(); - return sessionFactory; + Metadata metadata = new MetadataSources(serviceRegistry) + .addAnnotatedClass(Cart.class) + .addAnnotatedClass(CartOIO.class) + .addAnnotatedClass(Item.class) + .addAnnotatedClass(ItemOIO.class) + .getMetadataBuilder() + .applyImplicitNamingStrategy(ImplicitNamingStrategyJpaCompliantImpl.INSTANCE) + .build(); + + return metadata.getSessionFactoryBuilder().build(); } catch (Throwable ex) { - System.err.println("Initial SessionFactory creation failed." + ex); - ex.printStackTrace(); + LOGGER.error("Initial SessionFactory creation failed.", ex); throw new ExceptionInInitializerError(ex); } } - - public static SessionFactory getSessionFactory() { - if (sessionFactory == null) - sessionFactory = buildSessionFactory(); - return sessionFactory; - } } diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateManyIsOwningSide.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateManyIsOwningSide.java new file mode 100644 index 0000000000..f74aecbb92 --- /dev/null +++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateManyIsOwningSide.java @@ -0,0 +1,71 @@ +package com.baeldung.hibernate.oneToMany.main; + +import java.util.HashSet; +import java.util.Set; + +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; + +import com.baeldung.hibernate.oneToMany.config.HibernateAnnotationUtil; +import com.baeldung.hibernate.oneToMany.model.Cart; +import com.baeldung.hibernate.oneToMany.model.Item; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class HibernateManyIsOwningSide { + + private static final Logger LOGGER = LoggerFactory.getLogger(HibernateManyIsOwningSide.class); + + public static void main(String[] args) { + + Cart cart = new Cart(); + Cart cart2 = new Cart(); + + Item item1 = new Item(cart); + Item item2 = new Item(cart2); + + Set itemsSet = new HashSet<>(); + itemsSet.add(item1); + itemsSet.add(item2); + cart.setItems(itemsSet); + + // Get Session + SessionFactory sessionFactory = HibernateAnnotationUtil.getSessionFactory(); + Session session = sessionFactory.getCurrentSession(); + + try { + LOGGER.info("Session created"); + + // start transaction + Transaction tx = session.beginTransaction(); + + // Save the Model object + session.save(cart); + session.save(cart2); + session.save(item1); + session.save(item2); + + // Commit transaction + tx.commit(); + + session = sessionFactory.getCurrentSession(); + tx = session.beginTransaction(); + + item1 = session.get(Item.class, 1L); + item2 = session.get(Item.class, 2L); + tx.commit(); + + LOGGER.info("item1 ID={}, Foreign Key CartOIO ID={}", item1.getId(), item1.getCart().getId()); + LOGGER.info("item2 ID={}, Foreign Key CartOIO ID={}", item2.getId(), item2.getCart().getId()); + + } catch (Exception e) { + LOGGER.error("Exception occurred", e); + } finally { + if (!sessionFactory.isClosed()) { + LOGGER.info("Closing SessionFactory"); + sessionFactory.close(); + } + } + } +} diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateManyisOwningSide.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateManyisOwningSide.java deleted file mode 100644 index 372fb2fc07..0000000000 --- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateManyisOwningSide.java +++ /dev/null @@ -1,71 +0,0 @@ -package com.baeldung.hibernate.oneToMany.main; - -import java.util.HashSet; -import java.util.Set; - -import org.hibernate.Session; -import org.hibernate.SessionFactory; -import org.hibernate.Transaction; - -import com.baeldung.hibernate.oneToMany.config.HibernateAnnotationUtil; -import com.baeldung.hibernate.oneToMany.model.Cart; -import com.baeldung.hibernate.oneToMany.model.Items; -import com.baeldung.hibernate.oneToMany.model.ItemsOIO; - -public class HibernateManyisOwningSide { - public static void main(String[] args) { - - Cart cart = new Cart(); - Cart cart2 = new Cart(); - - Items item1 = new Items(cart); - Items item2 = new Items(cart2); - Set itemsSet = new HashSet(); - itemsSet.add(item1); - itemsSet.add(item2); - - cart.setItems(itemsSet); - - - - SessionFactory sessionFactory = null; - Session session = null; - Transaction tx = null; - try { - // Get Session - sessionFactory = HibernateAnnotationUtil.getSessionFactory(); - session = sessionFactory.getCurrentSession(); - System.out.println("Session created"); - // start transaction - tx = session.beginTransaction(); - // Save the Model object - session.save(cart); - session.save(cart2); - session.save(item1); - session.save(item2); - // Commit transaction - tx.commit(); - session = sessionFactory.getCurrentSession(); - tx = session.beginTransaction(); - - item1 = (Items) session.get(Items.class, new Long(1)); - item2 = (Items) session.get(Items.class, new Long(2)); - tx.commit(); - - - System.out.println("item1 ID=" + item1.getId() + ", Foreign Key CartOIO ID=" + item1.getCart() - .getId()); - System.out.println("item2 ID=" + item2.getId() + ", Foreign Key CartOIO ID=" + item2.getCart() - .getId()); - - } catch (Exception e) { - System.out.println("Exception occured. " + e.getMessage()); - e.printStackTrace(); - } finally { - if (!sessionFactory.isClosed()) { - System.out.println("Closing SessionFactory"); - sessionFactory.close(); - } - } - } -} diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneisOwningSide.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneIsOwningSide.java similarity index 50% rename from persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneisOwningSide.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneIsOwningSide.java index 0777664dd0..086e015ad1 100644 --- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneisOwningSide.java +++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneIsOwningSide.java @@ -9,57 +9,59 @@ import org.hibernate.Transaction; import com.baeldung.hibernate.oneToMany.config.HibernateAnnotationUtil; import com.baeldung.hibernate.oneToMany.model.CartOIO; -import com.baeldung.hibernate.oneToMany.model.ItemsOIO; +import com.baeldung.hibernate.oneToMany.model.ItemOIO; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class HibernateOneIsOwningSide { + + private static final Logger LOGGER = LoggerFactory.getLogger(HibernateOneIsOwningSide.class); -public class HibernateOneisOwningSide { public static void main(String[] args) { CartOIO cart = new CartOIO(); CartOIO cart2 = new CartOIO(); - ItemsOIO item1 = new ItemsOIO(cart); - ItemsOIO item2 = new ItemsOIO(cart2); - Set itemsSet = new HashSet(); + ItemOIO item1 = new ItemOIO(cart); + ItemOIO item2 = new ItemOIO(cart2); + Set itemsSet = new HashSet<>(); itemsSet.add(item1); itemsSet.add(item2); cart.setItems(itemsSet); - SessionFactory sessionFactory = null; - Session session = null; - Transaction tx = null; + SessionFactory sessionFactory = HibernateAnnotationUtil.getSessionFactory(); + Session session = sessionFactory.getCurrentSession(); + LOGGER.info("Session created"); + + Transaction tx; try { - // Get Session - sessionFactory = HibernateAnnotationUtil.getSessionFactory(); - session = sessionFactory.getCurrentSession(); - System.out.println("Session created"); // start transaction tx = session.beginTransaction(); + // Save the Model object session.save(cart); session.save(cart2); session.save(item1); session.save(item2); + // Commit transaction tx.commit(); session = sessionFactory.getCurrentSession(); tx = session.beginTransaction(); - item1 = (ItemsOIO) session.get(ItemsOIO.class, new Long(1)); - item2 = (ItemsOIO) session.get(ItemsOIO.class, new Long(2)); + item1 = session.get(ItemOIO.class, 1L); + item2 = session.get(ItemOIO.class, 2L); tx.commit(); - System.out.println("item1 ID=" + item1.getId() + ", Foreign Key CartOIO ID=" + item1.getCartOIO() - .getId()); - System.out.println("item2 ID=" + item2.getId() + ", Foreign Key CartOIO ID=" + item2.getCartOIO() - .getId()); + LOGGER.info("item1 ID={}, Foreign Key CartOIO ID={}", item1.getId(), item1.getCartOIO().getId()); + LOGGER.info("item2 ID={}, Foreign Key CartOIO ID={}", item2.getId(), item2.getCartOIO().getId()); } catch (Exception e) { - System.out.println("Exception occured. " + e.getMessage()); - e.printStackTrace(); + LOGGER.error("Exception occurred", e); } finally { if (!sessionFactory.isClosed()) { - System.out.println("Closing SessionFactory"); + LOGGER.info("Closing SessionFactory"); sessionFactory.close(); } } diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMain.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMain.java index 2bc5e514f7..99df67b4a8 100644 --- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMain.java +++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMain.java @@ -9,52 +9,53 @@ import org.hibernate.Transaction; import com.baeldung.hibernate.oneToMany.config.HibernateAnnotationUtil; import com.baeldung.hibernate.oneToMany.model.Cart; -import com.baeldung.hibernate.oneToMany.model.Items; +import com.baeldung.hibernate.oneToMany.model.Item; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class HibernateOneToManyAnnotationMain { + private static final Logger LOGGER = LoggerFactory.getLogger(HibernateOneToManyAnnotationMain.class); + public static void main(String[] args) { Cart cart = new Cart(); - Items item1 = new Items(cart); - Items item2 = new Items(cart); - Set itemsSet = new HashSet(); + Item item1 = new Item(cart); + Item item2 = new Item(cart); + Set itemsSet = new HashSet<>(); itemsSet.add(item1); itemsSet.add(item2); cart.setItems(itemsSet); - - SessionFactory sessionFactory = null; - Session session = null; - Transaction tx = null; + SessionFactory sessionFactory = HibernateAnnotationUtil.getSessionFactory(); + Session session = sessionFactory.getCurrentSession(); + LOGGER.info("Session created"); + try { - // Get Session - sessionFactory = HibernateAnnotationUtil.getSessionFactory(); - session = sessionFactory.getCurrentSession(); - System.out.println("Session created"); // start transaction - tx = session.beginTransaction(); + Transaction tx = session.beginTransaction(); + // Save the Model object session.save(cart); session.save(item1); session.save(item2); + // Commit transaction tx.commit(); - System.out.println("Cart ID=" + cart.getId()); - System.out.println("item1 ID=" + item1.getId() + ", Foreign Key Cart ID=" + item1.getCart().getId()); - System.out.println("item2 ID=" + item2.getId() + ", Foreign Key Cart ID=" + item1.getCart().getId()); + + LOGGER.info("Cart ID={}", cart.getId()); + LOGGER.info("item1 ID={}, Foreign Key Cart ID={}", item1.getId(), item1.getCart().getId()); + LOGGER.info("item2 ID={}, Foreign Key Cart ID={}", item2.getId(), item2.getCart().getId()); } catch (Exception e) { - System.out.println("Exception occured. " + e.getMessage()); - e.printStackTrace(); + LOGGER.error("Exception occurred", e); } finally { if (!sessionFactory.isClosed()) { - System.out.println("Closing SessionFactory"); + LOGGER.info("Closing SessionFactory"); sessionFactory.close(); } } } - } diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/Cart.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/Cart.java index b8b991831e..53878af445 100644 --- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/Cart.java +++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/Cart.java @@ -19,9 +19,8 @@ public class Cart { @Column(name = "cart_id") private long id; - @OneToMany(mappedBy = "cart") - private Set items; + private Set items; public long getId() { return id; @@ -31,12 +30,11 @@ public class Cart { this.id = id; } - - public Set getItems() { + public Set getItems() { return items; } - public void setItems(Set items) { + public void setItems(Set items) { this.items = items; } diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/CartOIO.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/CartOIO.java index 8a5ed5e7a4..27b28a6753 100644 --- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/CartOIO.java +++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/CartOIO.java @@ -9,8 +9,6 @@ import javax.persistence.JoinColumn; import javax.persistence.OneToMany; import javax.persistence.Table; - - @Entity @Table(name = "CARTOIO") public class CartOIO { @@ -21,7 +19,7 @@ public class CartOIO { @OneToMany @JoinColumn(name = "cart_id") // we need to duplicate the physical information - private Set items; + private Set items; public long getId() { return id; @@ -31,11 +29,11 @@ public class CartOIO { this.id = id; } - public Set getItems() { + public Set getItems() { return items; } - public void setItems(Set items) { + public void setItems(Set items) { this.items = items; } diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/Items.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/Item.java similarity index 92% rename from persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/Items.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/Item.java index f63a4855b5..a055682d0d 100644 --- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/Items.java +++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/Item.java @@ -11,23 +11,22 @@ import javax.persistence.Table; @Entity @Table(name = "ITEMS") -public class Items { +public class Item { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") private long id; - @ManyToOne @JoinColumn(name = "cart_id", nullable = false) private Cart cart; // Hibernate requires no-args constructor - public Items() { + public Item() { } - public Items(Cart c) { + public Item(Cart c) { this.cart = c; } diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/ItemsOIO.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/ItemOIO.java similarity index 91% rename from persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/ItemsOIO.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/ItemOIO.java index a3d6a796c5..baaf57b106 100644 --- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/ItemsOIO.java +++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/ItemOIO.java @@ -10,7 +10,7 @@ import javax.persistence.Table; @Entity @Table(name = "ITEMSOIO") -public class ItemsOIO { +public class ItemOIO { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @@ -21,10 +21,10 @@ public class ItemsOIO { private CartOIO cart; // Hibernate requires no-args constructor - public ItemsOIO() { + public ItemOIO() { } - public ItemsOIO(CartOIO c) { + public ItemOIO(CartOIO c) { this.cart = c; } diff --git a/persistence-modules/hibernate-annotations/src/main/resources/hibernate-annotation.cfg.xml b/persistence-modules/hibernate-annotations/src/main/resources/hibernate-annotation.cfg.xml new file mode 100644 index 0000000000..6e845b3781 --- /dev/null +++ b/persistence-modules/hibernate-annotations/src/main/resources/hibernate-annotation.cfg.xml @@ -0,0 +1,18 @@ + + + + + + org.h2.Driver + sa + + jdbc:h2:mem:spring_hibernate_one_to_many + + org.hibernate.dialect.H2Dialect + thread + true + create + + diff --git a/persistence-modules/hibernate-annotations/src/main/resources/log4j.xml b/persistence-modules/hibernate-annotations/src/main/resources/log4j.xml new file mode 100644 index 0000000000..bc2c24ea93 --- /dev/null +++ b/persistence-modules/hibernate-annotations/src/main/resources/log4j.xml @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMainIntegrationTest.java b/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMainIntegrationTest.java index 3bc5a6e12a..cb11df4212 100644 --- a/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMainIntegrationTest.java +++ b/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMainIntegrationTest.java @@ -1,26 +1,21 @@ package com.baeldung.hibernate.oneToMany.main; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; - -import java.util.HashSet; -import java.util.Set; - +import com.baeldung.hibernate.oneToMany.config.HibernateAnnotationUtil; +import com.baeldung.hibernate.oneToMany.model.Cart; +import com.baeldung.hibernate.oneToMany.model.Item; import org.hibernate.Session; import org.hibernate.SessionFactory; -import org.hibernate.boot.registry.StandardServiceRegistryBuilder; -import org.hibernate.cfg.Configuration; -import org.hibernate.dialect.H2Dialect; -import org.hibernate.service.ServiceRegistry; import org.junit.After; import org.junit.AfterClass; -import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; -import com.baeldung.hibernate.oneToMany.model.Cart; -import com.baeldung.hibernate.oneToMany.model.Items; +import java.util.HashSet; +import java.util.Set; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; public class HibernateOneToManyAnnotationMainIntegrationTest { @@ -28,20 +23,9 @@ public class HibernateOneToManyAnnotationMainIntegrationTest { private Session session; - public HibernateOneToManyAnnotationMainIntegrationTest() { - } - @BeforeClass public static void beforeTests() { - Configuration configuration = new Configuration().addAnnotatedClass(Cart.class).addAnnotatedClass(Items.class) - .setProperty("hibernate.dialect", H2Dialect.class.getName()) - .setProperty("hibernate.connection.driver_class", org.h2.Driver.class.getName()) - .setProperty("hibernate.connection.url", "jdbc:h2:mem:test") - .setProperty("hibernate.connection.username", "sa").setProperty("hibernate.connection.password", "") - .setProperty("hibernate.hbm2ddl.auto", "update"); - ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() - .applySettings(configuration.getProperties()).build(); - sessionFactory = configuration.buildSessionFactory(serviceRegistry); + sessionFactory = HibernateAnnotationUtil.getSessionFactory(); } @Before @@ -52,32 +36,38 @@ public class HibernateOneToManyAnnotationMainIntegrationTest { @Test public void givenSession_checkIfDatabaseIsEmpty() { - Cart cart = (Cart) session.get(Cart.class, new Long(1)); + Cart cart = session.get(Cart.class, 1L); assertNull(cart); - } @Test public void givenSession_checkIfDatabaseIsPopulated_afterCommit() { Cart cart = new Cart(); - Set cartItems = new HashSet<>(); - cartItems = cart.getItems(); - Assert.assertNull(cartItems); - Items item1 = new Items(); + Set cartItems = cart.getItems(); + + assertNull(cartItems); + + Item item1 = new Item(); item1.setCart(cart); + assertNotNull(item1); - Set itemsSet = new HashSet(); - itemsSet.add(item1); - assertNotNull(itemsSet); - cart.setItems(itemsSet); + + Set itemSet = new HashSet<>(); + itemSet.add(item1); + + assertNotNull(itemSet); + cart.setItems(itemSet); + assertNotNull(cart); + session.persist(cart); session.getTransaction().commit(); session.close(); session = sessionFactory.openSession(); session.beginTransaction(); - cart = (Cart) session.get(Cart.class, new Long(1)); + cart = session.get(Cart.class, 1L); + assertNotNull(cart); } diff --git a/persistence-modules/hibernate-annotations/src/test/resources/log4j.xml b/persistence-modules/hibernate-annotations/src/test/resources/log4j.xml index 7e2895f1e0..bc2c24ea93 100644 --- a/persistence-modules/hibernate-annotations/src/test/resources/log4j.xml +++ b/persistence-modules/hibernate-annotations/src/test/resources/log4j.xml @@ -1,24 +1,31 @@ - + + + + + - + + + - \ No newline at end of file + + \ No newline at end of file diff --git a/persistence-modules/hibernate-annotations/src/test/resources/profile.png b/persistence-modules/hibernate-annotations/src/test/resources/profile.png deleted file mode 100644 index 1cd4e978b9..0000000000 Binary files a/persistence-modules/hibernate-annotations/src/test/resources/profile.png and /dev/null differ diff --git a/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/persistentobject/HibernateUtil.java b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/persistentobject/HibernateUtil.java new file mode 100644 index 0000000000..641b80b412 --- /dev/null +++ b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/persistentobject/HibernateUtil.java @@ -0,0 +1,47 @@ +package com.baeldung.hibernate.exception.persistentobject; + +import java.util.Properties; + +import org.hibernate.SessionFactory; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.cfg.Configuration; +import org.hibernate.cfg.Environment; +import org.hibernate.service.ServiceRegistry; + +import com.baeldung.hibernate.exception.persistentobject.entity.Article; +import com.baeldung.hibernate.exception.persistentobject.entity.Author; +import com.baeldung.hibernate.exception.persistentobject.entity.Book; + +public class HibernateUtil { + private static SessionFactory sessionFactory; + + public static SessionFactory getSessionFactory() { + if (sessionFactory == null) { + try { + Configuration configuration = new Configuration(); + Properties settings = new Properties(); + + settings.put(Environment.DRIVER, "org.hsqldb.jdbcDriver"); + settings.put(Environment.URL, "jdbc:hsqldb:mem:userrole"); + settings.put(Environment.USER, "sa"); + settings.put(Environment.PASS, ""); + settings.put(Environment.DIALECT, "org.hibernate.dialect.HSQLDialect"); + settings.put(Environment.SHOW_SQL, "true"); + settings.put(Environment.HBM2DDL_AUTO, "update"); + settings.put(Environment.CHECK_NULLABILITY, "true"); + + configuration.setProperties(settings); + configuration.addAnnotatedClass(Book.class); + configuration.addAnnotatedClass(Author.class); + configuration.addAnnotatedClass(Article.class); + + ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() + .applySettings(configuration.getProperties()).build(); + sessionFactory = configuration.buildSessionFactory(serviceRegistry); + } catch (Exception e) { + e.printStackTrace(); + } + } + return sessionFactory; + } +} \ No newline at end of file diff --git a/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/persistentobject/entity/Article.java b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/persistentobject/entity/Article.java new file mode 100644 index 0000000000..3c9c7c5b31 --- /dev/null +++ b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/persistentobject/entity/Article.java @@ -0,0 +1,29 @@ +package com.baeldung.hibernate.exception.persistentobject.entity; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.ManyToOne; + +@Entity +public class Article { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private long id; + + private String title; + + @ManyToOne(optional = false) + private Author author; + + public Article(String title) { + this.title = title; + } + + public void setAuthor(Author author) { + this.author = author; + } + +} diff --git a/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/persistentobject/entity/Author.java b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/persistentobject/entity/Author.java new file mode 100644 index 0000000000..fa6aaa9abe --- /dev/null +++ b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/persistentobject/entity/Author.java @@ -0,0 +1,48 @@ +package com.baeldung.hibernate.exception.persistentobject.entity; + +import java.util.List; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.OneToMany; +import javax.persistence.OneToOne; + +import org.hibernate.annotations.Cascade; +import org.hibernate.annotations.CascadeType; + +@Entity +public class Author { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private long id; + + private String name; + + @OneToMany + @Cascade(CascadeType.ALL) + private List
articles; + + public Author(String name) { + this.name = name; + } + + public Author() { + } + + public List
getArticles() { + return articles; + } + + public void setArticles(List
articles) { + this.articles = articles; + } + + public void addArticles(List
articles) { + this.articles = articles; + articles.forEach(article -> article.setAuthor(this)); + } + +} diff --git a/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/persistentobject/entity/Book.java b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/persistentobject/entity/Book.java new file mode 100644 index 0000000000..342da27c77 --- /dev/null +++ b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/persistentobject/entity/Book.java @@ -0,0 +1,34 @@ +package com.baeldung.hibernate.exception.persistentobject.entity; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; + +@Entity +public class Book { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + + @Column(nullable = false) + private String title; + + public Book(String title) { + this.title = title; + } + + public Book() { + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } +} diff --git a/persistence-modules/hibernate-exceptions/src/test/java/com/baeldung/hibernate/exception/persistentobject/HibernatePersistentObjectUnitTest.java b/persistence-modules/hibernate-exceptions/src/test/java/com/baeldung/hibernate/exception/persistentobject/HibernatePersistentObjectUnitTest.java new file mode 100644 index 0000000000..09f11b07a2 --- /dev/null +++ b/persistence-modules/hibernate-exceptions/src/test/java/com/baeldung/hibernate/exception/persistentobject/HibernatePersistentObjectUnitTest.java @@ -0,0 +1,65 @@ +package com.baeldung.hibernate.exception.persistentobject; + +import static java.util.Arrays.asList; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import org.hibernate.PropertyValueException; +import org.hibernate.Session; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import com.baeldung.hibernate.exception.persistentobject.entity.Article; +import com.baeldung.hibernate.exception.persistentobject.entity.Author; +import com.baeldung.hibernate.exception.persistentobject.entity.Book; + +public class HibernatePersistentObjectUnitTest { + + private static Session session; + + @Before + public void beforeAll() { + session = HibernateUtil.getSessionFactory() + .openSession(); + session.beginTransaction(); + } + + @After + public void afterAll() { + session.close(); + } + + @Test + public void whenSavingEntityWithNullMandatoryField_thenThrowPropertyValueException() { + Book book = new Book(); + + assertThatThrownBy(() -> session.save(book)).isInstanceOf(PropertyValueException.class) + .hasMessageContaining("not-null property references a null or transient value"); + } + + @Test + public void whenSavingEntityWithAllMandatoryField_thenDoNotThrowException() { + Book book = new Book(); + book.setTitle("Clean Code"); + + session.save(book); + } + + @Test + public void whenSavingBidirectionalEntitiesWithoutSettingParent_thenThrowPropertyValueException() { + Author author = new Author("John Doe"); + author.setArticles(asList(new Article("Java Tutorial"), new Article("What's New in JUnit5"))); + + assertThatThrownBy(() -> session.save(author)).isInstanceOf(PropertyValueException.class) + .hasMessageContaining("not-null property references a null or transient value"); + } + + @Test + public void whenSavingBidirectionalEntitiesWithCorrectParent_thenDoNotThrowException() { + Author author = new Author("John Doe"); + author.addArticles(asList(new Article("Java tutorial"), new Article("What's new in JUnit5"))); + + session.save(author); + } + +} \ No newline at end of file diff --git a/persistence-modules/hibernate-queries/README.md b/persistence-modules/hibernate-queries/README.md index f1bc1cba0f..ac52e73abf 100644 --- a/persistence-modules/hibernate-queries/README.md +++ b/persistence-modules/hibernate-queries/README.md @@ -10,3 +10,4 @@ This module contains articles about use of Queries in Hibernate. - [Hibernate Named Query](https://www.baeldung.com/hibernate-named-query) - [Hibernate Query Plan Cache](https://www.baeldung.com/hibernate-query-plan-cache) - [Hibernate’s addScalar() Method](https://www.baeldung.com/hibernate-addscalar) +- [Distinct Queries in HQL](https://www.baeldung.com/java-hql-distinct) diff --git a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/HibernateUtil.java b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/HibernateUtil.java index 58724e690c..84b20197bd 100644 --- a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/HibernateUtil.java +++ b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/HibernateUtil.java @@ -13,6 +13,8 @@ import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.service.ServiceRegistry; import com.baeldung.hibernate.customtypes.LocalDateStringType; +import com.baeldung.hibernate.distinct.entities.Post; +import com.baeldung.hibernate.distinct.entities.Comment; import com.baeldung.hibernate.entities.DeptEmployee; import com.baeldung.hibernate.pojo.Student; @@ -41,6 +43,8 @@ public class HibernateUtil { metadataSources.addAnnotatedClass(Student.class); metadataSources.addAnnotatedClass(DeptEmployee.class); metadataSources.addAnnotatedClass(com.baeldung.hibernate.entities.Department.class); + metadataSources.addAnnotatedClass(Comment.class); + metadataSources.addAnnotatedClass(Post.class); Metadata metadata = metadataSources.getMetadataBuilder() .applyBasicType(LocalDateStringType.INSTANCE) diff --git a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/distinct/entities/Comment.java b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/distinct/entities/Comment.java new file mode 100644 index 0000000000..1d155b112e --- /dev/null +++ b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/distinct/entities/Comment.java @@ -0,0 +1,28 @@ +package com.baeldung.hibernate.distinct.entities; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class Comment { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private long id; + + private String text; + + public Comment() { + } + + public Comment(String text) { + this.text = text; + } + + @Override + public String toString() { + return "Comment{" + "id=" + id + ", text='" + text + '\'' + '}'; + } +} diff --git a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/distinct/entities/Post.java b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/distinct/entities/Post.java new file mode 100644 index 0000000000..d2608e614c --- /dev/null +++ b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/distinct/entities/Post.java @@ -0,0 +1,59 @@ +package com.baeldung.hibernate.distinct.entities; + +import java.util.List; + +import javax.persistence.Entity; +import javax.persistence.FetchType; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.OneToMany; + +import org.hibernate.annotations.Cascade; +import org.hibernate.annotations.CascadeType; + +@Entity +public class Post { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private long id; + + private String title; + + @OneToMany + @Cascade(CascadeType.ALL) + private List comments; + + public Post() { + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public List getComments() { + return comments; + } + + public void setComments(List comments) { + this.comments = comments; + } + + @Override + public String toString() { + return "Post{" + "id=" + id + ", title='" + title + '\'' + ", comments=" + comments + '}'; + } +} diff --git a/persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/distinct/entities/DistinctHqlQueriesUnitTest.java b/persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/distinct/entities/DistinctHqlQueriesUnitTest.java new file mode 100644 index 0000000000..799439a51b --- /dev/null +++ b/persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/distinct/entities/DistinctHqlQueriesUnitTest.java @@ -0,0 +1,80 @@ +package com.baeldung.hibernate.distinct.entities; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.IOException; +import java.util.Arrays; +import java.util.List; + +import org.hibernate.Session; +import org.hibernate.Transaction; +import org.hibernate.annotations.QueryHints; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import com.baeldung.hibernate.HibernateUtil; + +public class DistinctHqlQueriesUnitTest { + + private Session session; + + @Before + public void setUp() throws IOException { + this.session = HibernateUtil.getSessionFactory() + .openSession(); + saveDummyData(); + } + + private void saveDummyData() { + Transaction trx = session.beginTransaction(); + session.createQuery("delete from Post") + .executeUpdate(); + + Post post = new Post(); + post.setTitle("Distinct Queries in HQL"); + post.setComments(Arrays.asList(new Comment("Great article!"), new Comment("Nice one :)"), new Comment("Keep up the good work!"))); + session.persist(post); + + trx.commit(); + } + + @After + public void tearDown() { + session.close(); + } + + @Test + public void whenExecutingSelectQuery_thereWillBeDuplicates() { + String hql = "SELECT p FROM Post p LEFT JOIN FETCH p.comments"; + List posts = session.createQuery(hql, Post.class) + .getResultList(); + + assertThat(posts).hasSize(3); + } + + @Test + public void whenExecutingSelectDistinctQuery_thereShouldBeNoDuplicates() { + String hql = "SELECT DISTINCT p FROM Post p LEFT JOIN FETCH p.comments"; + List posts = session.createQuery(hql, Post.class) + .getResultList(); + + assertThat(posts).hasSize(1) + .allMatch(post -> post.getTitle() + .equals("Distinct Queries in HQL") && post.getComments() + .size() == 3); + } + + @Test + public void whenExecutingSelectDistinctQueryWithHint_thereShouldBeNoDuplicates() { + String hql = "SELECT DISTINCT p FROM Post p LEFT JOIN FETCH p.comments"; + List posts = session.createQuery(hql, Post.class) + .setHint(QueryHints.PASS_DISTINCT_THROUGH, false) + .getResultList(); + + assertThat(posts).hasSize(1) + .allMatch(post -> post.getTitle() + .equals("Distinct Queries in HQL") && post.getComments() + .size() == 3); + } +} \ No newline at end of file diff --git a/persistence-modules/java-mongodb-2/src/main/java/com/baeldung/mongo/ConnectionCheck.java b/persistence-modules/java-mongodb-2/src/main/java/com/baeldung/mongo/ConnectionCheck.java new file mode 100644 index 0000000000..240e54ab99 --- /dev/null +++ b/persistence-modules/java-mongodb-2/src/main/java/com/baeldung/mongo/ConnectionCheck.java @@ -0,0 +1,46 @@ +package com.baeldung; + +import com.mongodb.DB; +import com.mongodb.MongoClient; +import com.mongodb.MongoClientOptions; +import com.mongodb.ServerAddress; + +public class ConnectionCheck { + + public static void checkingConnection() { + + MongoClientOptions.Builder builder = MongoClientOptions.builder(); + + builder.connectionsPerHost(100); + builder.maxWaitTime(60000); + builder.connectTimeout(1500); + builder.socketTimeout(60000); + builder.socketKeepAlive(true); + + ServerAddress ServerAddress = new ServerAddress("localhost", 27017); + MongoClient mongoClient = new MongoClient(ServerAddress, builder.build()); + + try { + System.out.println("MongoDB Server is Up:- " + mongoClient.getAddress()); + DB db = mongoClient.getDB("baeldung"); + System.out.println(mongoClient.getConnectPoint()); + System.out.println(db.getStats()); + } catch (Exception e) { + System.out.println("MongoDB Server is Down"); + mongoClient.close(); + } + + } + + public static void main(String[] args) { + + // + // Connection check + // + + checkingConnection(); + + } + +} + diff --git a/persistence-modules/java-mongodb-2/src/test/java/com/baeldung/mongo/ConnectionCheckLiveTest.java b/persistence-modules/java-mongodb-2/src/test/java/com/baeldung/mongo/ConnectionCheckLiveTest.java new file mode 100644 index 0000000000..69f356997c --- /dev/null +++ b/persistence-modules/java-mongodb-2/src/test/java/com/baeldung/mongo/ConnectionCheckLiveTest.java @@ -0,0 +1,47 @@ +package com.baeldung.mongo; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; + +import java.io.IOException; + +import org.junit.BeforeClass; +import org.junit.Test; + +import com.mongodb.MongoClient; +import com.mongodb.MongoClientOptions; +import com.mongodb.ServerAddress; + +public class ConnectionCheckLiveTest { + + private static MongoClient mongoClient; + private static MongoClientOptions.Builder builder; + private static ServerAddress ServerAddress; + + @BeforeClass + public static void setup() throws IOException { + if (mongoClient == null) { + + builder = MongoClientOptions.builder(); + builder.connectionsPerHost(100); + builder.maxWaitTime(60000); + builder.connectTimeout(1500); + builder.socketTimeout(60000); + builder.socketKeepAlive(true); + + ServerAddress = new ServerAddress("localhost", 27017); + mongoClient = new MongoClient(ServerAddress, builder.build()); + + } + } + + @Test + public void givenMongoClient_whenConnectionCheck_thenCheckingForConnectionPoint() { + + String connectionPoint = mongoClient.getConnectPoint(); + assertNotNull(connectionPoint); + assertFalse(connectionPoint.isEmpty()); + + } +} + diff --git a/persistence-modules/java-mongodb/src/test/java/com/baeldung/bsontojson/BsonToJsonLiveTest.java b/persistence-modules/java-mongodb/src/test/java/com/baeldung/bsontojson/BsonToJsonLiveTest.java index 12053523f8..0548119d7a 100644 --- a/persistence-modules/java-mongodb/src/test/java/com/baeldung/bsontojson/BsonToJsonLiveTest.java +++ b/persistence-modules/java-mongodb/src/test/java/com/baeldung/bsontojson/BsonToJsonLiveTest.java @@ -21,7 +21,7 @@ import dev.morphia.Datastore; import dev.morphia.Morphia; public class BsonToJsonLiveTest { - + private static final String DB_NAME = "library"; private static Datastore datastore; @@ -31,17 +31,17 @@ public class BsonToJsonLiveTest { morphia.mapPackage("com.baeldung.bsontojson"); datastore = morphia.createDatastore(new MongoClient(), DB_NAME); datastore.ensureIndexes(); - + datastore.save(new Book() .setIsbn("isbn") .setTitle("title") .setAuthor("author") .setCost(3.95) .setPublisher(new Publisher(new ObjectId("fffffffffffffffffffffffa"),"publisher")) - .setPublishDate(LocalDateTime.parse("2020-01-01T18:13:32Z", DateTimeFormatter.ISO_DATE_TIME)) + .setPublishDate(LocalDateTime.parse("2020-01-01T17:13:32Z", DateTimeFormatter.ISO_DATE_TIME)) .addCompanionBooks(new Book().setIsbn("isbn2"))); } - + @AfterClass public static void tearDown() { datastore.delete(datastore.createQuery(Book.class)); @@ -50,32 +50,32 @@ public class BsonToJsonLiveTest { @Test public void givenBsonDocument_whenUsingStandardJsonTransformation_thenJsonDateIsObjectEpochTime() { - String json = null; + String json; try (MongoClient mongoClient = new MongoClient()) { MongoDatabase mongoDatabase = mongoClient.getDatabase(DB_NAME); Document bson = mongoDatabase.getCollection("Books").find().first(); json = bson.toJson(); } - - String expectedJson = "{\"_id\": \"isbn\", " + - "\"className\": \"com.baeldung.bsontojson.Book\", " + - "\"title\": \"title\", " + - "\"author\": \"author\", " + - "\"publisher\": {\"_id\": {\"$oid\": \"fffffffffffffffffffffffa\"}, " + - "\"name\": \"publisher\"}, " + - "\"price\": 3.95, " + + + String expectedJson = "{\"_id\": \"isbn\", " + + "\"className\": \"com.baeldung.bsontojson.Book\", " + + "\"title\": \"title\", " + + "\"author\": \"author\", " + + "\"publisher\": {\"_id\": {\"$oid\": \"fffffffffffffffffffffffa\"}, " + + "\"name\": \"publisher\"}, " + + "\"price\": 3.95, " + "\"publishDate\": {\"$date\": 1577898812000}}"; assertNotNull(json); - + assertEquals(expectedJson, json); } - + @Test public void givenBsonDocument_whenUsingRelaxedJsonTransformation_thenJsonDateIsObjectIsoDate() { - - String json = null; + + String json; try (MongoClient mongoClient = new MongoClient()) { MongoDatabase mongoDatabase = mongoClient.getDatabase(DB_NAME); Document bson = mongoDatabase.getCollection("Books").find().first(); @@ -84,25 +84,25 @@ public class BsonToJsonLiveTest { .outputMode(JsonMode.RELAXED) .build()); } - - String expectedJson = "{\"_id\": \"isbn\", " + - "\"className\": \"com.baeldung.bsontojson.Book\", " + - "\"title\": \"title\", " + - "\"author\": \"author\", " + - "\"publisher\": {\"_id\": {\"$oid\": \"fffffffffffffffffffffffa\"}, " + - "\"name\": \"publisher\"}, " + - "\"price\": 3.95, " + + + String expectedJson = "{\"_id\": \"isbn\", " + + "\"className\": \"com.baeldung.bsontojson.Book\", " + + "\"title\": \"title\", " + + "\"author\": \"author\", " + + "\"publisher\": {\"_id\": {\"$oid\": \"fffffffffffffffffffffffa\"}, " + + "\"name\": \"publisher\"}, " + + "\"price\": 3.95, " + "\"publishDate\": {\"$date\": \"2020-01-01T17:13:32Z\"}}"; assertNotNull(json); - + assertEquals(expectedJson, json); } - + @Test public void givenBsonDocument_whenUsingCustomJsonTransformation_thenJsonDateIsStringField() { - String json = null; + String json; try (MongoClient mongoClient = new MongoClient()) { MongoDatabase mongoDatabase = mongoClient.getDatabase(DB_NAME); Document bson = mongoDatabase.getCollection("Books").find().first(); @@ -112,13 +112,13 @@ public class BsonToJsonLiveTest { .build()); } - String expectedJson = "{\"_id\": \"isbn\", " + - "\"className\": \"com.baeldung.bsontojson.Book\", " + - "\"title\": \"title\", " + - "\"author\": \"author\", " + - "\"publisher\": {\"_id\": {\"$oid\": \"fffffffffffffffffffffffa\"}, " + - "\"name\": \"publisher\"}, " + - "\"price\": 3.95, " + + String expectedJson = "{\"_id\": \"isbn\", " + + "\"className\": \"com.baeldung.bsontojson.Book\", " + + "\"title\": \"title\", " + + "\"author\": \"author\", " + + "\"publisher\": {\"_id\": {\"$oid\": \"fffffffffffffffffffffffa\"}, " + + "\"name\": \"publisher\"}, " + + "\"price\": 3.95, " + "\"publishDate\": \"2020-01-01T17:13:32Z\"}"; assertEquals(expectedJson, json); diff --git a/persistence-modules/spring-boot-persistence-mongodb/README.md b/persistence-modules/spring-boot-persistence-mongodb/README.md index 91dd8718e1..6659e82677 100644 --- a/persistence-modules/spring-boot-persistence-mongodb/README.md +++ b/persistence-modules/spring-boot-persistence-mongodb/README.md @@ -8,3 +8,4 @@ - [A Guide to @DBRef in MongoDB](https://www.baeldung.com/spring-mongodb-dbref-annotation) - [Import Data to MongoDB From JSON File Using Java](https://www.baeldung.com/java-import-json-mongodb) - [Logging MongoDB Queries with Spring Boot](https://www.baeldung.com/spring-boot-mongodb-logging) +- [Return Only Specific Fields for a Query in Spring Data MongoDB](https://www.baeldung.com/mongodb-return-specific-fields) diff --git a/pom.xml b/pom.xml index 441cf0e580..21589f5525 100644 --- a/pom.xml +++ b/pom.xml @@ -432,8 +432,6 @@ httpclient-simple hystrix - immutables - jackson-modules jackson-simple java-blockchain @@ -916,9 +914,7 @@ helidon httpclient httpclient-simple - hystrix - - immutables + hystrix jackson-modules jackson-simple diff --git a/reactor-core/src/test/java/com/baeldung/reactor/core/CombiningPublishersIntegrationTest.java b/reactor-core/src/test/java/com/baeldung/reactor/core/CombiningPublishersIntegrationTest.java index e6108759e1..4f37718814 100644 --- a/reactor-core/src/test/java/com/baeldung/reactor/core/CombiningPublishersIntegrationTest.java +++ b/reactor-core/src/test/java/com/baeldung/reactor/core/CombiningPublishersIntegrationTest.java @@ -18,8 +18,8 @@ public class CombiningPublishersIntegrationTest { @Test public void givenFluxes_whenMergeDelayErrorIsInvoked_thenMergeDelayError() { Flux fluxOfIntegers = Flux.mergeDelayError(1, - evenNumbers.delayElements(Duration.ofMillis(2000L)), - oddNumbers.delayElements(Duration.ofMillis(1000L))); + evenNumbers.delayElements(Duration.ofMillis(500L)), + oddNumbers.delayElements(Duration.ofMillis(300L))); StepVerifier.create(fluxOfIntegers) .expectNext(1) diff --git a/regexMatchesToArray/src/regex/array/RegexMatches.java b/regexMatchesToArray/src/regex/array/RegexMatches.java new file mode 100644 index 0000000000..d7b50d95ca --- /dev/null +++ b/regexMatchesToArray/src/regex/array/RegexMatches.java @@ -0,0 +1,24 @@ +package regex.array; + +import java.util.ArrayList; +import java.util.List; +import java.util.regex.*; + +class RegexMatches { + + String[] regexMatch(String strSearch) + { + List matchesList = new ArrayList(); + String stringToSearch = strSearch; + Pattern p1 = Pattern.compile("780{1}\\d{7}"); + Matcher m1 = p1.matcher(stringToSearch); + while (m1.find()) + { + matchesList.add(m1.group()); + } + int sizeOfNewArray = matchesList.size(); + String newArrayOfMatches[] = new String[sizeOfNewArray]; + matchesList.toArray(newArrayOfMatches); + return newArrayOfMatches; + } +} diff --git a/regexMatchesToArray/test/regex/array/RegexMatchesUnitTest.java b/regexMatchesToArray/test/regex/array/RegexMatchesUnitTest.java new file mode 100644 index 0000000000..3e8f23c4bb --- /dev/null +++ b/regexMatchesToArray/test/regex/array/RegexMatchesUnitTest.java @@ -0,0 +1,33 @@ +package regex.array; + +import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; + +import regex.array.RegexMatches; + +class RegexMatchesUnitTest { + + @Test + void whenFourNums_thenFourMatches() { + RegexMatches rm = new RegexMatches(); + String actual[] = rm.regexMatch("7801111211fsdafasdfa 7802222222 sadfsadfsda7803333333 sadfdasfasd 7804444444"); + + assertArrayEquals(new String[] {"7801111211", "7802222222", "7803333333", "7804444444"}, actual, "success"); + } + + @Test + void whenThreeNums_thenThreeMatches() { + RegexMatches rm = new RegexMatches(); + String actual[] = rm.regexMatch("7801111211fsdafasdfa 780222222 sadfsadfsda7803333333 sadfdasfasd 7804444444"); + + assertArrayEquals(new String[] {"7801111211", "7803333333", "7804444444"}, actual, "success"); + } + + @Test + void whenZeroNums_thenZeroMatches() { + RegexMatches rm = new RegexMatches(); + String actual[] = rm.regexMatch("78011111fsdafasdfa 780222222 sadfsadfsda78033333 sadfdasfasd 7804444"); + + assertArrayEquals(new String[] {}, actual, "success"); + } +} diff --git a/rule-engines/jess/pom.xml b/rule-engines/jess/pom.xml index f5db0374ef..be26d54a1e 100644 --- a/rule-engines/jess/pom.xml +++ b/rule-engines/jess/pom.xml @@ -7,18 +7,28 @@ jess 1.0-SNAPSHOT - jsr94 jsr94 1.1 + + + + + wso2 + Numerical Method's Maven Repository + http://dist.wso2.org/maven2/ + + + \ No newline at end of file diff --git a/spring-boot-modules/pom.xml b/spring-boot-modules/pom.xml index fabd54aa92..939add1147 100644 --- a/spring-boot-modules/pom.xml +++ b/spring-boot-modules/pom.xml @@ -16,8 +16,7 @@ ../parent-boot-2 - - spring-boot + spring-boot-1 spring-boot-2 spring-boot-admin @@ -56,6 +55,7 @@ spring-boot-mvc spring-boot-mvc-2 spring-boot-mvc-3 + spring-boot-mvc-4 spring-boot-mvc-birt spring-boot-mvc-jersey spring-boot-nashorn @@ -64,6 +64,7 @@ spring-boot-properties spring-boot-properties-2 spring-boot-properties-3 + spring-boot-properties-migrator-demo spring-boot-property-exp spring-boot-runtime spring-boot-runtime-2 diff --git a/spring-boot-modules/spring-boot/src/main/resources/templates/customer.html b/spring-boot-modules/spring-boot-1/src/main/resources/templates/customer.html similarity index 100% rename from spring-boot-modules/spring-boot/src/main/resources/templates/customer.html rename to spring-boot-modules/spring-boot-1/src/main/resources/templates/customer.html diff --git a/spring-boot-modules/spring-boot-basic-customization-2/README.md b/spring-boot-modules/spring-boot-basic-customization-2/README.md index 9488618ca5..bfd24a0475 100644 --- a/spring-boot-modules/spring-boot-basic-customization-2/README.md +++ b/spring-boot-modules/spring-boot-basic-customization-2/README.md @@ -8,3 +8,5 @@ This module contains articles about Spring Boot customization 2 - [XML Defined Beans in Spring Boot](https://www.baeldung.com/spring-boot-xml-beans) - [What Is OncePerRequestFilter?](https://www.baeldung.com/spring-onceperrequestfilter) - [Spring Boot Exit Codes](https://www.baeldung.com/spring-boot-exit-codes) + - [Guide to Spring Type Conversions](https://www.baeldung.com/spring-type-conversions) + - [Container Configuration in Spring Boot 2](https://www.baeldung.com/embeddedservletcontainercustomizer-configurableembeddedservletcontainer-spring-boot) \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-basic-customization-2/pom.xml b/spring-boot-modules/spring-boot-basic-customization-2/pom.xml index b615947de7..b537f43c23 100644 --- a/spring-boot-modules/spring-boot-basic-customization-2/pom.xml +++ b/spring-boot-modules/spring-boot-basic-customization-2/pom.xml @@ -19,10 +19,23 @@ org.springframework.boot spring-boot-starter-web + + org.springframework.boot + spring-boot-starter-data-jpa + + + com.h2database + h2 + org.springframework.boot spring-boot-starter-test + + com.google.guava + guava + ${guava.version} + \ No newline at end of file diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/rss/CustomContainer.java b/spring-boot-modules/spring-boot-basic-customization-2/src/main/java/com/baeldung/container/CustomContainer.java similarity index 93% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/rss/CustomContainer.java rename to spring-boot-modules/spring-boot-basic-customization-2/src/main/java/com/baeldung/container/CustomContainer.java index aaa3188010..6ebd4d5c62 100644 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/rss/CustomContainer.java +++ b/spring-boot-modules/spring-boot-basic-customization-2/src/main/java/com/baeldung/container/CustomContainer.java @@ -1,4 +1,4 @@ -package com.baeldung.rss; +package com.baeldung.container; import org.springframework.boot.web.server.WebServerFactoryCustomizer; import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory; diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/Application.java b/spring-boot-modules/spring-boot-basic-customization-2/src/main/java/com/baeldung/typeconversion/Application.java similarity index 91% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/Application.java rename to spring-boot-modules/spring-boot-basic-customization-2/src/main/java/com/baeldung/typeconversion/Application.java index cb0d0c1532..1313032bbe 100644 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/Application.java +++ b/spring-boot-modules/spring-boot-basic-customization-2/src/main/java/com/baeldung/typeconversion/Application.java @@ -1,4 +1,4 @@ -package com.baeldung.boot; +package com.baeldung.typeconversion; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/config/WebConfig.java b/spring-boot-modules/spring-boot-basic-customization-2/src/main/java/com/baeldung/typeconversion/config/WebConfig.java similarity index 67% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/config/WebConfig.java rename to spring-boot-modules/spring-boot-basic-customization-2/src/main/java/com/baeldung/typeconversion/config/WebConfig.java index b23c910a04..bad84edf88 100644 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/config/WebConfig.java +++ b/spring-boot-modules/spring-boot-basic-customization-2/src/main/java/com/baeldung/typeconversion/config/WebConfig.java @@ -1,12 +1,13 @@ -package com.baeldung.boot.config; +package com.baeldung.typeconversion.config; -import com.baeldung.boot.converter.StringToEmployeeConverter; -import com.baeldung.boot.converter.StringToEnumConverterFactory; -import com.baeldung.boot.converter.GenericBigDecimalConverter; import org.springframework.context.annotation.Configuration; import org.springframework.format.FormatterRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; +import com.baeldung.typeconversion.converter.GenericBigDecimalConverter; +import com.baeldung.typeconversion.converter.StringToEmployeeConverter; +import com.baeldung.typeconversion.converter.StringToEnumConverterFactory; + @Configuration public class WebConfig implements WebMvcConfigurer { diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/converter/GenericBigDecimalConverter.java b/spring-boot-modules/spring-boot-basic-customization-2/src/main/java/com/baeldung/typeconversion/converter/GenericBigDecimalConverter.java similarity index 96% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/converter/GenericBigDecimalConverter.java rename to spring-boot-modules/spring-boot-basic-customization-2/src/main/java/com/baeldung/typeconversion/converter/GenericBigDecimalConverter.java index fc73cfee5f..440ffba5ee 100644 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/converter/GenericBigDecimalConverter.java +++ b/spring-boot-modules/spring-boot-basic-customization-2/src/main/java/com/baeldung/typeconversion/converter/GenericBigDecimalConverter.java @@ -1,4 +1,4 @@ -package com.baeldung.boot.converter; +package com.baeldung.typeconversion.converter; import com.google.common.collect.ImmutableSet; import org.springframework.core.convert.TypeDescriptor; diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/converter/StringToEmployeeConverter.java b/spring-boot-modules/spring-boot-basic-customization-2/src/main/java/com/baeldung/typeconversion/converter/StringToEmployeeConverter.java similarity index 76% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/converter/StringToEmployeeConverter.java rename to spring-boot-modules/spring-boot-basic-customization-2/src/main/java/com/baeldung/typeconversion/converter/StringToEmployeeConverter.java index ac635532ea..9703ed2514 100644 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/converter/StringToEmployeeConverter.java +++ b/spring-boot-modules/spring-boot-basic-customization-2/src/main/java/com/baeldung/typeconversion/converter/StringToEmployeeConverter.java @@ -1,8 +1,8 @@ -package com.baeldung.boot.converter; +package com.baeldung.typeconversion.converter; import org.springframework.core.convert.converter.Converter; -import com.baeldung.toggle.Employee; +import com.baeldung.typeconversion.entity.Employee; public class StringToEmployeeConverter implements Converter { diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/converter/StringToEnumConverterFactory.java b/spring-boot-modules/spring-boot-basic-customization-2/src/main/java/com/baeldung/typeconversion/converter/StringToEnumConverterFactory.java similarity index 94% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/converter/StringToEnumConverterFactory.java rename to spring-boot-modules/spring-boot-basic-customization-2/src/main/java/com/baeldung/typeconversion/converter/StringToEnumConverterFactory.java index a2dce11a6a..dc15f83d6d 100644 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/converter/StringToEnumConverterFactory.java +++ b/spring-boot-modules/spring-boot-basic-customization-2/src/main/java/com/baeldung/typeconversion/converter/StringToEnumConverterFactory.java @@ -1,4 +1,4 @@ -package com.baeldung.boot.converter; +package com.baeldung.typeconversion.converter; import org.springframework.core.convert.converter.Converter; import org.springframework.core.convert.converter.ConverterFactory; diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/converter/controller/StringToEmployeeConverterController.java b/spring-boot-modules/spring-boot-basic-customization-2/src/main/java/com/baeldung/typeconversion/converter/controller/StringToEmployeeConverterController.java similarity index 81% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/converter/controller/StringToEmployeeConverterController.java rename to spring-boot-modules/spring-boot-basic-customization-2/src/main/java/com/baeldung/typeconversion/converter/controller/StringToEmployeeConverterController.java index 260b1c734b..5c3f93f346 100644 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/converter/controller/StringToEmployeeConverterController.java +++ b/spring-boot-modules/spring-boot-basic-customization-2/src/main/java/com/baeldung/typeconversion/converter/controller/StringToEmployeeConverterController.java @@ -1,11 +1,11 @@ -package com.baeldung.boot.converter.controller; +package com.baeldung.typeconversion.converter.controller; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; -import com.baeldung.toggle.Employee; +import com.baeldung.typeconversion.entity.Employee; @RestController public class StringToEmployeeConverterController { diff --git a/spring-boot-modules/spring-boot-basic-customization-2/src/main/java/com/baeldung/typeconversion/domain/Modes.java b/spring-boot-modules/spring-boot-basic-customization-2/src/main/java/com/baeldung/typeconversion/domain/Modes.java new file mode 100644 index 0000000000..d905faacac --- /dev/null +++ b/spring-boot-modules/spring-boot-basic-customization-2/src/main/java/com/baeldung/typeconversion/domain/Modes.java @@ -0,0 +1,6 @@ +package com.baeldung.typeconversion.domain; + +public enum Modes { + + ALPHA, BETA; +} diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/toggle/Employee.java b/spring-boot-modules/spring-boot-basic-customization-2/src/main/java/com/baeldung/typeconversion/entity/Employee.java similarity index 92% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/toggle/Employee.java rename to spring-boot-modules/spring-boot-basic-customization-2/src/main/java/com/baeldung/typeconversion/entity/Employee.java index 64a8b3ce5b..e1897de877 100644 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/toggle/Employee.java +++ b/spring-boot-modules/spring-boot-basic-customization-2/src/main/java/com/baeldung/typeconversion/entity/Employee.java @@ -1,4 +1,4 @@ -package com.baeldung.toggle; +package com.baeldung.typeconversion.entity; import javax.persistence.Entity; import javax.persistence.Id; diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/converter/CustomConverterIntegrationTest.java b/spring-boot-modules/spring-boot-basic-customization-2/src/test/java/com/baeldung/typeconversion/converter/CustomConverterIntegrationTest.java similarity index 90% rename from spring-boot-modules/spring-boot/src/test/java/com/baeldung/converter/CustomConverterIntegrationTest.java rename to spring-boot-modules/spring-boot-basic-customization-2/src/test/java/com/baeldung/typeconversion/converter/CustomConverterIntegrationTest.java index 4619964783..3e12e3c58d 100644 --- a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/converter/CustomConverterIntegrationTest.java +++ b/spring-boot-modules/spring-boot-basic-customization-2/src/test/java/com/baeldung/typeconversion/converter/CustomConverterIntegrationTest.java @@ -1,9 +1,9 @@ -package com.baeldung.converter; +package com.baeldung.typeconversion.converter; -import com.baeldung.toggle.Employee; +import com.baeldung.typeconversion.Application; +import com.baeldung.typeconversion.domain.Modes; +import com.baeldung.typeconversion.entity.Employee; -import com.baeldung.boot.Application; -import com.baeldung.boot.domain.Modes; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/converter/controller/StringToEmployeeConverterControllerIntegrationTest.java b/spring-boot-modules/spring-boot-basic-customization-2/src/test/java/com/baeldung/typeconversion/converter/controller/StringToEmployeeConverterControllerIntegrationTest.java similarity index 92% rename from spring-boot-modules/spring-boot/src/test/java/com/baeldung/converter/controller/StringToEmployeeConverterControllerIntegrationTest.java rename to spring-boot-modules/spring-boot-basic-customization-2/src/test/java/com/baeldung/typeconversion/converter/controller/StringToEmployeeConverterControllerIntegrationTest.java index 52dc542ebf..8632eebda3 100644 --- a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/converter/controller/StringToEmployeeConverterControllerIntegrationTest.java +++ b/spring-boot-modules/spring-boot-basic-customization-2/src/test/java/com/baeldung/typeconversion/converter/controller/StringToEmployeeConverterControllerIntegrationTest.java @@ -1,4 +1,4 @@ -package com.baeldung.converter.controller; +package com.baeldung.typeconversion.converter.controller; import org.junit.Test; import org.junit.runner.RunWith; @@ -8,14 +8,14 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; +import com.baeldung.typeconversion.Application; + import static org.hamcrest.CoreMatchers.is; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import com.baeldung.boot.Application; - @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK, classes = Application.class) @AutoConfigureMockMvc diff --git a/spring-boot-modules/spring-boot-crud/README.md b/spring-boot-modules/spring-boot-crud/README.md index 6b0032deb3..3d3d8f42d7 100644 --- a/spring-boot-modules/spring-boot-crud/README.md +++ b/spring-boot-modules/spring-boot-crud/README.md @@ -5,3 +5,4 @@ This module contains articles about Spring Boot CRUD Operations ### Relevant Articles: - [Spring Boot CRUD Application with Thymeleaf](https://www.baeldung.com/spring-boot-crud-thymeleaf) - [Using a Spring Boot Application as a Dependency](https://www.baeldung.com/spring-boot-dependency) +- [A Guide to Spring in Eclipse STS](https://www.baeldung.com/eclipse-sts-spring) \ No newline at end of file diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/DemoApplication.java b/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/demo/DemoApplication.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/DemoApplication.java rename to spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/demo/DemoApplication.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/components/FooService.java b/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/demo/components/FooService.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/components/FooService.java rename to spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/demo/components/FooService.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/exceptions/CommonException.java b/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/demo/exceptions/CommonException.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/exceptions/CommonException.java rename to spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/demo/exceptions/CommonException.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/exceptions/FooNotFoundException.java b/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/demo/exceptions/FooNotFoundException.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/exceptions/FooNotFoundException.java rename to spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/demo/exceptions/FooNotFoundException.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/model/Foo.java b/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/demo/model/Foo.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/model/Foo.java rename to spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/demo/model/Foo.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/repository/FooRepository.java b/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/demo/repository/FooRepository.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/repository/FooRepository.java rename to spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/demo/repository/FooRepository.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/service/FooController.java b/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/demo/service/FooController.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/service/FooController.java rename to spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/demo/service/FooController.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/session/exception/Application.java b/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/session/exception/Application.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/session/exception/Application.java rename to spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/session/exception/Application.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/session/exception/repository/FooRepository.java b/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/session/exception/repository/FooRepository.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/session/exception/repository/FooRepository.java rename to spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/session/exception/repository/FooRepository.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/session/exception/repository/FooRepositoryImpl.java b/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/session/exception/repository/FooRepositoryImpl.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/session/exception/repository/FooRepositoryImpl.java rename to spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/session/exception/repository/FooRepositoryImpl.java diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/boot/ApplicationIntegrationTest.java b/spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/boot/ApplicationIntegrationTest.java similarity index 99% rename from spring-boot-modules/spring-boot/src/test/java/com/baeldung/boot/ApplicationIntegrationTest.java rename to spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/boot/ApplicationIntegrationTest.java index 462291e0ac..88ff8c75f1 100644 --- a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/boot/ApplicationIntegrationTest.java +++ b/spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/boot/ApplicationIntegrationTest.java @@ -1,12 +1,13 @@ package com.baeldung.boot; -import com.baeldung.session.exception.Application; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; +import com.baeldung.session.exception.Application; + @RunWith(SpringRunner.class) @SpringBootTest(classes = Application.class) @TestPropertySource("classpath:exception.properties") diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/boot/repository/FooRepositoryIntegrationTest.java b/spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/boot/repository/FooRepositoryIntegrationTest.java similarity index 94% rename from spring-boot-modules/spring-boot/src/test/java/com/baeldung/boot/repository/FooRepositoryIntegrationTest.java rename to spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/boot/repository/FooRepositoryIntegrationTest.java index 1772739d20..9de1f56af0 100644 --- a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/boot/repository/FooRepositoryIntegrationTest.java +++ b/spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/boot/repository/FooRepositoryIntegrationTest.java @@ -1,6 +1,6 @@ package com.baeldung.boot.repository; -import com.baeldung.boot.DemoApplicationIntegrationTest; +import com.baeldung.demo.DemoApplicationIntegrationTest; import com.baeldung.demo.model.Foo; import com.baeldung.demo.repository.FooRepository; import org.junit.Before; diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/boot/repository/HibernateSessionIntegrationTest.java b/spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/boot/repository/HibernateSessionIntegrationTest.java similarity index 94% rename from spring-boot-modules/spring-boot/src/test/java/com/baeldung/boot/repository/HibernateSessionIntegrationTest.java rename to spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/boot/repository/HibernateSessionIntegrationTest.java index 2fe072bb67..63b4734cf0 100644 --- a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/boot/repository/HibernateSessionIntegrationTest.java +++ b/spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/boot/repository/HibernateSessionIntegrationTest.java @@ -1,6 +1,6 @@ package com.baeldung.boot.repository; -import com.baeldung.boot.DemoApplicationIntegrationTest; +import com.baeldung.demo.DemoApplicationIntegrationTest; import com.baeldung.demo.model.Foo; import com.baeldung.demo.repository.FooRepository; import org.junit.Test; diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/boot/repository/NoHibernateSessionIntegrationTest.java b/spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/boot/repository/NoHibernateSessionIntegrationTest.java similarity index 99% rename from spring-boot-modules/spring-boot/src/test/java/com/baeldung/boot/repository/NoHibernateSessionIntegrationTest.java rename to spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/boot/repository/NoHibernateSessionIntegrationTest.java index 2e3326e6b1..ae20b15cb3 100644 --- a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/boot/repository/NoHibernateSessionIntegrationTest.java +++ b/spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/boot/repository/NoHibernateSessionIntegrationTest.java @@ -3,6 +3,7 @@ package com.baeldung.boot.repository; import com.baeldung.boot.ApplicationIntegrationTest; import com.baeldung.demo.model.Foo; import com.baeldung.session.exception.repository.FooRepository; + import org.hibernate.HibernateException; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/boot/DemoApplicationIntegrationTest.java b/spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/demo/DemoApplicationIntegrationTest.java similarity index 95% rename from spring-boot-modules/spring-boot/src/test/java/com/baeldung/boot/DemoApplicationIntegrationTest.java rename to spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/demo/DemoApplicationIntegrationTest.java index aaf4f1f780..3d72ec0140 100644 --- a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/boot/DemoApplicationIntegrationTest.java +++ b/spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/demo/DemoApplicationIntegrationTest.java @@ -1,4 +1,4 @@ -package com.baeldung.boot; +package com.baeldung.demo; import com.baeldung.demo.DemoApplication; import org.junit.Test; diff --git a/spring-boot-modules/spring-boot/src/test/resources/exception-hibernate.properties b/spring-boot-modules/spring-boot-crud/src/test/resources/exception-hibernate.properties similarity index 100% rename from spring-boot-modules/spring-boot/src/test/resources/exception-hibernate.properties rename to spring-boot-modules/spring-boot-crud/src/test/resources/exception-hibernate.properties diff --git a/spring-boot-modules/spring-boot/src/test/resources/exception.properties b/spring-boot-modules/spring-boot-crud/src/test/resources/exception.properties similarity index 100% rename from spring-boot-modules/spring-boot/src/test/resources/exception.properties rename to spring-boot-modules/spring-boot-crud/src/test/resources/exception.properties diff --git a/spring-boot-modules/spring-boot-data-2/README.md b/spring-boot-modules/spring-boot-data-2/README.md index b99356492b..fd9d034f8a 100644 --- a/spring-boot-modules/spring-boot-data-2/README.md +++ b/spring-boot-modules/spring-boot-data-2/README.md @@ -4,3 +4,5 @@ - [Spring Boot: Customize the Jackson ObjectMapper](https://www.baeldung.com/spring-boot-customize-jackson-objectmapper) - [“HttpMessageNotWritableException: No converter found for return value of type”](https://www.baeldung.com/spring-no-converter-found) - [Creating a Read-Only Repository with Spring Data](https://www.baeldung.com/spring-data-read-only-repository) +- [Using JaVers for Data Model Auditing in Spring Data](https://www.baeldung.com/spring-data-javers-audit) +- [BootstrapMode for JPA Repositories](https://github.com/eugenp/tutorials/tree/master/spring-boot-modules/spring-boot-data-2) diff --git a/spring-boot-modules/spring-boot-data-2/pom.xml b/spring-boot-modules/spring-boot-data-2/pom.xml index a3c2430497..ea5de6d4b5 100644 --- a/spring-boot-modules/spring-boot-data-2/pom.xml +++ b/spring-boot-modules/spring-boot-data-2/pom.xml @@ -20,11 +20,20 @@ org.springframework.boot spring-boot-starter-data-jpa + + org.javers + javers-spring-boot-starter-sql + ${javers.version} + com.h2database h2 runtime + + + 6.5.3 + \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/javers/SpringBootJaVersApplication.java b/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/javers/SpringBootJaVersApplication.java similarity index 100% rename from spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/javers/SpringBootJaVersApplication.java rename to spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/javers/SpringBootJaVersApplication.java diff --git a/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/javers/config/JaversConfiguration.java b/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/javers/config/JaversConfiguration.java similarity index 100% rename from spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/javers/config/JaversConfiguration.java rename to spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/javers/config/JaversConfiguration.java diff --git a/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/javers/domain/Address.java b/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/javers/domain/Address.java similarity index 100% rename from spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/javers/domain/Address.java rename to spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/javers/domain/Address.java diff --git a/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/javers/domain/Product.java b/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/javers/domain/Product.java similarity index 100% rename from spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/javers/domain/Product.java rename to spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/javers/domain/Product.java diff --git a/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/javers/domain/Store.java b/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/javers/domain/Store.java similarity index 100% rename from spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/javers/domain/Store.java rename to spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/javers/domain/Store.java diff --git a/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/javers/repo/ProductRepository.java b/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/javers/repo/ProductRepository.java similarity index 100% rename from spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/javers/repo/ProductRepository.java rename to spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/javers/repo/ProductRepository.java diff --git a/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/javers/repo/StoreRepository.java b/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/javers/repo/StoreRepository.java similarity index 100% rename from spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/javers/repo/StoreRepository.java rename to spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/javers/repo/StoreRepository.java diff --git a/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/javers/service/StoreService.java b/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/javers/service/StoreService.java similarity index 100% rename from spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/javers/service/StoreService.java rename to spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/javers/service/StoreService.java diff --git a/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/javers/web/RebrandStoreDto.java b/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/javers/web/RebrandStoreDto.java similarity index 100% rename from spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/javers/web/RebrandStoreDto.java rename to spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/javers/web/RebrandStoreDto.java diff --git a/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/javers/web/StoreController.java b/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/javers/web/StoreController.java similarity index 100% rename from spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/javers/web/StoreController.java rename to spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/javers/web/StoreController.java diff --git a/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/javers/web/UpdatePriceDto.java b/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/javers/web/UpdatePriceDto.java similarity index 100% rename from spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/javers/web/UpdatePriceDto.java rename to spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/javers/web/UpdatePriceDto.java diff --git a/spring-boot-modules/spring-boot-data-2/src/main/resources/application.properties b/spring-boot-modules/spring-boot-data-2/src/main/resources/application.properties new file mode 100644 index 0000000000..60a6e0fed5 --- /dev/null +++ b/spring-boot-modules/spring-boot-data-2/src/main/resources/application.properties @@ -0,0 +1,22 @@ +spring.h2.console.path=/h2 +spring.h2.console.enabled=true +spring.datasource.url=jdbc:h2:mem:testdb +spring.datasource.driver-class-name=org.h2.Driver +spring.datasource.username=sa +spring.datasource.password= +javers.mappingStyle=FIELD +javers.algorithm=SIMPLE +javers.commitIdGenerator=synchronized_sequence +javers.prettyPrint=true +javers.typeSafeValues=false +javers.newObjectSnapshot=true +javers.packagesToScan= +javers.auditableAspectEnabled=true +javers.springDataAuditableRepositoryAspectEnabled=true +javers.sqlSchema= +javers.sqlSchemaManagementEnabled=true +javers.prettyPrintDateFormats.localDateTime=dd MMM yyyy, HH:mm:ss +javers.prettyPrintDateFormats.zonedDateTime=dd MMM yyyy, HH:mm:ssZ +javers.prettyPrintDateFormats.localDate=dd MMM yyyy +javers.prettyPrintDateFormats.localTime=HH:mm:ss + diff --git a/spring-boot-modules/spring-boot-data/README.md b/spring-boot-modules/spring-boot-data/README.md index f72864e6d9..c56c87014d 100644 --- a/spring-boot-modules/spring-boot-data/README.md +++ b/spring-boot-modules/spring-boot-data/README.md @@ -11,4 +11,4 @@ This module contains articles about Spring Boot with Spring Data - [Spring Custom Property Editor](https://www.baeldung.com/spring-mvc-custom-property-editor) - [Using @JsonComponent in Spring Boot](https://www.baeldung.com/spring-boot-jsoncomponent) - [Guide To Running Logic on Startup in Spring](https://www.baeldung.com/running-setup-logic-on-startup-in-spring) -- [Using JaVers for Data Model Auditing in Spring Data](https://www.baeldung.com/spring-data-javers-audit) + diff --git a/spring-boot-modules/spring-boot-data/pom.xml b/spring-boot-modules/spring-boot-data/pom.xml index 18360bbd8b..b69d0e093a 100644 --- a/spring-boot-modules/spring-boot-data/pom.xml +++ b/spring-boot-modules/spring-boot-data/pom.xml @@ -19,11 +19,6 @@ org.springframework.boot spring-boot-starter-data-redis - - org.javers - javers-spring-boot-starter-sql - ${javers.version} - org.springframework.boot spring-boot-starter-data-mongodb @@ -164,7 +159,6 @@ - 5.14.0 2.2.4 1.8 1.8 diff --git a/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/disableautoconfig/SpringDataJPA.java b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/disableautoconfig/SpringDataJPA.java index 87656f66a6..8554076612 100644 --- a/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/disableautoconfig/SpringDataJPA.java +++ b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/disableautoconfig/SpringDataJPA.java @@ -1,6 +1,5 @@ package com.baeldung.disableautoconfig; -import org.javers.spring.boot.sql.JaversSqlAutoConfiguration; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.data.web.SpringDataWebAutoConfiguration; @@ -9,8 +8,8 @@ import org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerA import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration; @SpringBootApplication(exclude = {DataSourceAutoConfiguration.class, - JaversSqlAutoConfiguration.class, SpringDataWebAutoConfiguration.class, - DataSourceTransactionManagerAutoConfiguration.class, HibernateJpaAutoConfiguration.class}) + SpringDataWebAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class, + HibernateJpaAutoConfiguration.class}) public class SpringDataJPA { public static void main(String[] args) { diff --git a/spring-boot-modules/spring-boot-data/src/main/resources/application.properties b/spring-boot-modules/spring-boot-data/src/main/resources/application.properties index 969464a41c..cee5701cb5 100644 --- a/spring-boot-modules/spring-boot-data/src/main/resources/application.properties +++ b/spring-boot-modules/spring-boot-data/src/main/resources/application.properties @@ -6,19 +6,5 @@ spring.datasource.url=jdbc:h2:mem:testdb spring.datasource.driver-class-name=org.h2.Driver spring.datasource.username=sa spring.datasource.password= -javers.mappingStyle=FIELD -javers.algorithm=SIMPLE -javers.commitIdGenerator=synchronized_sequence -javers.prettyPrint=true -javers.typeSafeValues=false -javers.newObjectSnapshot=true -javers.packagesToScan= -javers.auditableAspectEnabled=true -javers.springDataAuditableRepositoryAspectEnabled=true -javers.sqlSchema= -javers.sqlSchemaManagementEnabled=true -javers.prettyPrintDateFormats.localDateTime=dd MMM yyyy, HH:mm:ss -javers.prettyPrintDateFormats.zonedDateTime=dd MMM yyyy, HH:mm:ssZ -javers.prettyPrintDateFormats.localDate=dd MMM yyyy -javers.prettyPrintDateFormats.localTime=HH:mm:ss + diff --git a/spring-boot-modules/spring-boot/src/main/resources/templates/displayallbeans.html b/spring-boot-modules/spring-boot-di/src/main/resources/templates/displayallbeans.html similarity index 100% rename from spring-boot-modules/spring-boot/src/main/resources/templates/displayallbeans.html rename to spring-boot-modules/spring-boot-di/src/main/resources/templates/displayallbeans.html diff --git a/spring-boot-modules/spring-boot-mvc-3/README.md b/spring-boot-modules/spring-boot-mvc-3/README.md index fa24ac11ed..e4b0a73bda 100644 --- a/spring-boot-modules/spring-boot-mvc-3/README.md +++ b/spring-boot-modules/spring-boot-mvc-3/README.md @@ -11,4 +11,4 @@ This module contains articles about Spring Web MVC in Spring Boot projects. - [CharacterEncodingFilter In SpringBoot](https://www.baeldung.com/spring-boot-characterencodingfilter) - [HandlerInterceptors vs. Filters in Spring MVC](https://www.baeldung.com/spring-mvc-handlerinterceptor-vs-filter) - [ETags for REST with Spring](https://www.baeldung.com/etags-for-rest-with-spring) -- More articles: [[prev -->]](/spring-boot-modules/spring-boot-mvc-2) +- More articles: [[<-- Prev]](/spring-boot-modules/spring-boot-mvc-2)[[Next -->]](/spring-boot-modules/spring-boot-mvc-4) diff --git a/spring-boot-modules/spring-boot-mvc-4/README.md b/spring-boot-modules/spring-boot-mvc-4/README.md new file mode 100644 index 0000000000..68fcfa8b6b --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-4/README.md @@ -0,0 +1,10 @@ +## Spring Boot MVC + +This module contains articles about Spring Web MVC in Spring Boot projects. + +### Relevant Articles: + +- [How to Register a Servlet in Java](https://www.baeldung.com/register-servlet) +- [Guide to Spring WebUtils and ServletRequestUtils](https://www.baeldung.com/spring-webutils-servletrequestutils) +- [Configure a Spring Boot Web Application](https://www.baeldung.com/spring-boot-application-configuration) +- More articles: [[<-- Prev]](/spring-boot-modules/spring-boot-mvc-3) diff --git a/spring-boot-modules/spring-boot-mvc-4/pom.xml b/spring-boot-modules/spring-boot-mvc-4/pom.xml new file mode 100644 index 0000000000..7d4d6e3d0c --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-4/pom.xml @@ -0,0 +1,45 @@ + + + 4.0.0 + spring-boot-mvc-4 + spring-boot-mvc-4 + jar + Module For Spring Boot MVC Web + + + com.baeldung.spring-boot-modules + spring-boot-modules + 1.0.0-SNAPSHOT + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-validation + + + org.springframework.boot + spring-boot-starter-thymeleaf + + + org.springframework.boot + spring-boot-starter-data-jpa + + + com.h2database + h2 + + + commons-io + commons-io + ${commons-io.version} + + + + \ No newline at end of file diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/controller/servlet/HelloWorldServlet.java b/spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/boot/controller/servlet/HelloWorldServlet.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/controller/servlet/HelloWorldServlet.java rename to spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/boot/controller/servlet/HelloWorldServlet.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/controller/servlet/SpringHelloWorldServlet.java b/spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/boot/controller/servlet/SpringHelloWorldServlet.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/controller/servlet/SpringHelloWorldServlet.java rename to spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/boot/controller/servlet/SpringHelloWorldServlet.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/common/error/MyCustomErrorController.java b/spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/common/error/MyCustomErrorController.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/common/error/MyCustomErrorController.java rename to spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/common/error/MyCustomErrorController.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/common/error/SpringHelloServletRegistrationBean.java b/spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/common/error/SpringHelloServletRegistrationBean.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/common/error/SpringHelloServletRegistrationBean.java rename to spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/common/error/SpringHelloServletRegistrationBean.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/common/error/controller/ErrorController.java b/spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/common/error/controller/ErrorController.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/common/error/controller/ErrorController.java rename to spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/common/error/controller/ErrorController.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/common/properties/MyServletContainerCustomizationBean.java b/spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/common/properties/MyServletContainerCustomizationBean.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/common/properties/MyServletContainerCustomizationBean.java rename to spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/common/properties/MyServletContainerCustomizationBean.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/common/resources/ExecutorServiceExitCodeGenerator.java b/spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/common/resources/ExecutorServiceExitCodeGenerator.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/common/resources/ExecutorServiceExitCodeGenerator.java rename to spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/common/resources/ExecutorServiceExitCodeGenerator.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/main/SpringBootApplication.java b/spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/main/SpringBootApplication.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/main/SpringBootApplication.java rename to spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/main/SpringBootApplication.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/servlets/ApplicationMain.java b/spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/servlets/ApplicationMain.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/servlets/ApplicationMain.java rename to spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/servlets/ApplicationMain.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/servlets/configuration/WebAppInitializer.java b/spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/servlets/configuration/WebAppInitializer.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/servlets/configuration/WebAppInitializer.java rename to spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/servlets/configuration/WebAppInitializer.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/servlets/configuration/WebMvcConfigure.java b/spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/servlets/configuration/WebMvcConfigure.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/servlets/configuration/WebMvcConfigure.java rename to spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/servlets/configuration/WebMvcConfigure.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/servlets/props/Constants.java b/spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/servlets/props/Constants.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/servlets/props/Constants.java rename to spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/servlets/props/Constants.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/servlets/props/PropertyLoader.java b/spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/servlets/props/PropertyLoader.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/servlets/props/PropertyLoader.java rename to spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/servlets/props/PropertyLoader.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/servlets/props/PropertySourcesLoader.java b/spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/servlets/props/PropertySourcesLoader.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/servlets/props/PropertySourcesLoader.java rename to spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/servlets/props/PropertySourcesLoader.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/servlets/servlets/GenericCustomServlet.java b/spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/servlets/servlets/GenericCustomServlet.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/servlets/servlets/GenericCustomServlet.java rename to spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/servlets/servlets/GenericCustomServlet.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/servlets/servlets/javaee/AnnotationServlet.java b/spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/servlets/servlets/javaee/AnnotationServlet.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/servlets/servlets/javaee/AnnotationServlet.java rename to spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/servlets/servlets/javaee/AnnotationServlet.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/servlets/servlets/javaee/EEWebXmlServlet.java b/spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/servlets/servlets/javaee/EEWebXmlServlet.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/servlets/servlets/javaee/EEWebXmlServlet.java rename to spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/servlets/servlets/javaee/EEWebXmlServlet.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/servlets/servlets/springboot/SpringRegistrationBeanServlet.java b/spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/servlets/servlets/springboot/SpringRegistrationBeanServlet.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/servlets/servlets/springboot/SpringRegistrationBeanServlet.java rename to spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/servlets/servlets/springboot/SpringRegistrationBeanServlet.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/servlets/servlets/springboot/embedded/EmbeddedTomcatExample.java b/spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/servlets/servlets/springboot/embedded/EmbeddedTomcatExample.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/servlets/servlets/springboot/embedded/EmbeddedTomcatExample.java rename to spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/servlets/servlets/springboot/embedded/EmbeddedTomcatExample.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/utils/UtilsApplication.java b/spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/utils/UtilsApplication.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/utils/UtilsApplication.java rename to spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/utils/UtilsApplication.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/utils/controller/UtilsController.java b/spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/utils/controller/UtilsController.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/utils/controller/UtilsController.java rename to spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/utils/controller/UtilsController.java diff --git a/spring-boot-modules/spring-boot/src/main/resources/application.properties b/spring-boot-modules/spring-boot-mvc-4/src/main/resources/application.properties similarity index 100% rename from spring-boot-modules/spring-boot/src/main/resources/application.properties rename to spring-boot-modules/spring-boot-mvc-4/src/main/resources/application.properties diff --git a/spring-boot-modules/spring-boot/src/main/resources/custom.properties b/spring-boot-modules/spring-boot-mvc-4/src/main/resources/custom.properties similarity index 100% rename from spring-boot-modules/spring-boot/src/main/resources/custom.properties rename to spring-boot-modules/spring-boot-mvc-4/src/main/resources/custom.properties diff --git a/immutables/src/main/resources/logback.xml b/spring-boot-modules/spring-boot-mvc-4/src/main/resources/logback.xml similarity index 100% rename from immutables/src/main/resources/logback.xml rename to spring-boot-modules/spring-boot-mvc-4/src/main/resources/logback.xml diff --git a/spring-boot-modules/spring-boot/src/main/resources/shutdown/shutdown.bat b/spring-boot-modules/spring-boot-mvc-4/src/main/resources/shutdown/shutdown.bat similarity index 100% rename from spring-boot-modules/spring-boot/src/main/resources/shutdown/shutdown.bat rename to spring-boot-modules/spring-boot-mvc-4/src/main/resources/shutdown/shutdown.bat diff --git a/spring-boot-modules/spring-boot/src/main/resources/templates/other.html b/spring-boot-modules/spring-boot-mvc-4/src/main/resources/templates/other.html similarity index 100% rename from spring-boot-modules/spring-boot/src/main/resources/templates/other.html rename to spring-boot-modules/spring-boot-mvc-4/src/main/resources/templates/other.html diff --git a/spring-boot-modules/spring-boot/src/main/resources/templates/utils.html b/spring-boot-modules/spring-boot-mvc-4/src/main/resources/templates/utils.html similarity index 100% rename from spring-boot-modules/spring-boot/src/main/resources/templates/utils.html rename to spring-boot-modules/spring-boot-mvc-4/src/main/resources/templates/utils.html diff --git a/spring-boot-modules/spring-boot/src/main/webapp/WEB-INF/context.xml b/spring-boot-modules/spring-boot-mvc-4/src/main/webapp/WEB-INF/context.xml similarity index 100% rename from spring-boot-modules/spring-boot/src/main/webapp/WEB-INF/context.xml rename to spring-boot-modules/spring-boot-mvc-4/src/main/webapp/WEB-INF/context.xml diff --git a/spring-boot-modules/spring-boot/src/main/webapp/WEB-INF/dispatcher.xml b/spring-boot-modules/spring-boot-mvc-4/src/main/webapp/WEB-INF/dispatcher.xml similarity index 100% rename from spring-boot-modules/spring-boot/src/main/webapp/WEB-INF/dispatcher.xml rename to spring-boot-modules/spring-boot-mvc-4/src/main/webapp/WEB-INF/dispatcher.xml diff --git a/spring-boot-modules/spring-boot/src/main/webapp/WEB-INF/web.xml b/spring-boot-modules/spring-boot-mvc-4/src/main/webapp/WEB-INF/web.xml similarity index 100% rename from spring-boot-modules/spring-boot/src/main/webapp/WEB-INF/web.xml rename to spring-boot-modules/spring-boot-mvc-4/src/main/webapp/WEB-INF/web.xml diff --git a/spring-boot-modules/spring-boot/src/main/webapp/annotationservlet.jsp b/spring-boot-modules/spring-boot-mvc-4/src/main/webapp/annotationservlet.jsp similarity index 100% rename from spring-boot-modules/spring-boot/src/main/webapp/annotationservlet.jsp rename to spring-boot-modules/spring-boot-mvc-4/src/main/webapp/annotationservlet.jsp diff --git a/spring-boot-modules/spring-boot/src/main/webapp/index.jsp b/spring-boot-modules/spring-boot-mvc-4/src/main/webapp/index.jsp similarity index 100% rename from spring-boot-modules/spring-boot/src/main/webapp/index.jsp rename to spring-boot-modules/spring-boot-mvc-4/src/main/webapp/index.jsp diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/utils/UtilsControllerIntegrationTest.java b/spring-boot-modules/spring-boot-mvc-4/src/test/java/com/baeldung/utils/UtilsControllerIntegrationTest.java similarity index 100% rename from spring-boot-modules/spring-boot/src/test/java/com/baeldung/utils/UtilsControllerIntegrationTest.java rename to spring-boot-modules/spring-boot-mvc-4/src/test/java/com/baeldung/utils/UtilsControllerIntegrationTest.java diff --git a/spring-boot-modules/spring-boot-mvc/README.md b/spring-boot-modules/spring-boot-mvc/README.md index 5e9ecded10..cdb2bd0fce 100644 --- a/spring-boot-modules/spring-boot-mvc/README.md +++ b/spring-boot-modules/spring-boot-mvc/README.md @@ -11,4 +11,5 @@ This module contains articles about Spring Web MVC in Spring Boot projects. - [Using Spring ResponseEntity to Manipulate the HTTP Response](https://www.baeldung.com/spring-response-entity) - [The @ServletComponentScan Annotation in Spring Boot](https://www.baeldung.com/spring-servletcomponentscan) - [Guide to Internationalization in Spring Boot](https://www.baeldung.com/spring-boot-internationalization) +- [Hide a Request Field in Swagger API](https://www.baeldung.com/spring-swagger-hide-field) - More articles: [[next -->]](/spring-boot-modules/spring-boot-mvc-2) diff --git a/spring-boot-modules/spring-boot-properties-migrator-demo/pom.xml b/spring-boot-modules/spring-boot-properties-migrator-demo/pom.xml new file mode 100644 index 0000000000..d44a8ce6f1 --- /dev/null +++ b/spring-boot-modules/spring-boot-properties-migrator-demo/pom.xml @@ -0,0 +1,57 @@ + + + 4.0.0 + + spring-boot-properties-migrator-demo + 1.0-SNAPSHOT + + + com.baeldung.spring-boot-modules + spring-boot-modules + 1.0.0-SNAPSHOT + ../pom.xml + + + + + + + + + + + 8 + 8 + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-properties-migrator + runtime + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + repackage + + + + + + + + diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/intro/App.java b/spring-boot-modules/spring-boot-properties-migrator-demo/src/main/java/com/baeldung/spring/boot/properties/migrator/Main.java similarity index 61% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/intro/App.java rename to spring-boot-modules/spring-boot-properties-migrator-demo/src/main/java/com/baeldung/spring/boot/properties/migrator/Main.java index 77cdf4ddb9..848b9680a0 100644 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/intro/App.java +++ b/spring-boot-modules/spring-boot-properties-migrator-demo/src/main/java/com/baeldung/spring/boot/properties/migrator/Main.java @@ -1,11 +1,11 @@ -package com.baeldung.intro; +package com.baeldung.spring.boot.properties.migrator; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication -public class App { +public class Main { public static void main(String[] args) { - SpringApplication.run(App.class, args); + SpringApplication.run(Main.class, args); } } diff --git a/spring-boot-modules/spring-boot-properties-migrator-demo/src/main/resources/application-dev.yaml b/spring-boot-modules/spring-boot-properties-migrator-demo/src/main/resources/application-dev.yaml new file mode 100644 index 0000000000..6eadac798b --- /dev/null +++ b/spring-boot-modules/spring-boot-properties-migrator-demo/src/main/resources/application-dev.yaml @@ -0,0 +1,16 @@ +# Deprecated Properties for Demonstration +#spring: +# resources: +# cache: +# period: 31536000 +# chain: +# compressed: true +# html-application-cache: true + +spring: + web: + resources: + cache: + period: 31536000 + chain: + compressed: false diff --git a/spring-boot-modules/spring-boot-properties-migrator-demo/src/main/resources/application.properties b/spring-boot-modules/spring-boot-properties-migrator-demo/src/main/resources/application.properties new file mode 100644 index 0000000000..15199b7710 --- /dev/null +++ b/spring-boot-modules/spring-boot-properties-migrator-demo/src/main/resources/application.properties @@ -0,0 +1,7 @@ +# Deprecated Properties for Demonstration +#spring.resources.cache.period=31536000 +#spring.resources.chain.compressed=false +#spring.resources.chain.html-application-cache=false +spring.web.resources.cache.period=31536000 +spring.web.resources.chain.compressed=false +banner.image.location="myBanner.txt" diff --git a/spring-boot-modules/spring-boot-validation/README.md b/spring-boot-modules/spring-boot-validation/README.md index 8c3c8b9305..93b6e7d2d1 100644 --- a/spring-boot-modules/spring-boot-validation/README.md +++ b/spring-boot-modules/spring-boot-validation/README.md @@ -1,3 +1,4 @@ ### Relevant Articles - [Spring Validation in the Service Layer](https://www.baeldung.com/spring-service-layer-validation) +- [Validation in Spring Boot](https://www.baeldung.com/spring-boot-bean-validation) diff --git a/spring-boot-modules/spring-boot-validation/pom.xml b/spring-boot-modules/spring-boot-validation/pom.xml index fa4e8439e6..639a62059d 100644 --- a/spring-boot-modules/spring-boot-validation/pom.xml +++ b/spring-boot-modules/spring-boot-validation/pom.xml @@ -22,6 +22,14 @@ org.hibernate.validator hibernate-validator + + org.springframework.boot + spring-boot-starter-data-jpa + + + com.h2database + h2 + diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/beanvalidation/application/Application.java b/spring-boot-modules/spring-boot-validation/src/main/java/com/baeldung/beanvalidation/application/Application.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/beanvalidation/application/Application.java rename to spring-boot-modules/spring-boot-validation/src/main/java/com/baeldung/beanvalidation/application/Application.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/beanvalidation/application/controllers/UserController.java b/spring-boot-modules/spring-boot-validation/src/main/java/com/baeldung/beanvalidation/application/controllers/UserController.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/beanvalidation/application/controllers/UserController.java rename to spring-boot-modules/spring-boot-validation/src/main/java/com/baeldung/beanvalidation/application/controllers/UserController.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/beanvalidation/application/entities/User.java b/spring-boot-modules/spring-boot-validation/src/main/java/com/baeldung/beanvalidation/application/entities/User.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/beanvalidation/application/entities/User.java rename to spring-boot-modules/spring-boot-validation/src/main/java/com/baeldung/beanvalidation/application/entities/User.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/beanvalidation/application/repositories/UserRepository.java b/spring-boot-modules/spring-boot-validation/src/main/java/com/baeldung/beanvalidation/application/repositories/UserRepository.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/beanvalidation/application/repositories/UserRepository.java rename to spring-boot-modules/spring-boot-validation/src/main/java/com/baeldung/beanvalidation/application/repositories/UserRepository.java diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/beanvalidation/application/UserControllerIntegrationTest.java b/spring-boot-modules/spring-boot-validation/src/test/java/com/baeldung/beanvalidation/application/UserControllerIntegrationTest.java similarity index 100% rename from spring-boot-modules/spring-boot/src/test/java/com/baeldung/beanvalidation/application/UserControllerIntegrationTest.java rename to spring-boot-modules/spring-boot-validation/src/test/java/com/baeldung/beanvalidation/application/UserControllerIntegrationTest.java diff --git a/spring-boot-modules/spring-boot/.gitignore b/spring-boot-modules/spring-boot/.gitignore deleted file mode 100644 index da7c2c5c0a..0000000000 --- a/spring-boot-modules/spring-boot/.gitignore +++ /dev/null @@ -1,5 +0,0 @@ -/target/ -.settings/ -.classpath -.project - diff --git a/spring-boot-modules/spring-boot/.mvn/wrapper/maven-wrapper.properties b/spring-boot-modules/spring-boot/.mvn/wrapper/maven-wrapper.properties deleted file mode 100755 index a447c9fa81..0000000000 --- a/spring-boot-modules/spring-boot/.mvn/wrapper/maven-wrapper.properties +++ /dev/null @@ -1 +0,0 @@ -distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.2/apache-maven-3.5.2-bin.zip \ No newline at end of file diff --git a/spring-boot-modules/spring-boot/README.md b/spring-boot-modules/spring-boot/README.md deleted file mode 100644 index fdc8093806..0000000000 --- a/spring-boot-modules/spring-boot/README.md +++ /dev/null @@ -1,16 +0,0 @@ -## Spring Boot - -This module contains articles about Spring Boot - -### The Course -The "REST With Spring" Classes: http://bit.ly/restwithspring - -### Relevant Articles: - -- [A Guide to Spring in Eclipse STS](https://www.baeldung.com/eclipse-sts-spring) -- [Guide to Spring Type Conversions](https://www.baeldung.com/spring-type-conversions) -- [Spring Boot: Configuring a Main Class](https://www.baeldung.com/spring-boot-main-class) -- [Container Configuration in Spring Boot 2](https://www.baeldung.com/embeddedservletcontainercustomizer-configurableembeddedservletcontainer-spring-boot) -- [Validation in Spring Boot](https://www.baeldung.com/spring-boot-bean-validation) -- [How to Register a Servlet in Java](https://www.baeldung.com/register-servlet) -- [Guide to Spring WebUtils and ServletRequestUtils](https://www.baeldung.com/spring-webutils-servletrequestutils) diff --git a/spring-boot-modules/spring-boot/mvnw b/spring-boot-modules/spring-boot/mvnw deleted file mode 100755 index e96ccd5fbb..0000000000 --- a/spring-boot-modules/spring-boot/mvnw +++ /dev/null @@ -1,227 +0,0 @@ -#!/bin/sh -# ---------------------------------------------------------------------------- -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. -# ---------------------------------------------------------------------------- - -# ---------------------------------------------------------------------------- -# Maven2 Start Up Batch script -# -# Required ENV vars: -# ------------------ -# JAVA_HOME - location of a JDK home dir -# -# Optional ENV vars -# ----------------- -# M2_HOME - location of maven2's installed home dir -# MAVEN_OPTS - parameters passed to the Java VM when running Maven -# e.g. to debug Maven itself, use -# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 -# MAVEN_SKIP_RC - flag to disable loading of mavenrc files -# ---------------------------------------------------------------------------- - -if [ -z "$MAVEN_SKIP_RC" ] ; then - - if [ -f /etc/mavenrc ] ; then - . /etc/mavenrc - fi - - if [ -f "$HOME/.mavenrc" ] ; then - . "$HOME/.mavenrc" - fi - -fi - -# OS specific support. $var _must_ be set to either true or false. -cygwin=false; -darwin=false; -mingw=false -case "`uname`" in - CYGWIN*) cygwin=true ;; - MINGW*) mingw=true;; - Darwin*) darwin=true - # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home - # See https://developer.apple.com/library/mac/qa/qa1170/_index.html - if [ -z "$JAVA_HOME" ]; then - if [ -x "/usr/libexec/java_home" ]; then - export JAVA_HOME="`/usr/libexec/java_home`" - else - export JAVA_HOME="/Library/Java/Home" - fi - fi - ;; -esac - -if [ -z "$JAVA_HOME" ] ; then - if [ -r /etc/gentoo-release ] ; then - JAVA_HOME=`java-config --jre-home` - fi -fi - -if [ -z "$M2_HOME" ] ; then - ## resolve links - $0 may be a link to maven's home - 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 - - saveddir=`pwd` - - M2_HOME=`dirname "$PRG"`/.. - - # make it fully qualified - M2_HOME=`cd "$M2_HOME" && pwd` - - cd "$saveddir" - # echo Using m2 at $M2_HOME -fi - -# For Cygwin, ensure paths are in UNIX format before anything is touched -if $cygwin ; then - [ -n "$M2_HOME" ] && - M2_HOME=`cygpath --unix "$M2_HOME"` - [ -n "$JAVA_HOME" ] && - JAVA_HOME=`cygpath --unix "$JAVA_HOME"` - [ -n "$CLASSPATH" ] && - CLASSPATH=`cygpath --path --unix "$CLASSPATH"` -fi - -# For Mingw, ensure paths are in UNIX format before anything is touched -if $mingw ; then - [ -n "$M2_HOME" ] && - M2_HOME="`(cd "$M2_HOME"; pwd)`" - [ -n "$JAVA_HOME" ] && - JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" - # TODO classpath? -fi - -if [ -z "$JAVA_HOME" ]; then - javaExecutable="`which javac`" - if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then - # readlink(1) is not available as standard on Solaris 10. - readLink=`which readlink` - if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then - if $darwin ; then - javaHome="`dirname \"$javaExecutable\"`" - javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" - else - javaExecutable="`readlink -f \"$javaExecutable\"`" - fi - javaHome="`dirname \"$javaExecutable\"`" - javaHome=`expr "$javaHome" : '\(.*\)/bin'` - JAVA_HOME="$javaHome" - export JAVA_HOME - fi - fi -fi - -if [ -z "$JAVACMD" ] ; then - 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 - else - JAVACMD="`which java`" - fi -fi - -if [ ! -x "$JAVACMD" ] ; then - echo "Error: JAVA_HOME is not defined correctly." >&2 - echo " We cannot execute $JAVACMD" >&2 - exit 1 -fi - -if [ -z "$JAVA_HOME" ] ; then - echo "Warning: JAVA_HOME environment variable is not set." -fi - -CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher - -# traverses directory structure from process work directory to filesystem root -# first directory with .mvn subdirectory is considered project base directory -find_maven_basedir() { - - if [ -z "$1" ] - then - echo "Path not specified to find_maven_basedir" - return 1 - fi - - basedir="$1" - wdir="$1" - while [ "$wdir" != '/' ] ; do - if [ -d "$wdir"/.mvn ] ; then - basedir=$wdir - break - fi - # workaround for JBEAP-8937 (on Solaris 10/Sparc) - if [ -d "${wdir}" ]; then - wdir=`cd "$wdir/.."; pwd` - fi - # end of workaround - done - echo "${basedir}" -} - -# concatenates all lines of a file -concat_lines() { - if [ -f "$1" ]; then - echo "$(tr -s '\n' ' ' < "$1")" - fi -} - -BASE_DIR=`find_maven_basedir "$(pwd)"` -if [ -z "$BASE_DIR" ]; then - exit 1; -fi - -export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} -if [ "$MVNW_VERBOSE" = true ]; then - echo $MAVEN_PROJECTBASEDIR -fi -MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" - -# For Cygwin, switch paths to Windows format before running java -if $cygwin; then - [ -n "$M2_HOME" ] && - M2_HOME=`cygpath --path --windows "$M2_HOME"` - [ -n "$JAVA_HOME" ] && - JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` - [ -n "$CLASSPATH" ] && - CLASSPATH=`cygpath --path --windows "$CLASSPATH"` - [ -n "$MAVEN_PROJECTBASEDIR" ] && - MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` -fi - -WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain - -exec "$JAVACMD" \ - $MAVEN_OPTS \ - -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ - "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ - ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/spring-boot-modules/spring-boot/mvnw.cmd b/spring-boot-modules/spring-boot/mvnw.cmd deleted file mode 100755 index 6a6eec39ba..0000000000 --- a/spring-boot-modules/spring-boot/mvnw.cmd +++ /dev/null @@ -1,145 +0,0 @@ -@REM ---------------------------------------------------------------------------- -@REM Licensed to the Apache Software Foundation (ASF) under one -@REM or more contributor license agreements. See the NOTICE file -@REM distributed with this work for additional information -@REM regarding copyright ownership. The ASF licenses this file -@REM to you under the Apache License, Version 2.0 (the -@REM "License"); you may not use this file except in compliance -@REM with the License. You may obtain a copy of the License at -@REM -@REM http://www.apache.org/licenses/LICENSE-2.0 -@REM -@REM Unless required by applicable law or agreed to in writing, -@REM software distributed under the License is distributed on an -@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -@REM KIND, either express or implied. See the License for the -@REM specific language governing permissions and limitations -@REM under the License. -@REM ---------------------------------------------------------------------------- - -@REM ---------------------------------------------------------------------------- -@REM Maven2 Start Up Batch script -@REM -@REM Required ENV vars: -@REM JAVA_HOME - location of a JDK home dir -@REM -@REM Optional ENV vars -@REM M2_HOME - location of maven2's installed home dir -@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands -@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending -@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven -@REM e.g. to debug Maven itself, use -@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 -@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files -@REM ---------------------------------------------------------------------------- - -@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' -@echo off -@REM set title of command window -title %0 -@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' -@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% - -@REM set %HOME% to equivalent of $HOME -if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") - -@REM Execute a user defined script before this one -if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre -@REM check for pre script, once with legacy .bat ending and once with .cmd ending -if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" -if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" -:skipRcPre - -@setlocal - -set ERROR_CODE=0 - -@REM To isolate internal variables from possible post scripts, we use another setlocal -@setlocal - -@REM ==== START VALIDATION ==== -if not "%JAVA_HOME%" == "" goto OkJHome - -echo. -echo Error: JAVA_HOME not found in your environment. >&2 -echo Please set the JAVA_HOME variable in your environment to match the >&2 -echo location of your Java installation. >&2 -echo. -goto error - -:OkJHome -if exist "%JAVA_HOME%\bin\java.exe" goto init - -echo. -echo Error: JAVA_HOME is set to an invalid directory. >&2 -echo JAVA_HOME = "%JAVA_HOME%" >&2 -echo Please set the JAVA_HOME variable in your environment to match the >&2 -echo location of your Java installation. >&2 -echo. -goto error - -@REM ==== END VALIDATION ==== - -:init - -@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". -@REM Fallback to current working directory if not found. - -set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% -IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir - -set EXEC_DIR=%CD% -set WDIR=%EXEC_DIR% -:findBaseDir -IF EXIST "%WDIR%"\.mvn goto baseDirFound -cd .. -IF "%WDIR%"=="%CD%" goto baseDirNotFound -set WDIR=%CD% -goto findBaseDir - -:baseDirFound -set MAVEN_PROJECTBASEDIR=%WDIR% -cd "%EXEC_DIR%" -goto endDetectBaseDir - -:baseDirNotFound -set MAVEN_PROJECTBASEDIR=%EXEC_DIR% -cd "%EXEC_DIR%" - -:endDetectBaseDir - -IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig - -@setlocal EnableExtensions EnableDelayedExpansion -for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a -@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% - -:endReadAdditionalConfig - -SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" - -set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" -set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain - -%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* -if ERRORLEVEL 1 goto error -goto end - -:error -set ERROR_CODE=1 - -:end -@endlocal & set ERROR_CODE=%ERROR_CODE% - -if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost -@REM check for post script, once with legacy .bat ending and once with .cmd ending -if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" -if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" -:skipRcPost - -@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' -if "%MAVEN_BATCH_PAUSE%" == "on" pause - -if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% - -exit /B %ERROR_CODE% diff --git a/spring-boot-modules/spring-boot/pom.xml b/spring-boot-modules/spring-boot/pom.xml deleted file mode 100644 index 3afccef925..0000000000 --- a/spring-boot-modules/spring-boot/pom.xml +++ /dev/null @@ -1,166 +0,0 @@ - - - 4.0.0 - spring-boot - 0.0.1-SNAPSHOT - spring-boot - war - This is simple boot application for Spring boot actuator test - - - com.baeldung.spring-boot-modules - spring-boot-modules - 1.0.0-SNAPSHOT - - - - - org.springframework.boot - spring-boot-starter-thymeleaf - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-validation - - - org.springframework.boot - spring-boot-starter-data-jpa - - - org.ehcache - ehcache - - - org.hibernate - hibernate-ehcache - - - org.springframework.boot - spring-boot-starter-actuator - - - org.springframework.boot - spring-boot-starter-tomcat - - - org.springframework.boot - spring-boot-starter-test - test - - - io.dropwizard.metrics - metrics-core - - - com.h2database - h2 - - - org.springframework.boot - spring-boot-starter - - - com.jayway.jsonpath - json-path - test - - - com.google.guava - guava - ${guava.version} - - - org.apache.tomcat - tomcat-servlet-api - ${tomee-servlet-api.version} - provided - - - org.apache.activemq - artemis-server - - - com.rometools - rome - ${rome.version} - - - - - spring-boot - - - src/main/resources - true - - - - - org.apache.maven.plugins - maven-war-plugin - - - org.apache.maven.plugins - maven-resources-plugin - - - @ - - false - - - - - - - - autoconfiguration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - **/*IntegrationTest.java - **/*IntTest.java - - - **/AutoconfigurationTest.java - - - - - - - json - - - - - - - - - - - com.baeldung.intro.App - 8.5.11 - 1.9.0 - @ - - - \ No newline at end of file diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/config/H2JpaConfig.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/config/H2JpaConfig.java deleted file mode 100644 index 928928c9a5..0000000000 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/config/H2JpaConfig.java +++ /dev/null @@ -1,67 +0,0 @@ -package com.baeldung.boot.config; - -import java.util.Properties; - -import javax.persistence.EntityManagerFactory; -import javax.sql.DataSource; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.PropertySource; -import org.springframework.core.env.Environment; -import org.springframework.data.jpa.repository.config.EnableJpaRepositories; -import org.springframework.jdbc.datasource.DriverManagerDataSource; -import org.springframework.orm.jpa.JpaTransactionManager; -import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; -import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; -import org.springframework.transaction.annotation.EnableTransactionManagement; - -@Configuration -@EnableJpaRepositories(basePackages = { "com.baeldung.boot.repository", "com.baeldung.boot.boottest", "com.baeldung.repository" }) -@PropertySource("classpath:persistence-generic-entity.properties") -@EnableTransactionManagement -public class H2JpaConfig { - - @Autowired - private Environment env; - - @Bean - public DataSource dataSource() { - final DriverManagerDataSource dataSource = new DriverManagerDataSource(); - dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName")); - dataSource.setUrl(env.getProperty("jdbc.url")); - dataSource.setUsername(env.getProperty("jdbc.user")); - dataSource.setPassword(env.getProperty("jdbc.pass")); - - return dataSource; - } - - @Bean - public LocalContainerEntityManagerFactoryBean entityManagerFactory() { - final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); - em.setDataSource(dataSource()); - em.setPackagesToScan(new String[] { "com.baeldung.boot.domain", "com.baeldung.boot.model", "com.baeldung.boot.boottest", "com.baeldung.model" }); - em.setJpaVendorAdapter(new HibernateJpaVendorAdapter()); - em.setJpaProperties(additionalProperties()); - return em; - } - - @Bean - JpaTransactionManager transactionManager(final EntityManagerFactory entityManagerFactory) { - final JpaTransactionManager transactionManager = new JpaTransactionManager(); - transactionManager.setEntityManagerFactory(entityManagerFactory); - return transactionManager; - } - - final Properties additionalProperties() { - final Properties hibernateProperties = new Properties(); - - hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); - hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); - hibernateProperties.setProperty("hibernate.show_sql", env.getProperty("hibernate.show_sql")); - - return hibernateProperties; - } - -} diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/domain/Modes.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/domain/Modes.java deleted file mode 100644 index 7717294996..0000000000 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/domain/Modes.java +++ /dev/null @@ -1,6 +0,0 @@ -package com.baeldung.boot.domain; - -public enum Modes { - - ALPHA, BETA; -} diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/buildproperties/Application.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/buildproperties/Application.java deleted file mode 100644 index 405cec3eac..0000000000 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/buildproperties/Application.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.baeldung.buildproperties; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.PropertySource; - -@SpringBootApplication -@ComponentScan(basePackages = "com.baeldung.buildproperties") -@PropertySource("classpath:build.properties") -//@PropertySource("classpath:build.yml") -public class Application { - - public static void main(String[] args) { - SpringApplication.run(Application.class, args); - } - -} diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/buildproperties/BuildInfoService.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/buildproperties/BuildInfoService.java deleted file mode 100644 index 2a0d27188e..0000000000 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/buildproperties/BuildInfoService.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.baeldung.buildproperties; - -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Service; - -@Service -public class BuildInfoService { - @Value("${application-description}") - private String applicationDescription; - - @Value("${application-version}") - private String applicationVersion; - - public String getApplicationDescription() { - return applicationDescription; - } - - public String getApplicationVersion() { - return applicationVersion; - } -} diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/intro/controller/HomeController.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/intro/controller/HomeController.java deleted file mode 100644 index 4797d6e593..0000000000 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/intro/controller/HomeController.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.baeldung.intro.controller; - -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RestController; - -@RestController -public class HomeController { - - @GetMapping("/") - public String root() { - return "Index Page"; - } - - @GetMapping("/local") - public String local() { - return "/local"; - } -} diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/jsondateformat/Contact.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/jsondateformat/Contact.java deleted file mode 100644 index f131d17196..0000000000 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/jsondateformat/Contact.java +++ /dev/null @@ -1,70 +0,0 @@ -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-modules/spring-boot/src/main/java/com/baeldung/jsondateformat/ContactAppConfig.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/jsondateformat/ContactAppConfig.java deleted file mode 100644 index 7a20ebfa51..0000000000 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/jsondateformat/ContactAppConfig.java +++ /dev/null @@ -1,33 +0,0 @@ -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-modules/spring-boot/src/main/java/com/baeldung/jsondateformat/ContactController.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/jsondateformat/ContactController.java deleted file mode 100644 index 8894d82fc7..0000000000 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/jsondateformat/ContactController.java +++ /dev/null @@ -1,77 +0,0 @@ -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-modules/spring-boot/src/main/java/com/baeldung/jsondateformat/ContactWithJavaUtilDate.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/jsondateformat/ContactWithJavaUtilDate.java deleted file mode 100644 index 5a1c508098..0000000000 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/jsondateformat/ContactWithJavaUtilDate.java +++ /dev/null @@ -1,69 +0,0 @@ -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-modules/spring-boot/src/main/java/com/baeldung/jsondateformat/PlainContact.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/jsondateformat/PlainContact.java deleted file mode 100644 index 7e9e53d205..0000000000 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/jsondateformat/PlainContact.java +++ /dev/null @@ -1,66 +0,0 @@ -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-modules/spring-boot/src/main/java/com/baeldung/jsondateformat/PlainContactWithJavaUtilDate.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/jsondateformat/PlainContactWithJavaUtilDate.java deleted file mode 100644 index daefb15543..0000000000 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/jsondateformat/PlainContactWithJavaUtilDate.java +++ /dev/null @@ -1,69 +0,0 @@ -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-modules/spring-boot/src/main/java/com/baeldung/model/User.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/model/User.java deleted file mode 100644 index cc5f27f38c..0000000000 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/model/User.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.baeldung.model; - -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.Table; - -@Entity -@Table(name = "users") -public class User { - - @Id - @GeneratedValue - private Integer id; - private String name; - private Integer status; - - public User() { - } - - public User(String name, Integer status) { - this.name = name; - this.status = status; - } - - 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 Integer getStatus() { - return status; - } - - public void setStatus(Integer status) { - this.status = status; - } -} diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/repository/UserRepository.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/repository/UserRepository.java deleted file mode 100644 index 4dd863fb17..0000000000 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/repository/UserRepository.java +++ /dev/null @@ -1,79 +0,0 @@ -package com.baeldung.repository; - -import com.baeldung.model.User; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.Pageable; -import org.springframework.data.domain.Sort; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.Modifying; -import org.springframework.data.jpa.repository.Query; -import org.springframework.data.repository.query.Param; -import org.springframework.scheduling.annotation.Async; -import org.springframework.stereotype.Repository; - -import java.util.Collection; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.CompletableFuture; - -@Repository("userRepository") -public interface UserRepository extends JpaRepository { - - int countByStatus(int status); - - Optional findOneByName(String name); - - @Async - CompletableFuture findOneByStatus(Integer status); - - @Query("SELECT u FROM User u WHERE u.status = 1") - Collection findAllActiveUsers(); - - @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 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") - User findUserByStatusAndName(Integer status, String name); - - @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 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") - User findUserByUserStatusAndUserName(@Param("status") Integer userStatus, @Param("name") String userName); - - @Query("SELECT u FROM User u WHERE u.name like ?1%") - User findUserByNameLike(String name); - - @Query("SELECT u FROM User u WHERE u.name like :name%") - User findUserByNameLikeNamedParam(@Param("name") String name); - - @Query(value = "SELECT * FROM users u WHERE u.name LIKE ?1%", nativeQuery = true) - User findUserByNameLikeNative(String name); - - @Query(value = "SELECT u FROM User u") - List findAllUsers(Sort sort); - - @Query(value = "SELECT u FROM User u ORDER BY id") - Page findAllUsersWithPagination(Pageable pageable); - - @Query(value = "SELECT * FROM Users ORDER BY id \n-- #pageable\n", countQuery = "SELECT count(*) FROM Users", nativeQuery = true) - Page findAllUsersWithPaginationNative(Pageable pageable); - - @Modifying - @Query("update User u set u.status = :status where u.name = :name") - int updateUserSetStatusForName(@Param("status") Integer status, @Param("name") String name); - - @Modifying - @Query(value = "UPDATE Users u SET u.status = ? WHERE u.name = ?", nativeQuery = true) - int updateUserSetStatusForNameNative(Integer status, String name); - -} diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/rss/ArticleFeedView.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/rss/ArticleFeedView.java deleted file mode 100644 index 3efa619409..0000000000 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/rss/ArticleFeedView.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.baeldung.rss; - -import com.rometools.rome.feed.rss.Channel; -import com.rometools.rome.feed.rss.Description; -import com.rometools.rome.feed.rss.Item; -import org.springframework.stereotype.Service; -import org.springframework.web.servlet.view.feed.AbstractRssFeedView; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.Map; - -@Service("articleFeedView") -public class ArticleFeedView extends AbstractRssFeedView { - - protected Channel newFeed() { - Channel channel = new Channel("rss_2.0"); - channel.setLink("http://localhost:8080/rss"); - channel.setTitle("Article Feed"); - channel.setDescription("Article Feed Description"); - channel.setPubDate(new Date()); - return channel; - } - - @Override - protected List buildFeedItems(Map map, HttpServletRequest httpStRequest, HttpServletResponse httpStResponse) throws Exception { - List list = new ArrayList(); - - Item item1 = new Item(); - item1.setLink("http://www.baeldung.com/netty-exception-handling"); - item1.setTitle("Exceptions in Netty"); - Description description1 = new Description(); - description1.setValue("In this quick article, we’ll be looking at exception handling in Netty."); - item1.setDescription(description1); - item1.setPubDate(new Date()); - item1.setAuthor("Carlos"); - - Item item2 = new Item(); - item2.setLink("http://www.baeldung.com/cockroachdb-java"); - item2.setTitle("Guide to CockroachDB in Java"); - Description description2 = new Description(); - description2.setValue("This tutorial is an introductory guide to using CockroachDB with Java."); - item2.setDescription(description2); - item2.setPubDate(new Date()); - item2.setAuthor("Baeldung"); - - list.add(item1); - list.add(item2); - return list; - } -} diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/rss/ArticleRssController.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/rss/ArticleRssController.java deleted file mode 100644 index daaeb8159b..0000000000 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/rss/ArticleRssController.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.baeldung.rss; - -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; - -@Controller -@RequestMapping(value = "/rss", produces = "application/*") -public class ArticleRssController { - - @GetMapping - public String articleFeed() { - return "articleFeedView"; - } - -} diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/rss/RssApp.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/rss/RssApp.java deleted file mode 100644 index e067d3cfd1..0000000000 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/rss/RssApp.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.baeldung.rss; - -import javax.annotation.security.RolesAllowed; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.annotation.ComponentScan; - -@SpringBootApplication -@ComponentScan(basePackages = "com.baeldung.rss") -public class RssApp { - - @RolesAllowed("*") - public static void main(String[] args) { - SpringApplication.run(RssApp.class, args); - } - -} diff --git a/spring-boot-modules/spring-boot/src/main/resources/application-errorhandling.properties b/spring-boot-modules/spring-boot/src/main/resources/application-errorhandling.properties deleted file mode 100644 index 270e86d443..0000000000 --- a/spring-boot-modules/spring-boot/src/main/resources/application-errorhandling.properties +++ /dev/null @@ -1,4 +0,0 @@ -#server -server.port=9000 -server.servlet-path=/ -server.context-path=/ \ No newline at end of file diff --git a/spring-boot-modules/spring-boot/src/main/resources/build.properties b/spring-boot-modules/spring-boot/src/main/resources/build.properties deleted file mode 100644 index 1612b8086d..0000000000 --- a/spring-boot-modules/spring-boot/src/main/resources/build.properties +++ /dev/null @@ -1,2 +0,0 @@ -application-description=@project.description@ -application-version=@project.version@ \ No newline at end of file diff --git a/spring-boot-modules/spring-boot/src/main/resources/build.yml b/spring-boot-modules/spring-boot/src/main/resources/build.yml deleted file mode 100644 index 528d2e3440..0000000000 --- a/spring-boot-modules/spring-boot/src/main/resources/build.yml +++ /dev/null @@ -1,2 +0,0 @@ -application-description: ^project.description^ -application-version: ^project.version^ \ No newline at end of file diff --git a/spring-boot-modules/spring-boot/src/main/resources/data-expressions.sql b/spring-boot-modules/spring-boot/src/main/resources/data-expressions.sql deleted file mode 100644 index 3e702a759d..0000000000 --- a/spring-boot-modules/spring-boot/src/main/resources/data-expressions.sql +++ /dev/null @@ -1,3 +0,0 @@ -insert into contact_info_expression values ('email','[a-z0-9!#$%&*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?') -insert into contact_info_expression values ('phone','^([0-9]( |-)?)?(\(?[0-9]{3}\)?|[0-9]{3})( |-)?([0-9]{3}( |-)?[0-9]{4}|[a-zA-Z0-9]{7})$') -insert into contact_info_expression values ('website','^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$') \ No newline at end of file diff --git a/spring-boot-modules/spring-boot/src/main/resources/data.sql b/spring-boot-modules/spring-boot/src/main/resources/data.sql deleted file mode 100644 index c44034c739..0000000000 --- a/spring-boot-modules/spring-boot/src/main/resources/data.sql +++ /dev/null @@ -1,5 +0,0 @@ -insert into users values (1, 'Alex', 1); -insert into users values (2, 'Bob', 1); -insert into users values (3, 'John', 0); -insert into users values (4, 'Harry', 0); -insert into users values (5, 'Smith', 1); \ No newline at end of file diff --git a/spring-boot-modules/spring-boot/src/main/resources/demo.properties b/spring-boot-modules/spring-boot/src/main/resources/demo.properties deleted file mode 100644 index 6b4cbeb7a0..0000000000 --- a/spring-boot-modules/spring-boot/src/main/resources/demo.properties +++ /dev/null @@ -1,2 +0,0 @@ -spring.output.ansi.enabled=never -server.port=7070 diff --git a/spring-boot-modules/spring-boot/src/main/resources/logback.xml b/spring-boot-modules/spring-boot/src/main/resources/logback.xml deleted file mode 100644 index 56af2d397e..0000000000 --- a/spring-boot-modules/spring-boot/src/main/resources/logback.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - - - - - - - \ No newline at end of file diff --git a/spring-boot-modules/spring-boot/src/main/resources/persistence-generic-entity.properties b/spring-boot-modules/spring-boot/src/main/resources/persistence-generic-entity.properties deleted file mode 100644 index b19304cb1f..0000000000 --- a/spring-boot-modules/spring-boot/src/main/resources/persistence-generic-entity.properties +++ /dev/null @@ -1,8 +0,0 @@ -jdbc.driverClassName=org.h2.Driver -jdbc.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1 -jdbc.user=sa -jdbc.pass=sa - -hibernate.dialect=org.hibernate.dialect.H2Dialect -hibernate.show_sql=true -hibernate.hbm2ddl.auto=create-drop diff --git a/spring-boot-modules/spring-boot/src/main/resources/public/error/404.html b/spring-boot-modules/spring-boot/src/main/resources/public/error/404.html deleted file mode 100644 index df83ce219b..0000000000 --- a/spring-boot-modules/spring-boot/src/main/resources/public/error/404.html +++ /dev/null @@ -1,8 +0,0 @@ - - - RESOURCE NOT FOUND - - -

404 RESOURCE NOT FOUND

- - \ No newline at end of file diff --git a/spring-boot-modules/spring-boot/src/main/resources/schema-expressions.sql b/spring-boot-modules/spring-boot/src/main/resources/schema-expressions.sql deleted file mode 100644 index 59f6ab05eb..0000000000 --- a/spring-boot-modules/spring-boot/src/main/resources/schema-expressions.sql +++ /dev/null @@ -1,5 +0,0 @@ -create table contact_info_expression( - expression_type varchar(50) not null, - pattern varchar(500) not null, - PRIMARY KEY ( expression_type ) -); \ No newline at end of file diff --git a/spring-boot-modules/spring-boot/src/main/resources/schema.sql b/spring-boot-modules/spring-boot/src/main/resources/schema.sql deleted file mode 100644 index 4cd345c762..0000000000 --- a/spring-boot-modules/spring-boot/src/main/resources/schema.sql +++ /dev/null @@ -1,8 +0,0 @@ -drop table if exists USERS; - -create table USERS( - ID int not null AUTO_INCREMENT, - NAME varchar(100) not null, - STATUS int, - PRIMARY KEY ( ID ) -); \ No newline at end of file diff --git a/spring-boot-modules/spring-boot/src/main/resources/templates/customers.html b/spring-boot-modules/spring-boot/src/main/resources/templates/customers.html deleted file mode 100644 index 5a060d31da..0000000000 --- a/spring-boot-modules/spring-boot/src/main/resources/templates/customers.html +++ /dev/null @@ -1,33 +0,0 @@ - - - - - -
-

- Hello, --name--. -

- - - - - - - - - - - - - - - - - -
IDNameAddressService Rendered
Text ...Text ...Text ...Text...
- -
- - - diff --git a/spring-boot-modules/spring-boot/src/main/resources/templates/error.html b/spring-boot-modules/spring-boot/src/main/resources/templates/error.html deleted file mode 100644 index bc517913b2..0000000000 --- a/spring-boot-modules/spring-boot/src/main/resources/templates/error.html +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - -
-
-

Something went wrong!

- -

Our Engineers are on it.

-

Go Home

-
- - diff --git a/spring-boot-modules/spring-boot/src/main/resources/templates/error/404.html b/spring-boot-modules/spring-boot/src/main/resources/templates/error/404.html deleted file mode 100644 index df83ce219b..0000000000 --- a/spring-boot-modules/spring-boot/src/main/resources/templates/error/404.html +++ /dev/null @@ -1,8 +0,0 @@ - - - RESOURCE NOT FOUND - - -

404 RESOURCE NOT FOUND

- - \ No newline at end of file diff --git a/spring-boot-modules/spring-boot/src/main/resources/templates/external.html b/spring-boot-modules/spring-boot/src/main/resources/templates/external.html deleted file mode 100644 index 2f9cc76961..0000000000 --- a/spring-boot-modules/spring-boot/src/main/resources/templates/external.html +++ /dev/null @@ -1,31 +0,0 @@ - - - - - -
-
-

Customer Portal

-
-
-

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam - erat lectus, vehicula feugiat ultricies at, tempus sed ante. Cras - arcu erat, lobortis vitae quam et, mollis pharetra odio. Nullam sit - amet congue ipsum. Nunc dapibus odio ut ligula venenatis porta non - id dui. Duis nec tempor tellus. Suspendisse id blandit ligula, sit - amet varius mauris. Nulla eu eros pharetra, tristique dui quis, - vehicula libero. Aenean a neque sit amet tellus porttitor rutrum nec - at leo.

- -

Existing Customers

-
- Enter the intranet: customers -
-
- -
- - - - diff --git a/spring-boot-modules/spring-boot/src/main/resources/templates/index.html b/spring-boot-modules/spring-boot/src/main/resources/templates/index.html deleted file mode 100644 index c1314558f6..0000000000 --- a/spring-boot-modules/spring-boot/src/main/resources/templates/index.html +++ /dev/null @@ -1,19 +0,0 @@ - - - WebJars Demo - - - -

Welcome Home

-

-
- × - Success! It is working as we expected. -
-
- - - - - - diff --git a/spring-boot-modules/spring-boot/src/main/resources/templates/layout.html b/spring-boot-modules/spring-boot/src/main/resources/templates/layout.html deleted file mode 100644 index bab0c2982b..0000000000 --- a/spring-boot-modules/spring-boot/src/main/resources/templates/layout.html +++ /dev/null @@ -1,18 +0,0 @@ - - - -Customer Portal - - - - - \ No newline at end of file diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/buildproperties/BuildInfoServiceIntegrationTest.java b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/buildproperties/BuildInfoServiceIntegrationTest.java deleted file mode 100644 index cb056fe56d..0000000000 --- a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/buildproperties/BuildInfoServiceIntegrationTest.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.baeldung.buildproperties; - -import static org.junit.Assert.assertThat; - -import org.hamcrest.Matchers; -import org.junit.jupiter.api.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = Application.class) -class BuildInfoServiceIntegrationTest { - - @Autowired - private BuildInfoService service; - - @Test - void whenGetApplicationDescription_thenSuccess() { - assertThat(service.getApplicationDescription(), Matchers.is("This is simple boot application for Spring boot actuator test")); - assertThat(service.getApplicationVersion(), Matchers.is("0.0.1-SNAPSHOT")); - } -} diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/intro/AppLiveTest.java b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/intro/AppLiveTest.java deleted file mode 100644 index 2785054153..0000000000 --- a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/intro/AppLiveTest.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.baeldung.intro; - -import static org.hamcrest.Matchers.equalTo; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -import org.junit.Test; -import org.junit.runner.RunWith; -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.context.junit4.SpringRunner; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; - -@RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK) -@AutoConfigureMockMvc -public class AppLiveTest { - - @Autowired - private MockMvc mvc; - - @Test - public void getIndex() throws Exception { - mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()).andExpect(content().string(equalTo("Index Page"))); - } - - @Test - public void getLocal() throws Exception { - mvc.perform(MockMvcRequestBuilders.get("/local").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()).andExpect(content().string(equalTo("/local"))); - } - -} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/jsondateformat/ContactAppUnitTest.java b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/jsondateformat/ContactAppUnitTest.java deleted file mode 100644 index 7be85b5e4f..0000000000 --- a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/jsondateformat/ContactAppUnitTest.java +++ /dev/null @@ -1,109 +0,0 @@ -package com.baeldung.jsondateformat; - -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.ObjectMapper; - -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.boot.test.web.client.TestRestTemplate; -import org.springframework.boot.web.server.LocalServerPort; -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.RANDOM_PORT; - -@RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = RANDOM_PORT, classes = ContactApp.class) -@TestPropertySource(properties = { - "spring.jackson.date-format=yyyy-MM-dd HH:mm:ss" -}) -public class ContactAppUnitTest { - - private final ObjectMapper mapper = new ObjectMapper(); - - @Autowired - TestRestTemplate restTemplate; - - @LocalServerPort - int port; - - String url; - - @Before - public void before() { - url=String.format("http://localhost:%s", port); - } - - @Test - public void givenJsonFormatAnnotationAndJava8DateType_whenGet_thenReturnExpectedDateFormat() throws IOException, ParseException { - ResponseEntity response = restTemplate.getForEntity(url + "/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(url + "/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(url + "/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(url + "/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-modules/spring-boot/src/test/java/com/baeldung/jsondateformat/ContactAppWithObjectMapperCustomizerUnitTest.java b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/jsondateformat/ContactAppWithObjectMapperCustomizerUnitTest.java deleted file mode 100644 index 114f9bfc1a..0000000000 --- a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/jsondateformat/ContactAppWithObjectMapperCustomizerUnitTest.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.baeldung.jsondateformat; - -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.ObjectMapper; - -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.boot.test.web.client.TestRestTemplate; -import org.springframework.boot.web.server.LocalServerPort; -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.RANDOM_PORT; - -@RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = RANDOM_PORT, classes = ContactApp.class) -public class ContactAppWithObjectMapperCustomizerUnitTest { - - private final ObjectMapper mapper = new ObjectMapper(); - - @Autowired - TestRestTemplate restTemplate; - - @LocalServerPort - int port; - - String url; - - @Before - public void before() { - url=String.format("http://localhost:%s", port); - } - - @Test - public void givenDefaultDateFormatInAppPropertiesAndLegacyDateType_whenGet_thenReturnExpectedDateFormat() throws IOException { - ResponseEntity response = restTemplate.getForEntity(url + "/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(url + "/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-boot-modules/spring-boot/src/test/java/com/baeldung/repository/UserRepositoryIntegrationTest.java b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/repository/UserRepositoryIntegrationTest.java deleted file mode 100644 index a1318949f3..0000000000 --- a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/repository/UserRepositoryIntegrationTest.java +++ /dev/null @@ -1,73 +0,0 @@ -package com.baeldung.repository; - -import com.baeldung.boot.config.H2JpaConfig; -import com.baeldung.model.User; -import com.baeldung.repository.UserRepository; -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.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import java.util.Optional; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutionException; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Created by adam. - */ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = H2JpaConfig.class) -public class UserRepositoryIntegrationTest { - - private final String USER_NAME_ADAM = "Adam"; - private final Integer ACTIVE_STATUS = 1; - - @Autowired - private UserRepository userRepository; - - @Test - public void givenEmptyDBWhenFindOneByNameThenReturnEmptyOptional() { - Optional foundUser = userRepository.findOneByName(USER_NAME_ADAM); - - assertThat(foundUser.isPresent()).isEqualTo(false); - } - - @Test - public void givenUserInDBWhenFindOneByNameThenReturnOptionalWithUser() { - User user = new User(); - user.setName(USER_NAME_ADAM); - userRepository.save(user); - - Optional foundUser = userRepository.findOneByName(USER_NAME_ADAM); - - assertThat(foundUser.isPresent()).isEqualTo(true); - - assertThat(foundUser - .get() - .getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test - public void givenUserInDBWhenFindOneByStatusAsyncThenReturnCompletableFutureUser() throws ExecutionException, InterruptedException { - User user = new User(); - user.setName(USER_NAME_ADAM); - user.setStatus(ACTIVE_STATUS); - userRepository.save(user); - - CompletableFuture userByStatus = userRepository.findOneByStatus(ACTIVE_STATUS); - - assertThat(userByStatus - .get() - .getName()).isEqualTo(USER_NAME_ADAM); - } - - @After - public void cleanUp() { - userRepository.deleteAll(); - } - -} diff --git a/spring-boot-modules/spring-boot/src/test/resources/README.md b/spring-boot-modules/spring-boot/src/test/resources/README.md deleted file mode 100644 index 51c95afd9d..0000000000 --- a/spring-boot-modules/spring-boot/src/test/resources/README.md +++ /dev/null @@ -1,3 +0,0 @@ -### Relevant Articles: - -- [How to Test GraphQL Using Postman](https://www.baeldung.com/graphql-postman) diff --git a/spring-boot-modules/spring-boot/src/test/resources/application.properties b/spring-boot-modules/spring-boot/src/test/resources/application.properties deleted file mode 100644 index 9ad65e1815..0000000000 --- a/spring-boot-modules/spring-boot/src/test/resources/application.properties +++ /dev/null @@ -1,19 +0,0 @@ -spring.mail.host=localhost -spring.mail.port=8025 -spring.mail.properties.mail.smtp.auth=false - - -# spring.datasource.x -spring.datasource.driver-class-name=org.h2.Driver -spring.datasource.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1 -spring.datasource.username=sa -spring.datasource.password=sa - -# hibernate.X -spring.jpa.hibernate.dialect=org.hibernate.dialect.H2Dialect -spring.jpa.hibernate.ddl-auto=create-drop -spring.jpa.hibernate.show_sql=true -spring.jpa.hibernate.hbm2ddl.auto=create-drop -spring.jpa.hibernate.cache.use_second_level_cache=true -spring.jpa.hibernate.cache.use_query_cache=true -spring.jpa.hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.EhCacheRegionFactory diff --git a/spring-boot-modules/spring-boot/src/test/resources/conversion.properties b/spring-boot-modules/spring-boot/src/test/resources/conversion.properties deleted file mode 100644 index 640442ec33..0000000000 --- a/spring-boot-modules/spring-boot/src/test/resources/conversion.properties +++ /dev/null @@ -1,11 +0,0 @@ -###### time unit -conversion.timeInDefaultUnit=10 -conversion.timeInNano=9ns -conversion.timeInDays=2 - -###### data size -conversion.sizeInDefaultUnit=300 -conversion.sizeInGB=2GB -conversion.sizeInTB=4 - -conversion.employee=john,2000 \ No newline at end of file diff --git a/spring-boot-modules/spring-boot/src/test/resources/import.sql b/spring-boot-modules/spring-boot/src/test/resources/import.sql deleted file mode 100644 index 9095b9468c..0000000000 --- a/spring-boot-modules/spring-boot/src/test/resources/import.sql +++ /dev/null @@ -1 +0,0 @@ ---insert into Foo values(1,'Foo_Name'); \ No newline at end of file diff --git a/spring-boot-modules/spring-boot/src/test/resources/org/baeldung/boot/expected.json b/spring-boot-modules/spring-boot/src/test/resources/org/baeldung/boot/expected.json deleted file mode 100644 index f5409421a6..0000000000 --- a/spring-boot-modules/spring-boot/src/test/resources/org/baeldung/boot/expected.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "id":3, - "name":"Foo_Name_3" -} \ No newline at end of file diff --git a/spring-cloud/pom.xml b/spring-cloud/pom.xml index a2c4b3509f..9205416cd5 100644 --- a/spring-cloud/pom.xml +++ b/spring-cloud/pom.xml @@ -45,7 +45,7 @@ spring-cloud-ribbon-retry spring-cloud-circuit-breaker spring-cloud-eureka-self-preservation - + spring-cloud-openfeign spring-cloud-netflix-feign spring-cloud-sentinel spring-cloud-dapr diff --git a/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client-profiles/pom.xml b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client-profiles/pom.xml new file mode 100644 index 0000000000..23e06a55f9 --- /dev/null +++ b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client-profiles/pom.xml @@ -0,0 +1,48 @@ + + + 4.0.0 + spring-cloud-eureka-client-profiles + 1.0.0-SNAPSHOT + spring-cloud-eureka-client-profiles + jar + Spring Cloud Eureka Sample Client + + + com.baeldung.spring.cloud + spring-cloud-eureka + 1.0.0-SNAPSHOT + + + + + + org.junit + junit-bom + ${junit-jupiter.version} + pom + import + + + org.springframework.cloud + spring-cloud-starter-parent + ${spring-cloud-dependencies.version} + pom + import + + + + + + + org.springframework.cloud + spring-cloud-starter-netflix-eureka-client + + + org.springframework.boot + spring-boot-starter-web + + + + \ No newline at end of file diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/jsondateformat/ContactApp.java b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client-profiles/src/main/java/com/baeldung/spring/cloud/eureka/client/EurekaClientApplication.java similarity index 56% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/jsondateformat/ContactApp.java rename to spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client-profiles/src/main/java/com/baeldung/spring/cloud/eureka/client/EurekaClientApplication.java index 79037e1038..854bab97e7 100644 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/jsondateformat/ContactApp.java +++ b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client-profiles/src/main/java/com/baeldung/spring/cloud/eureka/client/EurekaClientApplication.java @@ -1,13 +1,13 @@ -package com.baeldung.jsondateformat; +package com.baeldung.spring.cloud.eureka.client; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication -public class ContactApp { +public class EurekaClientApplication { public static void main(String[] args) { - SpringApplication.run(ContactApp.class, args); + SpringApplication.run(EurekaClientApplication.class, args); } } diff --git a/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client-profiles/src/main/java/com/baeldung/spring/cloud/eureka/client/controller/HelloWorldController.java b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client-profiles/src/main/java/com/baeldung/spring/cloud/eureka/client/controller/HelloWorldController.java new file mode 100644 index 0000000000..d0d0a6ec9f --- /dev/null +++ b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client-profiles/src/main/java/com/baeldung/spring/cloud/eureka/client/controller/HelloWorldController.java @@ -0,0 +1,13 @@ +package com.baeldung.spring.cloud.eureka.client.controller; + +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class HelloWorldController { + + @RequestMapping("/hello") + public String hello() { + return "Hello World!"; + } +} diff --git a/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client-profiles/src/main/resources/application-dev.properties b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client-profiles/src/main/resources/application-dev.properties new file mode 100644 index 0000000000..c565e42678 --- /dev/null +++ b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client-profiles/src/main/resources/application-dev.properties @@ -0,0 +1,2 @@ +server.port=8080 +spring.cloud.discovery.enabled=false \ No newline at end of file diff --git a/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client-profiles/src/main/resources/application.properties b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client-profiles/src/main/resources/application.properties new file mode 100644 index 0000000000..3cfecbbf08 --- /dev/null +++ b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client-profiles/src/main/resources/application.properties @@ -0,0 +1,9 @@ +server.port=8080 + +eureka.client.serviceUrl.defaultZone=${EUREKA_URI:http://localhost:8761/eureka} +eureka.instance.preferIpAddress=false + +spring.application.name=spring-cloud-eureka-client +#--- +spring.config.activate.on-profile=dev +spring.cloud.discovery.enabled=false \ No newline at end of file diff --git a/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client-profiles/src/test/java/com/baeldung/spring/cloud/eureka/client/SpringContextTest.java b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client-profiles/src/test/java/com/baeldung/spring/cloud/eureka/client/SpringContextTest.java new file mode 100644 index 0000000000..a3ed012abb --- /dev/null +++ b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client-profiles/src/test/java/com/baeldung/spring/cloud/eureka/client/SpringContextTest.java @@ -0,0 +1,16 @@ +package com.baeldung.spring.cloud.eureka.client; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } + +} diff --git a/spring-cloud/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/OpenfeignManualTest.java b/spring-cloud/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/OpenFeignManualTest.java similarity index 96% rename from spring-cloud/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/OpenfeignManualTest.java rename to spring-cloud/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/OpenFeignManualTest.java index 8ae6883519..4eb014de96 100644 --- a/spring-cloud/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/OpenfeignManualTest.java +++ b/spring-cloud/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/OpenFeignManualTest.java @@ -15,7 +15,7 @@ import static org.junit.Assert.assertNotNull; @RunWith(SpringRunner.class) @SpringBootTest -public class OpenfeignManualTest { +public class OpenFeignManualTest { @Autowired private JSONPlaceHolderService jsonPlaceHolderService; diff --git a/spring-cloud/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/OpenFeignOAuth2ManualTest.java b/spring-cloud/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/OpenFeignOAuth2ManualTest.java new file mode 100644 index 0000000000..8084fd23cd --- /dev/null +++ b/spring-cloud/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/OpenFeignOAuth2ManualTest.java @@ -0,0 +1,44 @@ +package com.baeldung.cloud.openfeign; + +import com.baeldung.cloud.openfeign.client.PaymentClient; +import com.baeldung.cloud.openfeign.model.Payment; +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.test.context.junit4.SpringRunner; + +import java.util.List; + +import static org.junit.Assert.assertFalse; + +/** + * This test can be used to verify OAuth2 Token functionality with Feign client + * (https://www.baeldung.com/spring-cloud-feign-oauth-token). + * + * The following components should be setup and running, as described in the article, prior to running this test. + * + * Authorization Server - embedded Keycloak server with the correct client and client-secret defined in the master realm. + * This will issue the auth tokens used by Feign client. + * Further details are available at: https://www.baeldung.com/keycloak-embedded-in-spring-boot-app + * + * Resource Server - OAuth resource server requiring valid JWT token (issued by the Authorization Server). + * Further details are available at: https://www.baeldung.com/spring-security-oauth-resource-server + * + */ +@RunWith(SpringRunner.class) +@SpringBootTest +public class OpenFeignOAuth2ManualTest { + + @Autowired + private PaymentClient paymentClient; + + @Test + public void whenGetPayment_thenListPayments() { + + List payments = paymentClient.getPayments(); + + assertFalse(payments.isEmpty()); + } + +} diff --git a/spring-cloud/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/PaymentClientUnitTest.java b/spring-cloud/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/PaymentClientUnitTest.java deleted file mode 100644 index 0372728515..0000000000 --- a/spring-cloud/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/PaymentClientUnitTest.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.baeldung.cloud.openfeign; - -import com.baeldung.cloud.openfeign.client.PaymentClient; -import com.baeldung.cloud.openfeign.model.Payment; -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.test.context.junit4.SpringRunner; - -import java.util.List; - -import static org.junit.Assert.assertFalse; - -@RunWith(SpringRunner.class) -@SpringBootTest -public class PaymentClientUnitTest { - - @Autowired - private PaymentClient paymentClient; - - @Test - public void whenGetPayment_thenListPayments() { - - List payments = paymentClient.getPayments(); - - assertFalse(payments.isEmpty()); - } - -} diff --git a/spring-core-5/README.md b/spring-core-5/README.md index b6c9ba606a..ebf62ac24f 100644 --- a/spring-core-5/README.md +++ b/spring-core-5/README.md @@ -10,4 +10,5 @@ This module contains articles about core Spring functionality. - [AliasFor Annotation in Spring](https://www.baeldung.com/spring-aliasfor-annotation) - [A Quick Guide to the Spring @Lazy Annotation](https://www.baeldung.com/spring-lazy-annotation) - [Finding the Spring Version](https://www.baeldung.com/spring-find-version) +- [How Does the Spring Singleton Bean Serve Concurrent Requests?](https://www.baeldung.com/spring-singleton-concurrent-requests) - More articles: [[<-- prev]](../spring-core-4)