Compare commits

..

No commits in common. "main" and "0.1.0" have entirely different histories.
main ... 0.1.0

37 changed files with 693 additions and 889 deletions

10
.gitignore vendored
View File

@ -31,13 +31,3 @@ build/
### VS Code ###
.vscode/
.DS_Store/
.DS_Store
gradle.properties
gradlew
gradlew.bat
gradle/
**/.gradle
**/build

View File

@ -1,21 +1,4 @@
include:
- project: 'gitlab/gitlab'
ref: 'main'
file: 'ci-templates/gradle_java.yml'
deploy:
stage: deploy
tags:
- dind
script:
- echo "Building with gradle version ${BUILDVERSION}"
- gradle -Pversion=${BUILDVERSION} publish
- echo "BUILDVERSION=$BUILDVERSION" >> version.env
artifacts:
reports:
dotenv: version.env
rules:
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
- if: $CI_COMMIT_BRANCH =~ /^release/
- if: $CI_COMMIT_BRANCH =~ /^feature/
- if: $CI_COMMIT_TAG
file: 'ci-templates/maven_deps.yml'

View File

@ -1,116 +0,0 @@
plugins {
`java-library`
`maven-publish`
pmd
checkstyle
jacoco
id("io.freefair.lombok") version "8.4"
id("org.sonarqube") version "4.0.0.2929"
}
repositories {
mavenLocal()
maven {
url = uri("https://nexus.knecon.com/repository/gindev/");
credentials {
username = providers.gradleProperty("mavenUser").getOrNull();
password = providers.gradleProperty("mavenPassword").getOrNull();
}
}
mavenCentral()
}
val springBootVersion = "3.1.5"
val springCloudVersion = "4.0.4"
val springRabbitTest = "3.0.9"
val testContainersVersion = "1.20.1"
dependencies {
api("com.fasterxml.jackson.core:jackson-databind:2.15.2:")
api("com.knecon.fforesight:tenant-commons:0.31.0-RED10196.0")
api("com.zaxxer:HikariCP:5.0.1")
api("com.google.guava:guava:32.1.2-jre")
api("org.liquibase:liquibase-core:4.29.2")
api("org.springframework.boot:spring-boot-starter-data-jpa:${springBootVersion}")
api("org.springframework.cloud:spring-cloud-starter-openfeign:${springCloudVersion}")
api("org.springframework.boot:spring-boot-starter-amqp:${springBootVersion}")
api("org.postgresql:postgresql:42.6.0")
api("org.springframework.boot:spring-boot-configuration-processor:${springBootVersion}")
api("org.springframework.boot:spring-boot-actuator:${springBootVersion}")
api("org.projectlombok:lombok:1.18.28")
runtimeOnly("org.springframework.boot:spring-boot-devtools:${springBootVersion}")
testImplementation("org.springframework.boot:spring-boot-starter-test:${springBootVersion}")
testImplementation("org.testcontainers:postgresql:${testContainersVersion}")
testImplementation("org.springframework.amqp:spring-rabbit-test:${springRabbitTest}")
testImplementation("org.testcontainers:rabbitmq:${testContainersVersion}")
}
group = "com.knecon.fforesight"
description = "database-tenant-commons"
java.sourceCompatibility = JavaVersion.VERSION_17
java.targetCompatibility = JavaVersion.VERSION_17
publishing {
publications {
create<MavenPublication>("mavenJava") {
from(components["java"])
}
}
repositories {
maven {
url = uri("https://nexus.knecon.com/repository/red-platform-releases/")
credentials {
username = providers.gradleProperty("mavenUser").getOrNull();
password = providers.gradleProperty("mavenPassword").getOrNull();
}
}
}
}
tasks.withType<PublishToMavenRepository> {
onlyIf { publication.name == "mavenJava" }
}
pmd {
isConsoleOutput = true
}
tasks.pmdMain {
pmd.ruleSetFiles = files("${rootDir}/config/pmd/pmd.xml")
}
tasks.pmdTest {
pmd.ruleSetFiles = files("${rootDir}/config/pmd/test_pmd.xml")
}
tasks.named<Test>("test") {
useJUnitPlatform()
reports {
junitXml.outputLocation.set(layout.buildDirectory.dir("reports/junit"))
}
}
sonarqube {
properties {
providers.gradleProperty("sonarToken").getOrNull()?.let { property("sonar.login", it) }
property("sonar.host.url", "https://sonarqube.knecon.com")
}
}
tasks.test {
finalizedBy(tasks.jacocoTestReport)
}
tasks.jacocoTestReport {
dependsOn(tasks.test)
reports {
xml.required.set(true)
csv.required.set(false)
html.outputLocation.set(layout.buildDirectory.dir("jacocoHtml"))
}
}
java {
withJavadocJar()
}

View File

@ -1,39 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE module PUBLIC "-//Puppy Crawl//DTD Check Configuration 1.3//EN"
"http://www.puppycrawl.com/dtds/configuration_1_3.dtd">
<module name="Checker">
<property
name="severity"
value="error"/>
<module name="TreeWalker">
<module name="SuppressWarningsHolder"/>
<module name="MissingDeprecated"/>
<module name="MissingOverride"/>
<module name="AnnotationLocation"/>
<module name="JavadocStyle"/>
<module name="NonEmptyAtclauseDescription"/>
<module name="IllegalImport"/>
<module name="RedundantImport"/>
<module name="RedundantModifier"/>
<module name="EmptyBlock"/>
<module name="DefaultComesLast"/>
<module name="EmptyStatement"/>
<module name="EqualsHashCode"/>
<module name="ExplicitInitialization"/>
<module name="IllegalInstantiation"/>
<module name="ModifiedControlVariable"/>
<module name="MultipleVariableDeclarations"/>
<module name="PackageDeclaration"/>
<module name="ParameterAssignment"/>
<module name="SimplifyBooleanExpression"/>
<module name="SimplifyBooleanReturn"/>
<module name="StringLiteralEquality"/>
<module name="OneStatementPerLine"/>
<module name="FinalClass"/>
<module name="ArrayTypeStyle"/>
<module name="UpperEll"/>
<module name="OuterTypeFilename"/>
</module>
<module name="FileTabCharacter"/>
<module name="SuppressWarningsFilter"/>
</module>

View File

@ -1,20 +0,0 @@
<?xml version="1.0"?>
<ruleset name="Custom ruleset"
xmlns="http://pmd.sourceforge.net/ruleset/2.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://pmd.sourceforge.net/ruleset/2.0.0 http://pmd.sourceforge.net/ruleset_2_0_0.xsd">
<description>
Knecon ruleset checks the code for bad stuff
</description>
<rule ref="category/java/errorprone.xml">
<exclude name="MissingSerialVersionUID"/>
<exclude name="AvoidLiteralsInIfCondition"/>
<exclude name="AvoidDuplicateLiterals"/>
<exclude name="NullAssignment"/>
<exclude name="AssignmentInOperand"/>
<exclude name="BeanMembersShouldSerialize"/>
</rule>
</ruleset>

View File

@ -1,22 +0,0 @@
<?xml version="1.0"?>
<ruleset name="Custom ruleset"
xmlns="http://pmd.sourceforge.net/ruleset/2.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://pmd.sourceforge.net/ruleset/2.0.0 http://pmd.sourceforge.net/ruleset_2_0_0.xsd">
<description>
Knecon test ruleset checks the code for bad stuff
</description>
<rule ref="category/java/errorprone.xml">
<exclude name="MissingSerialVersionUID"/>
<exclude name="AvoidLiteralsInIfCondition"/>
<exclude name="AvoidDuplicateLiterals"/>
<exclude name="NullAssignment"/>
<exclude name="AssignmentInOperand"/>
<exclude name="TestClassWithoutTestCases"/>
<exclude name="BeanMembersShouldSerialize"/>
</rule>
</ruleset>

View File

@ -1 +0,0 @@
version = 0.2-SNAPSHOT

316
mvnw vendored Executable file
View File

@ -0,0 +1,316 @@
#!/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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Maven 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 /usr/local/etc/mavenrc ] ; then
. /usr/local/etc/mavenrc
fi
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)`"
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="`\\unset -f command; \\command -v 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
##########################################################################################
# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
# This allows using the maven wrapper in projects that prohibit checking in binary data.
##########################################################################################
if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found .mvn/wrapper/maven-wrapper.jar"
fi
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..."
fi
if [ -n "$MVNW_REPOURL" ]; then
jarUrl="$MVNW_REPOURL/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar"
else
jarUrl="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar"
fi
while IFS="=" read key value; do
case "$key" in (wrapperUrl) jarUrl="$value"; break ;;
esac
done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties"
if [ "$MVNW_VERBOSE" = true ]; then
echo "Downloading from: $jarUrl"
fi
wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar"
if $cygwin; then
wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"`
fi
if command -v wget > /dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found wget ... using wget"
fi
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
wget "$jarUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath"
else
wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath"
fi
elif command -v curl > /dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found curl ... using curl"
fi
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
curl -o "$wrapperJarPath" "$jarUrl" -f
else
curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f
fi
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Falling back to using Java to download"
fi
javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java"
# For Cygwin, switch paths to Windows format before running javac
if $cygwin; then
javaClass=`cygpath --path --windows "$javaClass"`
fi
if [ -e "$javaClass" ]; then
if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Compiling MavenWrapperDownloader.java ..."
fi
# Compiling the Java class
("$JAVA_HOME/bin/javac" "$javaClass")
fi
if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
# Running the downloader
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Running MavenWrapperDownloader.java ..."
fi
("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR")
fi
fi
fi
fi
##########################################################################################
# End of extension
##########################################################################################
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
# Provide a "standardized" way to retrieve the CLI args that will
# work with both Windows and non-Windows executions.
MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@"
export MAVEN_CMD_LINE_ARGS
WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
exec "$JAVACMD" \
$MAVEN_OPTS \
$MAVEN_DEBUG_OPTS \
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
"-Dmaven.home=${M2_HOME}" \
"-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"

188
mvnw.cmd vendored Normal file
View File

@ -0,0 +1,188 @@
@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 https://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 Maven 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 keystroke 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 by 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 "%USERPROFILE%\mavenrc_pre.bat" call "%USERPROFILE%\mavenrc_pre.bat" %*
if exist "%USERPROFILE%\mavenrc_pre.cmd" call "%USERPROFILE%\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
set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar"
FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B
)
@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
if exist %WRAPPER_JAR% (
if "%MVNW_VERBOSE%" == "true" (
echo Found %WRAPPER_JAR%
)
) else (
if not "%MVNW_REPOURL%" == "" (
SET DOWNLOAD_URL="%MVNW_REPOURL%/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar"
)
if "%MVNW_VERBOSE%" == "true" (
echo Couldn't find %WRAPPER_JAR%, downloading it ...
echo Downloading from: %DOWNLOAD_URL%
)
powershell -Command "&{"^
"$webclient = new-object System.Net.WebClient;"^
"if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^
"$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^
"}"^
"[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^
"}"
if "%MVNW_VERBOSE%" == "true" (
echo Finished downloading %WRAPPER_JAR%
)
)
@REM End of extension
@REM Provide a "standardized" way to retrieve the CLI args that will
@REM work with both Windows and non-Windows executions.
set MAVEN_CMD_LINE_ARGS=%*
%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 "%USERPROFILE%\mavenrc_post.bat" call "%USERPROFILE%\mavenrc_post.bat"
if exist "%USERPROFILE%\mavenrc_post.cmd" call "%USERPROFILE%\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%
cmd /C exit /B %ERROR_CODE%

99
pom.xml Normal file
View File

@ -0,0 +1,99 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.0.6</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.knecon.fforesight</groupId>
<artifactId>database-tenant-commons</artifactId>
<version>0.1-SNAPSHOT</version>
<name>database-tenant-commons</name>
<description>database-tenant-commons</description>
<properties>
<java.version>17</java.version>
<spring-cloud.version>2022.0.2</spring-cloud.version>
<storage-commons.version>2.1.0</storage-commons.version>
<tenant-commons.version>0.10.0</tenant-commons.version>
<guava.version>32.1.0-jre</guava.version>
</properties>
<dependencies>
<dependency>
<groupId>com.knecon.fforesight</groupId>
<artifactId>tenant-commons</artifactId>
<version>${tenant-commons.version}</version>
</dependency>
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>org.liquibase</groupId>
<artifactId>liquibase-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>${postgresql.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-actuator</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.amqp</groupId>
<artifactId>spring-rabbit-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
</project>

View File

@ -1,6 +0,0 @@
{
"$schema": "https://docs.renovatebot.com/renovate-schema.json",
"extends": [
"config:base"
]
}

View File

@ -1,5 +0,0 @@
/*
* This file was generated by the Gradle 'init' task.
*/
rootProject.name = "database-tenant-commons"

View File

@ -1,20 +1,14 @@
package com.knecon.fforesight.databasetenantcommons;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.boot.autoconfigure.liquibase.LiquibaseProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.ComponentScan;
import com.knecon.fforesight.databasetenantcommons.providers.properties.TenantHikariSettings;
import com.knecon.fforesight.tenantcommons.MultiTenancyAutoConfiguration;
@ComponentScan
@AutoConfiguration
@AutoConfigureAfter(MultiTenancyAutoConfiguration.class)
@ImportAutoConfiguration(MultiTenancyAutoConfiguration.class)
@EnableConfigurationProperties({TenantHikariSettings.class, LiquibaseProperties.class})
@EnableConfigurationProperties(TenantHikariSettings.class)
public class DatabaseTenantCommonsAutoConfiguration {
}

View File

@ -0,0 +1,52 @@
package com.knecon.fforesight.databasetenantcommons;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.QueueBuilder;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import lombok.RequiredArgsConstructor;
@Configuration
@RequiredArgsConstructor
public class TenantMessagingConfiguration {
@Value("${fforesight.multitenancy.tenant-created-queue:tenant-created}")
private String tenantCreatedEventQueue;
@Value("${fforesight.multitenancy.tenant-created-dlq:tenant-created-dlq}")
private String tenantCreatedDLQ;
@Bean("persistenceServiceTenantCreatedQueue")
public Queue persistenceServiceTenantCreatedQueue() {
return QueueBuilder.durable(tenantCreatedEventQueue)
.withArgument("x-dead-letter-exchange", "").withArgument("x-dead-letter-routing-key", tenantCreatedDLQ).build();
}
@Bean
public Queue persistenceServiceTenantDLQ() {
return QueueBuilder.durable(tenantCreatedEventQueue).build();
}
@Bean
public Binding tenantExchangeBinding(@Qualifier("persistenceServiceTenantCreatedQueue") Queue persistenceServiceTenantCreatedQueue,
@Qualifier("tenantExchange") TopicExchange tenantExchange) {
return BindingBuilder.bind(persistenceServiceTenantCreatedQueue).to(tenantExchange).with("tenant.created");
}
@Bean(name = "tenantExchange")
TopicExchange tenantExchange(@Value("${fforesight.tenant-exchange.name}") String tenantExchangeName) {
return new TopicExchange(tenantExchangeName);
}
}

View File

@ -28,7 +28,6 @@ import lombok.extern.slf4j.Slf4j;
@Slf4j
@Component
@RequiredArgsConstructor
@SuppressWarnings("PMD")
public class DynamicDataSourceBasedMultiTenantConnectionProvider extends AbstractDataSourceBasedMultiTenantConnectionProviderImpl {
private static final String TENANT_POOL_NAME_SUFFIX = "DataSource";
@ -43,9 +42,6 @@ public class DynamicDataSourceBasedMultiTenantConnectionProvider extends Abstrac
@Value("${multitenancy.datasource-cache.expireAfterAccess:10}")
private Integer expireAfterAccess;
@Value("${spring.application.name:}")
private String applicationName;
private LoadingCache<String, SchemaConnection> connectionPerTenant;
private LoadingCache<SchemaConnection, DataSource> dataSourcePerConnectionString;
@ -58,7 +54,7 @@ public class DynamicDataSourceBasedMultiTenantConnectionProvider extends Abstrac
public SchemaConnection load(String key) {
var tenant = tenantProvider.getTenant(key);
var jdbcUrl = JDBCUtils.buildJdbcUrl(tenant.getDatabaseConnection(), applicationName + "-multitenant");
var jdbcUrl = JDBCUtils.buildJdbcUrl(tenant.getDatabaseConnection());
return SchemaConnection.builder().jdbcUrl(jdbcUrl).databaseConnection(tenant.getDatabaseConnection()).build();
}
});
@ -89,7 +85,7 @@ public class DynamicDataSourceBasedMultiTenantConnectionProvider extends Abstrac
tenantHikariSettings.setUsername(connection.getDatabaseConnection().getUsername());
tenantHikariSettings.setPassword(decryptedPassword);
var jdbcUrl = JDBCUtils.buildJdbcUrl(connection.getDatabaseConnection(), applicationName + "-multitenant");
var jdbcUrl = JDBCUtils.buildJdbcUrl(connection.getDatabaseConnection());
tenantHikariSettings.setJdbcUrl(jdbcUrl);
tenantHikariSettings.setPoolName(jdbcUrl + TENANT_POOL_NAME_SUFFIX);

View File

@ -3,12 +3,10 @@ package com.knecon.fforesight.databasetenantcommons.providers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.jdbc.DataSourceHealthIndicator;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
@Primary
@Component
public class MultiTenantDataSourceHealthIndicator extends DataSourceHealthIndicator {
public class MultiTenantDataSourceHealthIndicator extends DataSourceHealthIndicator {
@Autowired
private MultiTenantDataSource multiTenantDataSource;
@ -23,7 +21,7 @@ public class MultiTenantDataSourceHealthIndicator extends DataSourceHealthIndica
@Override
protected void doHealthCheck(Health.Builder builder) {
protected void doHealthCheck(Health.Builder builder) throws Exception {
builder.up().withDetail("database", "multi-tenant-setup");
}

View File

@ -1,31 +0,0 @@
package com.knecon.fforesight.databasetenantcommons.providers;
import org.springframework.stereotype.Service;
import com.knecon.fforesight.tenantcommons.listener.ITenantEventHandler;
import com.knecon.fforesight.tenantcommons.model.TenantCreatedEvent;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@Service
@RequiredArgsConstructor
public class TenantCreatedDatabaseEventHandler implements ITenantEventHandler<TenantCreatedEvent> {
private final TenantLiquibaseInitializer tenantLiquibaseInitializer;
@Override
public void handle(TenantCreatedEvent tenantCreatedEvent) {
tenantLiquibaseInitializer.initializeTenant(tenantCreatedEvent.getTenantId());
}
@Override
public Class<TenantCreatedEvent> getEventClass() {
return TenantCreatedEvent.class;
}
}

View File

@ -1,5 +1,6 @@
package com.knecon.fforesight.databasetenantcommons.providers;
import java.net.URI;
import java.net.URISyntaxException;
import java.sql.Connection;
@ -9,16 +10,18 @@ import java.util.Set;
import javax.sql.DataSource;
import org.postgresql.util.PSQLException;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.liquibase.LiquibaseProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.core.io.ResourceLoader;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.StatementCallback;
import org.springframework.jdbc.datasource.SingleConnectionDataSource;
import org.springframework.stereotype.Service;
import com.knecon.fforesight.databasetenantcommons.providers.events.TenantCreatedEvent;
import com.knecon.fforesight.databasetenantcommons.providers.utils.JDBCUtils;
import com.knecon.fforesight.tenantcommons.EncryptionDecryptionService;
import com.knecon.fforesight.tenantcommons.TenantProvider;
@ -31,7 +34,8 @@ import lombok.extern.slf4j.Slf4j;
@Slf4j
@Service
public class TenantLiquibaseInitializer {
@EnableConfigurationProperties(LiquibaseProperties.class)
public class TenantCreatedListener {
private static final Set<String> SUPPORTED_DATABASES = Set.of("postgresql");
private static final Set<String> SQL_CONNECTION_ERROR_CODES = Set.of(
@ -50,15 +54,12 @@ public class TenantLiquibaseInitializer {
private final TenantProvider tenantProvider;
private final EncryptionDecryptionService encryptionDecryptionService;
@Value("${spring.application.name:}")
private String applicationName;
public TenantLiquibaseInitializer(@Qualifier("tenantLiquibaseProperties") LiquibaseProperties liquibaseProperties,
ResourceLoader resourceLoader,
EncryptionDecryptionService encryptionDecryptionService,
@Autowired(required = false) MigrationService migrationService,
TenantProvider tenantProvider) {
public TenantCreatedListener(@Qualifier("tenantLiquibaseProperties") LiquibaseProperties liquibaseProperties,
ResourceLoader resourceLoader,
EncryptionDecryptionService encryptionDecryptionService,
@Autowired(required = false) MigrationService migrationService,
TenantProvider tenantProvider) {
this.liquibaseProperties = liquibaseProperties;
this.resourceLoader = resourceLoader;
@ -69,9 +70,10 @@ public class TenantLiquibaseInitializer {
@SneakyThrows
public synchronized void initializeTenant(String tenantId) {
@RabbitListener(queues = "${fforesight.multitenancy.tenant-created-queue:tenant-created}")
public void createTenant(TenantCreatedEvent tenantRequest) {
var tenant = tenantProvider.getTenant(tenantId);
var tenant = tenantProvider.getTenant(tenantRequest.getTenantId());
createSchema(tenant);
@ -89,7 +91,7 @@ public class TenantLiquibaseInitializer {
}
if (migrationService != null) {
migrationService.runForTenant(tenantId);
migrationService.runForTenant(tenantRequest.getTenantId());
}
}
@ -97,7 +99,7 @@ public class TenantLiquibaseInitializer {
private void createSchema(TenantResponse tenantRequest) {
var jdbcUrl = JDBCUtils.buildJdbcUrl(tenantRequest.getDatabaseConnection(), applicationName + "-liquibase");
var jdbcUrl = JDBCUtils.buildJdbcUrl(tenantRequest.getDatabaseConnection());
try (Connection connection = DriverManager.getConnection(jdbcUrl,
tenantRequest.getDatabaseConnection().getUsername(),
encryptionDecryptionService.decrypt(tenantRequest.getDatabaseConnection().getPassword()))) {
@ -163,7 +165,6 @@ public class TenantLiquibaseInitializer {
liquibase.setDataSource(dataSource);
liquibase.setChangeLog(liquibaseProperties.getChangeLog());
liquibase.setContexts(liquibaseProperties.getContexts());
liquibase.setClearCheckSums(liquibaseProperties.isClearChecksums());
return liquibase;
}

View File

@ -1,95 +0,0 @@
package com.knecon.fforesight.databasetenantcommons.providers;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.hibernate.cfg.AvailableSettings;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.boot.autoconfigure.liquibase.LiquibaseProperties;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.hibernate5.SpringBeanContainer;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import com.knecon.fforesight.databasetenantcommons.providers.properties.TenantHikariSettings;
import com.knecon.fforesight.tenantcommons.EncryptionDecryptionService;
import com.knecon.fforesight.tenantcommons.TenantProvider;
import jakarta.persistence.EntityManagerFactory;
import lombok.RequiredArgsConstructor;
@Configuration
@EnableJpaRepositories(basePackages ="${multitenancy.packages.repositories:}", entityManagerFactoryRef = "tenantEntityManagerFactory", transactionManagerRef = "tenantTransactionManager")
@EnableConfigurationProperties({JpaProperties.class, TenantHikariSettings.class})
@RequiredArgsConstructor
public class TenantPersistenceConfig {
@Value("${multitenancy.packages.entities:}")
private String[] entityPackages;
private final JpaProperties jpaProperties;
@Primary
@Bean
public LocalContainerEntityManagerFactoryBean tenantEntityManagerFactory(DynamicDataSourceBasedMultiTenantConnectionProvider connectionProvider,
CurrentTenantIdentifierResolverImpl tenantResolver) {
LocalContainerEntityManagerFactoryBean emfBean = new LocalContainerEntityManagerFactoryBean();
emfBean.setPersistenceUnitName("tenant-persistence-unit");
emfBean.setPackagesToScan(entityPackages!=null ? entityPackages : new String[0]);
emfBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
Map<String, Object> properties = new HashMap<>(this.jpaProperties.getProperties());
properties.put(AvailableSettings.PHYSICAL_NAMING_STRATEGY, "org.hibernate.boot.model.naming.CamelCaseToUnderscoresNamingStrategy");
properties.put(AvailableSettings.IMPLICIT_NAMING_STRATEGY, "org.springframework.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy");
// properties.put(AvailableSettings.MULTI_TENANT, MultiTenancyStrategy.DATABASE);
properties.put(AvailableSettings.MULTI_TENANT_CONNECTION_PROVIDER, connectionProvider);
properties.put(AvailableSettings.MULTI_TENANT_IDENTIFIER_RESOLVER, tenantResolver);
properties.put(AvailableSettings.DIALECT, "org.hibernate.dialect.PostgreSQLDialect");
properties.put("hibernate.temp.use_jdbc_metadata_defaults",false);
emfBean.setJpaPropertyMap(properties);
return emfBean;
}
@Primary
@Bean
public JpaTransactionManager tenantTransactionManager(@Qualifier("tenantEntityManagerFactory") EntityManagerFactory emf) {
JpaTransactionManager tenantTransactionManager = new JpaTransactionManager();
tenantTransactionManager.setEntityManagerFactory(emf);
return tenantTransactionManager;
}
@Bean
@ConfigurationProperties("multitenancy.tenant.liquibase")
public LiquibaseProperties tenantLiquibaseProperties() {
return new LiquibaseProperties();
}
@Bean
public TenantSpringLiquibaseExecutor tenantLiquibase(EncryptionDecryptionService encryptionService,
TenantProvider tenantProvider,
LiquibaseProperties tenantLiquibaseProperties) {
return new TenantSpringLiquibaseExecutor(encryptionService, tenantProvider, tenantLiquibaseProperties);
}
}

View File

@ -1,88 +0,0 @@
package com.knecon.fforesight.databasetenantcommons.providers;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.List;
import javax.sql.DataSource;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.liquibase.LiquibaseProperties;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.core.io.ResourceLoader;
import org.springframework.jdbc.datasource.SingleConnectionDataSource;
import com.knecon.fforesight.databasetenantcommons.providers.utils.JDBCUtils;
import com.knecon.fforesight.tenantcommons.EncryptionDecryptionService;
import com.knecon.fforesight.tenantcommons.TenantProvider;
import com.knecon.fforesight.tenantcommons.model.TenantResponse;
import feign.RetryableException;
import liquibase.integration.spring.SpringLiquibase;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@RequiredArgsConstructor
public class TenantSpringLiquibaseExecutor implements InitializingBean, ResourceLoaderAware {
private final EncryptionDecryptionService encryptionService;
private final TenantProvider tenantProvider;
@Qualifier("tenantLiquibaseProperties")
private final LiquibaseProperties tenantLiquibaseProperties;
@Setter
private ResourceLoader resourceLoader;
@Override
public void afterPropertiesSet() {
log.info("DynamicDataSources based multi-tenancy enabled");
try {
this.runOnAllTenants(tenantProvider.getTenants());
} catch (RetryableException e) {
log.warn("Tenant Service not online, skipping liquibase migration: {}", e.getMessage(), e);
}
}
@SneakyThrows
protected void runOnAllTenants(List<TenantResponse> tenants) {
for (var tenant : tenants) {
var jdbcURL = JDBCUtils.buildJdbcUrlWithSchema(tenant.getDatabaseConnection());
log.info("Initializing Liquibase for tenant {} / {}", tenant.getTenantId(), jdbcURL);
try (Connection connection = DriverManager.getConnection(jdbcURL,
tenant.getDatabaseConnection().getUsername(),
encryptionService.decrypt(tenant.getDatabaseConnection().getPassword()))) {
DataSource tenantDataSource = new SingleConnectionDataSource(connection, false);
SpringLiquibase liquibase = this.getSpringLiquibase(tenantDataSource);
liquibase.setClearCheckSums(tenantLiquibaseProperties.isClearChecksums());
liquibase.setDefaultSchema(tenant.getDatabaseConnection().getSchema());
liquibase.setLiquibaseSchema(tenant.getDatabaseConnection().getSchema());
liquibase.afterPropertiesSet();
} catch (Exception e) {
log.error("Failed to run liquibase migration on tenant: {}", tenant.getTenantId(), e);
}
log.info("Liquibase ran for tenant " + tenant.getTenantId());
}
}
protected SpringLiquibase getSpringLiquibase(DataSource dataSource) {
SpringLiquibase liquibase = new SpringLiquibase();
liquibase.setResourceLoader(resourceLoader);
liquibase.setDataSource(dataSource);
liquibase.setChangeLog(tenantLiquibaseProperties.getChangeLog());
liquibase.setContexts(tenantLiquibaseProperties.getContexts());
return liquibase;
}
}

View File

@ -1,36 +0,0 @@
package com.knecon.fforesight.databasetenantcommons.providers;
import java.util.Optional;
import org.springframework.stereotype.Service;
import com.knecon.fforesight.tenantcommons.listener.ITenantEventHandler;
import com.knecon.fforesight.tenantcommons.model.TenantSyncEvent;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@Service
@RequiredArgsConstructor
public class TenantSyncDatabaseEventHandler implements ITenantEventHandler<TenantSyncEvent> {
private final Optional<TenantSyncService> tenantSyncServices;
@Override
@SneakyThrows
public void handle(TenantSyncEvent tenantSyncEvent) {
tenantSyncServices.ifPresent(t -> t.syncTenant(tenantSyncEvent));
}
@Override
public Class<TenantSyncEvent> getEventClass() {
return TenantSyncEvent.class;
}
}

View File

@ -1,9 +0,0 @@
package com.knecon.fforesight.databasetenantcommons.providers;
import com.knecon.fforesight.tenantcommons.model.TenantSyncEvent;
public interface TenantSyncService {
void syncTenant(TenantSyncEvent tenantSyncEvent);
}

View File

@ -0,0 +1,14 @@
package com.knecon.fforesight.databasetenantcommons.providers.events;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class TenantCreatedEvent {
private String tenantId;
}

View File

@ -12,7 +12,6 @@ import lombok.NoArgsConstructor;
@NoArgsConstructor
@Data
@Builder
@SuppressWarnings("PMD")
public class Page<T> {
@Builder.Default

View File

@ -18,14 +18,13 @@ public class JDBCUtils {
}
public String buildJdbcUrl(DatabaseConnection databaseConnection, String datasourceName) {
public String buildJdbcUrl(DatabaseConnection databaseConnection) {
StringBuilder sb = createJdbcConnectionStringBuilder(databaseConnection.getDriver(),
databaseConnection.getHost(),
databaseConnection.getPort(),
databaseConnection.getDatabase());
Map<String, String> params = getConnectionParameters(databaseConnection);
params.put("ApplicationName", datasourceName);
appendParams(sb, params);
return sb.toString();
}

View File

@ -8,7 +8,6 @@ import java.sql.PreparedStatement;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.stream.Collectors;
@ -105,7 +104,7 @@ public class JDBCWriteUtils {
private String toSnakeCase(String name) {
String ret = name.replaceAll("([A-Z]{1,100})([A-Z][a-z])", "$1_$2").replaceAll("([a-z])([A-Z])", "$1_$2");
return ret.toLowerCase(Locale.ROOT);
return ret.toLowerCase();
}

View File

@ -122,23 +122,4 @@ public class MagicConverter {
}
public static void copyAllFields(Object source, Object target) {
var sourceClass = source.getClass();
var targetClass = target.getClass();
var sourceFields = sourceClass.getDeclaredFields();
for (var field : sourceFields) {
try {
var targetField = targetClass.getDeclaredField(field.getName());
field.setAccessible(true);
targetField.setAccessible(true);
targetField.set(target, field.get(source));
} catch (NoSuchFieldException | IllegalAccessException ignored) {
}
}
}
}

View File

@ -1,56 +0,0 @@
package com.knecon.fforesight.databasetenantcommons;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration;
import org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.util.TestPropertyValues;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import com.knecon.fforesight.databasetenantcommons.utils.SpringPostgreSQLTestContainer;
import com.knecon.fforesight.tenantcommons.MultiTenancyAutoConfiguration;
import lombok.extern.slf4j.Slf4j;
import org.testcontainers.containers.RabbitMQContainer;
@Slf4j
@ContextConfiguration(initializers = {BasicIntegrationTest.Initializer.class})
@ImportAutoConfiguration({MultiTenancyAutoConfiguration.class, DatabaseTenantCommonsAutoConfiguration.class})
@SuppressWarnings("PMD.TestClassWithoutTestCases")
@SpringBootTest
public abstract class BasicIntegrationTest {
static class Initializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
@SuppressWarnings("PMD")
public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
var postgreSQLContainerMaster = SpringPostgreSQLTestContainer.getInstance().withDatabaseName("integration-tests-db-master").withUsername("sa").withPassword("sa");
postgreSQLContainerMaster.start();
var port = postgreSQLContainerMaster.getJdbcUrl().substring(0, postgreSQLContainerMaster.getJdbcUrl().lastIndexOf('/')).split(":")[3];
RabbitMQContainer rabbitContainer = new RabbitMQContainer("rabbitmq:3.12");
rabbitContainer.start();
log.info("Rabbit container started and available at {}", rabbitContainer.getHttpUrl());
TestPropertyValues.of("RABBITMQ_USERNAME=" + rabbitContainer.getAdminUsername(),
"RABBITMQ_PASSWORD=" + rabbitContainer.getAdminPassword(),
"RABBITMQ_HOST=" + rabbitContainer.getHost(),
"RABBITMQ_PORT=" + rabbitContainer.getAmqpPort(),
"DB_PORT=" + port,
"DB_HOST=" + postgreSQLContainerMaster.getHost(),
"POD_NAME=tenant-database-commons"
).applyTo(configurableApplicationContext.getEnvironment());
}
}
@SpringBootApplication(exclude = {LiquibaseAutoConfiguration.class, JpaRepositoriesAutoConfiguration.class})
static class TestConfiguration {
}
}

View File

@ -1,94 +0,0 @@
package com.knecon.fforesight.databasetenantcommons;
import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import com.knecon.fforesight.databasetenantcommons.providers.TenantLiquibaseInitializer;
import com.knecon.fforesight.databasetenantcommons.utils.TestTenantProvider;
import com.knecon.fforesight.databasetenantcommons.utils.entity.TestEntity;
import com.knecon.fforesight.databasetenantcommons.utils.repo.TestRepository;
import com.knecon.fforesight.tenantcommons.EncryptionDecryptionService;
import com.knecon.fforesight.tenantcommons.TenantContext;
import com.knecon.fforesight.tenantcommons.model.AuthDetails;
import com.knecon.fforesight.tenantcommons.model.DatabaseConnection;
import com.knecon.fforesight.tenantcommons.model.TenantResponse;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
@Slf4j
public class LiquibaseTenantInitIntegrationTest extends BasicIntegrationTest {
private final static String TENANT_1 = "tenant1";
@Autowired
private EncryptionDecryptionService encryptionDecryptionService;
@Autowired
private RabbitTemplate rabbitTemplate;
@Autowired
private TestTenantProvider tenantProvider;
@Autowired
private TestRepository testRepository;
@Value("${DB_PORT}")
private String port;
@Value("${DB_HOST}")
private String host;
@Value("${fforesight.tenant-exchange.name:tenants-exchange}")
String tenantExchangeName;
@Test
@SneakyThrows
public void testTenantInitialized() {
TenantContext.setTenantId(TENANT_1);
log.info("Creating tenant {}", TENANT_1);
var testTenant = new TenantResponse();
testTenant.setTenantId(TENANT_1);
testTenant.setGuid(TENANT_1);
testTenant.setDisplayName(TENANT_1);
testTenant.setAuthDetails(new AuthDetails());
testTenant.setDatabaseConnection(DatabaseConnection.builder()
.driver("postgresql")
.host(host)
.port(port)
.database("integration-tests-db-master")
.schema(TENANT_1)
.username("sa")
.password(encryptionDecryptionService.encrypt("sa"))
.build());
tenantProvider.addTenant(testTenant);
log.info("Sending tenant created event");
rabbitTemplate.convertAndSend(tenantExchangeName, "tenant.created", TENANT_1);
var iteration = 0;
do {
Thread.sleep(2000);
try {
testRepository.findAll();
// when find succeeds tenant was created
break;
} catch (Exception e) {
log.debug("Waiting for liquibase to be ready");
// continue
}
} while (iteration < 15);
testRepository.save(new TestEntity(1, "Hello"));
var all = testRepository.findAll();
assertThat(all).isNotEmpty();
assertThat(all.get(0).getLabel()).isEqualTo("Hello");
}
}

View File

@ -1,25 +0,0 @@
package com.knecon.fforesight.databasetenantcommons.utils;
import org.testcontainers.containers.PostgreSQLContainer;
public final class SpringPostgreSQLTestContainer extends PostgreSQLContainer<SpringPostgreSQLTestContainer> {
private static final String IMAGE_VERSION = "postgres:15.2";
private static SpringPostgreSQLTestContainer container;
private SpringPostgreSQLTestContainer() {
super(IMAGE_VERSION);
}
public static SpringPostgreSQLTestContainer getInstance() {
if (container == null) {
container = new SpringPostgreSQLTestContainer();
}
return container;
}
}

View File

@ -1,61 +0,0 @@
package com.knecon.fforesight.databasetenantcommons.utils;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Service;
import com.knecon.fforesight.tenantcommons.TenantApplicationType;
import com.knecon.fforesight.tenantcommons.TenantProvider;
import com.knecon.fforesight.tenantcommons.listener.ITenantEventHandler;
import com.knecon.fforesight.tenantcommons.model.TenantCreatedEvent;
import com.knecon.fforesight.tenantcommons.model.TenantResponse;
import com.knecon.fforesight.tenantcommons.model.UpdateDetailsRequest;
@Service
public class TestTenantProvider implements TenantProvider {
private List<TenantResponse> tenants = new ArrayList<>();
@Override
public void updateDetails(String s, UpdateDetailsRequest updateDetailsRequest) {
//noop
}
@Override
public TenantResponse getTenant(String s) {
return tenants.stream()
.filter(t -> t.getTenantId().equals(s))
.findFirst()
.orElse(null);
}
@Override
public List<TenantResponse> getTenants() {
return tenants;
}
@Override
public TenantApplicationType getTenantApplicationType(String s) {
return tenants.stream()
.filter(t -> t.getTenantId().equals(s))
.findFirst()
.map(TenantResponse::getApplicationType)
.orElse(TenantApplicationType.RedactManager);
}
public void addTenant(TenantResponse tenantResponse) {
this.tenants.add(tenantResponse);
}
}

View File

@ -1,24 +0,0 @@
package com.knecon.fforesight.databasetenantcommons.utils.entity;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.testcontainers.shaded.org.checkerframework.checker.units.qual.A;
@Entity
@Data
@Table(name = "test")
@NoArgsConstructor
@AllArgsConstructor
public class TestEntity {
@Id
private int id;
@Column
private String label;
}

View File

@ -1,9 +0,0 @@
package com.knecon.fforesight.databasetenantcommons.utils.repo;
import org.springframework.data.jpa.repository.JpaRepository;
import com.knecon.fforesight.databasetenantcommons.utils.entity.TestEntity;
public interface TestRepository extends JpaRepository<TestEntity, Integer> {
}

View File

@ -1,34 +0,0 @@
spring:
application:
name: database-tenant-commons-tester
rabbitmq:
host: ${RABBITMQ_HOST:localhost}
port: ${RABBITMQ_PORT:5672}
username: ${RABBITMQ_USERNAME:user}
password: ${RABBITMQ_PASSWORD:rabbitmq}
listener:
simple:
acknowledge-mode: AUTO
concurrency: 5
retry:
enabled: true
max-attempts: 3
max-interval: 15000
prefetch: 1
multitenancy:
datasource-cache:
maximumSize: 100
expireAfterAccess: 1
packages:
repositories: 'com.knecon.fforesight.databasetenantcommons.utils.repo'
entities: 'com.knecon.fforesight.databasetenantcommons.utils.entity'
tenant:
datasource:
driverClassName: org.postgresql.Driver
liquibase:
changeLog: classpath:changelog/db.changelog-tenant.yaml
clear-checksums: true
logging.type: ${LOGGING_TYPE:CONSOLE}

View File

@ -1,3 +0,0 @@
databaseChangeLog:
- include:
file: changelog/tenant/test-table.changelog.yaml

View File

@ -1,18 +0,0 @@
databaseChangeLog:
- changeSet:
id: test-1
author: test-1
changes:
- createTable:
columns:
- column:
constraints:
nullable: false
primaryKey: true
primaryKeyName: test_pkey
name: id
type: BIGINT
- column:
name: label
type: VARCHAR(255)
tableName: test

View File

@ -1,13 +0,0 @@
<configuration>
<springProperty scope="configuration" name="logType" source="logging.type"/>
<springProperty scope="context" name="application.name" source="spring.application.name"/>
<springProperty scope="context" name="version" source="project.version"/>
<include resource="org/springframework/boot/logging/logback/defaults.xml"/>
<include resource="org/springframework/boot/logging/logback/console-appender.xml"/>
<root level="INFO">
<appender-ref ref="${logType}"/>
</root>
</configuration>