Compare commits

...

48 Commits
0.7.0 ... main

Author SHA1 Message Date
Timo Bejan
da9c1747b7 Merge branch 'RED-10106' into 'main'
RED-10106 a cleaner implementation for tenant listeners/exchanges and fixed...

See merge request fforesight/tenant-commons!20
2024-09-25 10:46:49 +02:00
Timo Bejan
eff1fe7f7e RED-10106 a cleaner implementation for tenant listeners/exchanges and fixed logging issue, added integration test 2024-09-25 00:32:05 +03:00
Maverick Studer
f1b0bf453a Merge branch 'log-rabbit-listener-errors' into 'main'
Listener Logging and DLQ fix

See merge request fforesight/tenant-commons!19
2024-09-03 12:08:12 +02:00
Maverick Studer
7985dc7370 Listener Logging and DLQ fix 2024-09-03 12:08:11 +02:00
Maverick Studer
4493aff8ee Merge branch 'tenants-client-retry' into 'main'
tenants client retry logic

See merge request fforesight/tenant-commons!18
2024-08-29 09:56:52 +02:00
Maverick Studer
d59df2a111 tenants client retry logic 2024-08-29 09:56:52 +02:00
Maverick Studer
b59fc9278d Merge branch 'RED-9331' into 'main'
RED-9331: Implement fair upload / analysis processing per tenant

See merge request fforesight/tenant-commons!17
2024-08-26 14:38:24 +02:00
Maverick Studer
71e3082cd0 RED-9331: Implement fair upload / analysis processing per tenant 2024-08-26 14:38:23 +02:00
Maverick Studer
30cf9a68af Merge branch 'hotfix-duplicate-taskexecutor' into 'main'
hotfix duplicate bean definition taskexeuctor

See merge request fforesight/tenant-commons!16
2024-07-18 16:17:00 +02:00
Maverick Studer
7fa175509a hotfix duplicate bean definition taskexeuctor 2024-07-18 16:17:00 +02:00
Maverick Studer
00c057f3f6 Merge branch 'RED-9331' into 'main'
RED-9331: Explore possibilities for fair upload / analysis processing per tenant

See merge request fforesight/tenant-commons!15
2024-07-18 13:51:11 +02:00
Maverick Studer
f9679a68be RED-9331: Explore possibilities for fair upload / analysis processing per tenant 2024-07-18 13:51:10 +02:00
Maverick Studer
183ae05ec3 Merge branch 'hotfix-async-tenantcontext' into 'main'
hotfix tenant context not available in async calls

See merge request fforesight/tenant-commons!15
2024-07-01 10:14:21 +02:00
Maverick Studer
98f43c1f1d hotfix tenant context not available in async calls 2024-07-01 10:14:21 +02:00
Maverick Studer
528a8f4353 Merge branch 'RED-8702-clustered' into 'main'
RED-8702: Explore document databases to store entityLog

See merge request fforesight/tenant-commons!14
2024-04-11 11:52:15 +02:00
Maverick Studer
57f92456d0 RED-8702: Explore document databases to store entityLog 2024-04-11 11:52:15 +02:00
Maverick Studer
5c98a79c47 Merge branch 'RED-8702' into 'main'
RED-8702: Explore document databases to store entityLog

See merge request fforesight/tenant-commons!13
2024-04-02 16:49:41 +02:00
Maverick Studer
3c8d3cd896 RED-8702: Explore document databases to store entityLog 2024-04-02 16:49:41 +02:00
Ali Oezyetimoglu
2b3e63f72f Merge branch 'RED-8497' into 'main'
RED-8497 - Migrate to gradle

See merge request fforesight/tenant-commons!12
2024-02-13 10:37:04 +01:00
Andrei Isvoran
902ef41be3 RED-8497 - Migrate to gradle 2024-02-13 10:37:04 +01:00
Timo Bejan
c3ba4d70b7 Merge branch 'task-config-update' into 'main'
Fixed pool sizes

See merge request fforesight/tenant-commons!11
2024-01-31 10:07:05 +01:00
Timo Bejan
f49dcc1727 Fixed pool sizes 2024-01-31 10:07:05 +01:00
Timo Bejan
75e14220ee Merge branch 'RED-8171' into 'main'
RED-8171 : Refactored `AsyncConfig` to take into account tracing configuration overwrite

See merge request fforesight/tenant-commons!10
2024-01-29 16:20:29 +01:00
Hanelore Ianoseck
56e5092571 RED-8171 : Refactored AsyncConfig to take into account tracing configuration overwrite 2024-01-29 16:20:29 +01:00
Dominique Eifländer
faf12716b6 Merge branch 'RED-5223' into 'main'
RED-5223: Added RabbitTemplateMultiCustomizer

See merge request fforesight/tenant-commons!9
2023-12-13 13:25:50 +01:00
Dominique Eifländer
43a78f5378 RED-5223: Added RabbitTemplateMultiCustomizer 2023-12-13 13:15:13 +01:00
Dominique Eifländer
a559683c04 Merge branch 'RED-1137' into 'main'
RED-1137: Removed tracing library, because of wrong dependency order

See merge request fforesight/tenant-commons!8
2023-12-13 11:14:23 +01:00
Dominique Eifländer
04eb42965a RED-1137: Removed tracing library, because of wrong dependency order 2023-12-13 11:08:59 +01:00
Dominique Eifländer
f7276bda68 Merge branch 'bumb-tracing' into 'main'
hotfix: Updated to latest tracing version

See merge request fforesight/tenant-commons!7
2023-12-05 12:49:50 +01:00
Dominique Eifländer
331bc19756 hotfix: Updated to latest tracing version 2023-12-05 12:48:01 +01:00
Timo Bejan
e1221cc05d Merge branch 'clean-extendible-messaging-config' into 'main'
Removed the BeanPostProcessor raw auto-config in favor of a more extendible approach

See merge request fforesight/tenant-commons!6
2023-11-27 21:52:16 +01:00
Hanelore.Ianoseck
fde6db8572 Primary-ized the simpleMessageListenerContainerCustomizer bean creation 2023-11-22 20:44:21 +02:00
Hanelore.Ianoseck
0b3cf27f13 Removed the manual post-processor BeanPostProcessor messaging configuration in favour of a more stream-lined, extendable, approach. 2023-11-06 22:41:52 +02:00
Timo Bejan
69c1c17c71 Merge branch 'add-tracing-dependency' into 'main'
Add tracing dependency

See merge request fforesight/tenant-commons!5
2023-10-23 10:08:40 +02:00
Hanelore.Ianoseck
5acc4736f0 Bumped to tracing:0.3.0 and removed optional tag on it so that it's added to the classpath at runtime 2023-10-10 22:50:25 +03:00
Hanelore.Ianoseck
6c999b8560 Bumped to tracing:0.2.0 to account for the default application config props and the new, traceable, logging format. 2023-10-09 22:00:48 +03:00
Hanelore.Ianoseck
8c6127e7ea Added dependency on tracing:0.1.0 and bumped spring-boot-starter-parent to 3.1.4 to gain access to the version of RabbitTemplate auto-configure that makes use of RabbitTemplateCustomizers which is part of the tracing mechanics. 2023-10-09 19:15:27 +03:00
Timo Bejan
0bfd489510 Merge branch 'rabbit-template-bean-removal' into 'main'
Removed manual RabbitTemplate bean creation

See merge request fforesight/tenant-commons!4
2023-10-04 14:03:48 +02:00
Hanelore.Ianoseck
922c649d4f There's no need for a custom-configured RabbitTemplate since spring-boot-autoconfigure automatically collects and uses the MessageConverter via its RabbitTemplateConfigurer bean. Removing the manual RabbitTemplate bean also helps with eventual observability since it allows finer/global control over 'setObservationEnabled'. 2023-10-02 21:38:46 +03:00
Ali Oezyetimoglu
d3c8fa5440 Merge branch 'RED-7175-2' into 'main'
RED-7175: changed index name to index prefix in  search connection

See merge request fforesight/tenant-commons!3
2023-09-06 12:33:15 +02:00
Ali Oezyetimoglu
a7434736ef RED-7175: changed index name to index prefix in search connection 2023-09-06 12:18:21 +02:00
Ali Oezyetimoglu
485fb9c9fd Merge branch 'RED-7175' into 'main'
RED-7175: added index name to search connection

See merge request fforesight/tenant-commons!2
2023-09-01 11:55:20 +02:00
Ali Oezyetimoglu
83c772cd86 RED-7175: added index name to search connection 2023-09-01 11:37:41 +02:00
Dominique Eifländer
c28cf9c49f Merge branch 'RED-7499' into 'main'
RED-7499: Fixed NPE when no conditional on storage-backend

See merge request fforesight/tenant-commons!1
2023-08-28 15:44:52 +02:00
deiflaender
46414f8c31 RED-7499: Fixed NPE when no conditional on storage-backend 2023-08-28 15:42:05 +02:00
Timo Bejan
2889d68d79 Jackson config 2023-06-27 23:37:20 +03:00
Timo Bejan
40a66a640b RED-6686 tenant details 2023-06-21 15:01:16 +03:00
Timo Bejan
f9d508e95b RED-6686 cleanup 2023-06-21 14:41:08 +03:00
58 changed files with 1722 additions and 678 deletions

9
.gitignore vendored
View File

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

View File

@ -1,4 +1,21 @@
include:
- project: 'gitlab/gitlab'
ref: 'main'
file: 'ci-templates/maven_deps.yml'
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_TAG

Binary file not shown.

View File

@ -1,18 +0,0 @@
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# 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.
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.7/apache-maven-3.8.7-bin.zip
wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.1/maven-wrapper-3.1.1.jar

110
build.gradle.kts Normal file
View File

@ -0,0 +1,110 @@
plugins {
`java-library`
`maven-publish`
pmd
checkstyle
jacoco
id("io.freefair.lombok") version "8.4"
id("org.sonarqube") version "4.4.1.3373"
}
val storageCommonsVersion = "2.43.0"
val springBootVersion = "3.1.5"
val springCloudVersion = "4.0.4"
val springRabbitTest = "3.0.9"
val testContainersVersion = "1.20.1"
dependencies {
api("com.iqser.red.commons:storage-commons:${storageCommonsVersion}")
api("org.springframework.boot:spring-boot-starter-amqp:${springBootVersion}")
api("org.springframework.boot:spring-boot-starter-web:${springBootVersion}")
api("org.springframework.cloud:spring-cloud-starter-openfeign:${springCloudVersion}")
api("org.springframework.boot:spring-boot-configuration-processor:${springBootVersion}")
testImplementation("org.springframework.boot:spring-boot-configuration-processor:${springBootVersion}")
testImplementation("org.springframework.boot:spring-boot-starter-test:${springBootVersion}")
testImplementation("org.springframework.amqp:spring-rabbit-test:${springRabbitTest}")
testImplementation("org.testcontainers:rabbitmq:${testContainersVersion}")
}
group = "com.knecon.fforesight"
description = "tenant-commons"
java.sourceCompatibility = JavaVersion.VERSION_17
java.targetCompatibility = JavaVersion.VERSION_17
repositories {
mavenLocal()
maven {
url = uri("https://nexus.knecon.com/repository/gindev/");
credentials {
username = providers.gradleProperty("mavenUser").getOrNull();
password = providers.gradleProperty("mavenPassword").getOrNull();
}
}
mavenCentral()
}
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

@ -0,0 +1,39 @@
<?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>

20
config/pmd/pmd.xml Normal file
View File

@ -0,0 +1,20 @@
<?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>

22
config/pmd/test_pmd.xml Normal file
View File

@ -0,0 +1,22 @@
<?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>

1
gradle.properties.kts Normal file
View File

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

316
mvnw vendored
View File

@ -1,316 +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
#
# 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
View File

@ -1,188 +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 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%

82
pom.xml
View File

@ -1,82 +0,0 @@
<?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>tenant-commons</artifactId>
<version>0.1-SNAPSHOT</version>
<name>tenant-commons</name>
<description>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>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.iqser.red.commons</groupId>
<artifactId>storage-commons</artifactId>
<version>${storage-commons.version}</version>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</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>

5
settings.gradle.kts Normal file
View File

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

View File

@ -1,29 +0,0 @@
package com.knecon.fforesight.tenantcommons;
import java.util.concurrent.Executor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurerSupport;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
@Configuration
@ConditionalOnClass(AsyncConfigurerSupport.class)
public class AsyncConfig extends AsyncConfigurerSupport {
@Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(7);
executor.setMaxPoolSize(42);
executor.setQueueCapacity(11);
executor.setThreadNamePrefix("TenantAwareTaskExecutor-");
executor.setTaskDecorator(new TenantAwareTaskDecorator());
executor.initialize();
return executor;
}
}

View File

@ -10,7 +10,7 @@ import lombok.extern.slf4j.Slf4j;
@Slf4j
@AutoConfiguration
@EnableFeignClients(basePackageClasses = TenantsClient.class)
@ComponentScan(basePackageClasses = MultiTenancyAutoConfiguration.class)
@ComponentScan(basePackageClasses = {MultiTenancyAutoConfiguration.class})
public class MultiTenancyAutoConfiguration {
@PostConstruct

View File

@ -2,72 +2,112 @@ package com.knecon.fforesight.tenantcommons;
import static com.knecon.fforesight.tenantcommons.ForwardTenantInterceptor.TENANT_HEADER_NAME;
import org.springframework.amqp.rabbit.config.AbstractRabbitListenerContainerFactory;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.config.ContainerCustomizer;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.amqp.RabbitTemplateCustomizer;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
@Configuration
@ConditionalOnClass(RabbitTemplate.class)
@SuppressWarnings("checkstyle:all")
public class MultiTenancyMessagingConfiguration {
/**
* Spring boot-autoconfigure 3.14 only allows for one {@link ContainerCustomizer<SimpleMessageListenerContainer>}
* to be defined. If 2 or more are defined instead, nothing ends up customizing the {@link SimpleRabbitListenerContainerFactory}
* (for more details, see RabbitAnnotationDrivenConfiguration::simpleRabbitListenerContainerFactory).
* To bypass this limitation, we define and inject our own {@link SimpleMessageListenerContainerCustomizer} which allows
* us to define as many container customization points as needed.
*/
@Bean
@ConditionalOnBean(ConnectionFactory.class)
public RabbitTemplate rabbitTemplate(final ConnectionFactory connectionFactory) {
@Primary
public ContainerCustomizer<SimpleMessageListenerContainer> simpleMessageListenerContainerCustomizer(
ObjectProvider<SimpleMessageListenerContainerCustomizer> customizers) {
final var rabbitTemplate = new RabbitTemplate(connectionFactory);
rabbitTemplate.setMessageConverter(producerJackson2MessageConverter());
return rabbitTemplate;
return container -> customizers.orderedStream().forEach((customizer) -> customizer.customize(container));
}
@Bean
public Jackson2JsonMessageConverter producerJackson2MessageConverter() {
@Primary
public RabbitTemplateCustomizer rabbitTemplateMultiCustomizer(
ObjectProvider<RabbitTemplateMultiCustomizer> customizers) {
return rabbitTemplate -> customizers.orderedStream().forEach((customizer) -> customizer.customize(rabbitTemplate));
}
@Bean
public MessageConverter producerJackson2MessageConverter() {
ObjectMapper mapper = new ObjectMapper().findAndRegisterModules();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
return new Jackson2JsonMessageConverter(mapper);
}
@Bean
public static BeanPostProcessor multitenancyBeanPostProcessor() {
public RabbitTemplateMultiCustomizer rabbitTemplatePublishTenantIdHeaderCustomizer(
@Qualifier("tenantIdSetterPostProcessor") MessagePostProcessor messagePostProcessor) {
return new BeanPostProcessor() {
return template -> template.addBeforePublishPostProcessors(messagePostProcessor);
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof RabbitTemplate) {
@Bean
public SimpleMessageListenerContainerCustomizer rabbitInterceptTenantIdHeaderCustomizer(
@Qualifier("tenantIdGetterPostProcessor") MessagePostProcessor messagePostProcessor) {
((RabbitTemplate) bean).setBeforePublishPostProcessors(m -> {
m.getMessageProperties().setHeader(TENANT_HEADER_NAME, TenantContext.getTenantId());
return m;
});
return container -> container.addAfterReceivePostProcessors(messagePostProcessor);
}
} else if (bean instanceof AbstractRabbitListenerContainerFactory) {
((AbstractRabbitListenerContainerFactory<?>) bean).setAfterReceivePostProcessors(m -> {
String tenant = m.getMessageProperties().getHeader(TENANT_HEADER_NAME);
@Bean
public MessagePostProcessor tenantIdSetterPostProcessor() {
if (tenant != null) {
TenantContext.setTenantId(tenant);
} else {
throw new RuntimeException("No Tenant is set queue message");
}
return m;
});
}
return bean;
}
return message -> {
message.getMessageProperties().setHeader(TENANT_HEADER_NAME, TenantContext.getTenantId());
return message;
};
}
@Bean
public MessagePostProcessor tenantIdGetterPostProcessor() {
return message -> {
String tenant = message.getMessageProperties().getHeader(TENANT_HEADER_NAME);
if (tenant != null) {
TenantContext.setTenantId(tenant);
} else {
throw new RuntimeException("No Tenant is set queue message");
}
return message;
};
}
@Bean
public RabbitAdmin rabbitAdmin(ConnectionFactory connectionFactory) {
return new RabbitAdmin(connectionFactory);
}
}

View File

@ -0,0 +1,44 @@
package com.knecon.fforesight.tenantcommons;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import lombok.extern.slf4j.Slf4j;
@Configuration
@Slf4j
public class RabbitConfiguration {
@Bean
public BeanPostProcessor rabbitListenerContainerFactoryPostProcessor() {
return new CustomBeanPostProcessor();
}
public static class CustomBeanPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof SimpleRabbitListenerContainerFactory factory) {
factory.setErrorHandler(t -> {
log.error("Error occurred in Rabbit listener: ", t);
});
}
return bean;
}
}
}

View File

@ -0,0 +1,13 @@
package com.knecon.fforesight.tenantcommons;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
@FunctionalInterface
public interface RabbitTemplateMultiCustomizer {
void customize(RabbitTemplate rabbitTemplate);
}

View File

@ -0,0 +1,10 @@
package com.knecon.fforesight.tenantcommons;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
@FunctionalInterface
public interface SimpleMessageListenerContainerCustomizer {
void customize(SimpleMessageListenerContainer simpleMessageListenerContainer);
}

View File

@ -4,7 +4,6 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.stereotype.Service;
import com.iqser.red.storage.commons.service.StorageConnectionProvider;
import lombok.RequiredArgsConstructor;
@Service
@ -20,10 +19,10 @@ public class StorageConnectionProviderImpl implements StorageConnectionProvider
public com.iqser.red.storage.commons.model.AzureStorageConnection getAzureStorageConnection(String tenantId) {
var tenant = tenantProvider.getTenant(tenantId);
return com.iqser.red.storage.commons.model.AzureStorageConnection.builder()
return tenant.getAzureStorageConnection() != null ? com.iqser.red.storage.commons.model.AzureStorageConnection.builder()
.connectionString(encryptionDecryptionService.decrypt(tenant.getAzureStorageConnection().getConnectionString()))
.containerName(tenant.getAzureStorageConnection().getContainerName())
.build();
.build() : null;
}
@ -31,14 +30,14 @@ public class StorageConnectionProviderImpl implements StorageConnectionProvider
public com.iqser.red.storage.commons.model.S3StorageConnection getS3StorageConnection(String tenantId) {
var tenant = tenantProvider.getTenant(tenantId);
return com.iqser.red.storage.commons.model.S3StorageConnection.builder()
return tenant.getS3StorageConnection() != null ? com.iqser.red.storage.commons.model.S3StorageConnection.builder()
.key(tenant.getS3StorageConnection().getKey())
.secret(encryptionDecryptionService.decrypt(tenant.getS3StorageConnection().getSecret()))
.signerType(tenant.getS3StorageConnection().getSignerType())
.bucketName(tenant.getS3StorageConnection().getBucketName())
.region(tenant.getS3StorageConnection().getRegion())
.endpoint(tenant.getS3StorageConnection().getEndpoint())
.build();
.build() : null;
}
}

View File

@ -1,9 +1,10 @@
package com.knecon.fforesight.tenantcommons;
import org.springframework.core.task.TaskDecorator;
import org.springframework.lang.NonNull;
public class TenantAwareTaskDecorator implements TaskDecorator {
import com.knecon.fforesight.tenantcommons.task.KneconTaskDecorator;
public class TenantAwareTaskDecorator implements KneconTaskDecorator {
@Override
@NonNull

View File

@ -3,11 +3,16 @@ package com.knecon.fforesight.tenantcommons;
import java.util.List;
import com.knecon.fforesight.tenantcommons.model.TenantResponse;
import com.knecon.fforesight.tenantcommons.model.UpdateDetailsRequest;
public interface TenantProvider {
void updateDetails(String tenantId, UpdateDetailsRequest request);
TenantResponse getTenant(String tenantId);
List<TenantResponse> getTenants();
}

View File

@ -2,27 +2,34 @@ package com.knecon.fforesight.tenantcommons;
import java.util.List;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import com.knecon.fforesight.tenantcommons.model.TenantResponse;
import com.knecon.fforesight.tenantcommons.model.UpdateDetailsRequest;
@FeignClient(name = "TenantsResource", url = "${tenant-user-management-service.url}")
@FeignClient(name = "TenantsResource", url = "${tenant-user-management-service.url}", configuration = TenantsClientConfiguration.class)
@ResponseStatus(value = HttpStatus.OK)
@ConditionalOnProperty(prefix = "fforesight.tenants", value = "remote", havingValue = "true")
public interface TenantsClient extends TenantProvider {
String TENANT_PATH = "/tenants";
String TENANT_ID_PARAM = "tenantId";
String DETAILS_PATH = "/details";
String TENANT_ID_PATH_PARAM = "/{" + TENANT_ID_PARAM + "}";
@PostMapping(value = TENANT_PATH + TENANT_ID_PATH_PARAM + DETAILS_PATH, consumes = MediaType.APPLICATION_JSON_VALUE)
void updateDetails(@PathVariable("tenantId") String tenantId, @RequestBody UpdateDetailsRequest request);
@GetMapping(value = TENANT_PATH + TENANT_ID_PATH_PARAM, produces = MediaType.APPLICATION_JSON_VALUE)
TenantResponse getTenant(@PathVariable(TENANT_ID_PARAM) String tenantId);

View File

@ -0,0 +1,94 @@
package com.knecon.fforesight.tenantcommons;
import java.util.concurrent.TimeUnit;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import feign.RetryableException;
import feign.Retryer;
import lombok.extern.slf4j.Slf4j;
@Configuration
public class TenantsClientConfiguration {
public static final int INITIAL_BACKOFF_SECONDS = 15;
public static final int MAX_BACKOFF_MINUTES = 8;
public static final int RETRY_ATTEMPTS = 4;
@Bean
public Retryer feignRetryer() {
return new ExponentialRetryer(TimeUnit.SECONDS.toMillis(INITIAL_BACKOFF_SECONDS), TimeUnit.MINUTES.toMillis(MAX_BACKOFF_MINUTES), RETRY_ATTEMPTS);
}
@Slf4j
@SuppressWarnings("PMD.ProperCloneImplementation")
public static class ExponentialRetryer extends Retryer.Default {
private final long initialPeriod;
private final long maxPeriod;
private final int maxAttempts;
private int attempt = 1;
private long currentPeriod;
public ExponentialRetryer(long initialPeriod, long maxPeriod, int maxAttempts) {
this.initialPeriod = initialPeriod;
this.maxPeriod = maxPeriod;
this.maxAttempts = maxAttempts;
this.currentPeriod = initialPeriod;
}
@Override
public void continueOrPropagate(RetryableException e) {
if (attempt > maxAttempts) {
log.error("Max retry attempts reached. Giving up after {} attempts.", maxAttempts);
throw e;
}
log.info("Attempt {} - Retrying due to exception: {}", attempt, e.getMessage());
long interval;
if (e.retryAfter() != null) {
interval = e.retryAfter().getTime() - System.currentTimeMillis();
if (interval > maxPeriod) {
interval = maxPeriod;
}
if (interval < 0L) {
return;
}
} else {
interval = currentPeriod;
currentPeriod = Math.min(currentPeriod * 2, maxPeriod);
}
try {
Thread.sleep(interval);
} catch (InterruptedException ignored) {
Thread.currentThread().interrupt();
throw e; // Rethrow the exception if interrupted
}
attempt++;
}
@Override
public ExponentialRetryer clone() {
return new ExponentialRetryer(initialPeriod, maxPeriod, maxAttempts);
}
}
}

View File

@ -0,0 +1,12 @@
package com.knecon.fforesight.tenantcommons.listener;
import com.knecon.fforesight.tenantcommons.model.ITenantEvent;
public interface ITenantEventHandler<T extends ITenantEvent> {
void handle(T event);
Class<T> getEventClass();
}

View File

@ -0,0 +1,53 @@
package com.knecon.fforesight.tenantcommons.listener.impl;
import java.util.Optional;
import org.springframework.stereotype.Service;
import com.knecon.fforesight.tenantcommons.listener.ITenantEventHandler;
import com.knecon.fforesight.tenantcommons.model.TenantCreatedEvent;
import com.knecon.fforesight.tenantcommons.model.TenantQueueProvider;
import com.knecon.fforesight.tenantcommons.queue.RabbitQueueFromExchangeServiceImpl;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@Service
@RequiredArgsConstructor
public class TenantEventQueueCreationHandler implements ITenantEventHandler<TenantCreatedEvent> {
private final RabbitQueueFromExchangeServiceImpl rabbitQueueService;
private final Optional<TenantQueueProvider> tenantQueueProvider;
@PostConstruct
public void init() {
log.info("TenantEventQueueCreationHandler initialized");
}
@Override
public void handle(TenantCreatedEvent tenantCreatedEvent) {
tenantQueueProvider.ifPresentOrElse(t -> {
log.info("Creating queues for new tenant {}", tenantCreatedEvent.getTenantId());
t.getTenantQueueConfigurations().forEach(tqc -> rabbitQueueService.addNewQueue(tqc.getListenerId(),
tqc.getQueuePrefix(),
tqc.getExchangeName(),
tenantCreatedEvent.getTenantId(),
tqc.getDlqName(),
tqc.getArguments()));
}, () -> log.warn("This service does not provide any queues to create"));
}
@Override
public Class<TenantCreatedEvent> getEventClass() {
return TenantCreatedEvent.class;
}
}

View File

@ -0,0 +1,53 @@
package com.knecon.fforesight.tenantcommons.listener.impl;
import java.util.Optional;
import org.springframework.stereotype.Service;
import com.knecon.fforesight.tenantcommons.listener.ITenantEventHandler;
import com.knecon.fforesight.tenantcommons.model.TenantQueueProvider;
import com.knecon.fforesight.tenantcommons.model.TenantResponse;
import com.knecon.fforesight.tenantcommons.queue.RabbitQueueFromExchangeServiceImpl;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@Service
@RequiredArgsConstructor
public class TenantEventQueueDeletionHandler implements ITenantEventHandler<TenantResponse> {
private final RabbitQueueFromExchangeServiceImpl rabbitQueueService;
private final Optional<TenantQueueProvider> tenantQueueProvider;
@PostConstruct
public void init() {
log.info("TenantEventQueueDeletionHandler initialized");
}
@Override
public void handle(TenantResponse tenantResponse) {
tenantQueueProvider.ifPresentOrElse(t -> {
log.info("Deleting queues for tenant {}", tenantResponse.getTenantId());
t.getTenantQueueConfigurations().forEach(tqc -> rabbitQueueService.deleteQueue(tqc.getListenerId(),
tqc.getQueuePrefix(),
tqc.getExchangeName(),
tenantResponse.getTenantId(),
tqc.getDlqName(),
tqc.getArguments()));
}, () -> log.warn("This service does not provide any queues to delete"));
}
@Override
public Class<TenantResponse> getEventClass() {
return TenantResponse.class;
}
}

View File

@ -4,7 +4,6 @@ import java.util.HashSet;
import java.util.Set;
import com.fasterxml.jackson.annotation.JsonAlias;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

View File

@ -0,0 +1,7 @@
package com.knecon.fforesight.tenantcommons.model;
public interface ITenantEvent {
String getTenantId();
}

View File

@ -0,0 +1,21 @@
package com.knecon.fforesight.tenantcommons.model;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class MongoDBConnection {
private String prefix;
private String username;
private String password;
private String address;
private String database;
private String options;
}

View File

@ -20,5 +20,6 @@ public class SearchConnection {
private String password;
private String numberOfShards;
private String numberOfReplicas;
private String indexPrefix;
}

View File

@ -0,0 +1,14 @@
package com.knecon.fforesight.tenantcommons.model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class TenantCreatedEvent implements ITenantEvent {
private String tenantId;
}

View File

@ -0,0 +1,24 @@
package com.knecon.fforesight.tenantcommons.model;
import java.util.HashMap;
import java.util.Map;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class TenantQueueConfiguration {
private String listenerId;
private String exchangeName;
private String queuePrefix;
private String dlqName;
@Builder.Default
private Map<String, Object> arguments = new HashMap<>();
}

View File

@ -0,0 +1,14 @@
package com.knecon.fforesight.tenantcommons.model;
import java.util.Set;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
@RequiredArgsConstructor
@Getter
public class TenantQueueProvider {
public final Set<TenantQueueConfiguration> tenantQueueConfigurations;
}

View File

@ -1,5 +1,8 @@
package com.knecon.fforesight.tenantcommons.model;
import java.util.HashMap;
import java.util.Map;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
@ -9,7 +12,7 @@ import lombok.NoArgsConstructor;
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class TenantResponse {
public class TenantResponse implements ITenantEvent {
private String tenantId;
private String displayName;
@ -19,6 +22,9 @@ public class TenantResponse {
private SearchConnection searchConnection;
private AzureStorageConnection azureStorageConnection;
private S3StorageConnection s3StorageConnection;
private MongoDBConnection mongoDBConnection;
private AuthDetails authDetails;
private Map<String, Object> details = new HashMap<>();
}

View File

@ -0,0 +1,14 @@
package com.knecon.fforesight.tenantcommons.model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class TenantSyncEvent implements ITenantEvent {
private String tenantId;
}

View File

@ -0,0 +1,17 @@
package com.knecon.fforesight.tenantcommons.model;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class UpdateDetailsRequest {
private String key;
private Object value;
}

View File

@ -0,0 +1,21 @@
package com.knecon.fforesight.tenantcommons.queue;
import java.util.Map;
public interface RabbitQueueFromExchangeService {
void addNewQueue(String listenerId, String queueNamePrefix, String exchangeName, String routingKey, String dlq, Map<String, Object> arguments);
void deleteQueue(String listenerId, String queueNamePrefix, String exchangeName, String routingKey, String dlq, Map<String, Object> arguments);
void addQueueToListener(String listenerId, String queueName);
void removeQueueFromListener(String listenerId, String queueName);
boolean checkQueueExistOnListener(String listenerId, String queueName);
}

View File

@ -0,0 +1,122 @@
package com.knecon.fforesight.tenantcommons.queue;
import java.util.Map;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer;
import org.springframework.amqp.rabbit.listener.RabbitListenerEndpointRegistry;
import org.springframework.stereotype.Service;
import lombok.AccessLevel;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.experimental.FieldDefaults;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@Service
@RequiredArgsConstructor
@FieldDefaults(makeFinal = true, level = AccessLevel.PRIVATE)
public class RabbitQueueFromExchangeServiceImpl implements RabbitQueueFromExchangeService {
RabbitAdmin rabbitAdmin;
RabbitListenerEndpointRegistry rabbitListenerEndpointRegistry;
@Override
@SneakyThrows
public void addNewQueue(String listenerId, String queueNamePrefix, String exchangeName, String routingKey, String dlq, Map<String, Object> arguments) {
String queueName = queueNamePrefix + "_" + routingKey;
Queue queue = new Queue(queueName, true, false, false);
addArgumentsToQueue(queue, dlq, arguments);
Binding binding = getBinding(exchangeName, routingKey, queueName);
String returnedQueueName = rabbitAdmin.declareQueue(queue);
log.debug("Declared queue {}", returnedQueueName);
rabbitAdmin.declareBinding(binding);
log.debug("Declared binding");
addQueueToListener(listenerId, queueName);
}
private void addArgumentsToQueue(Queue queue, String dlq, Map<String, Object> arguments) {
if (dlq != null && !dlq.isBlank()) {
queue.addArgument("x-dead-letter-exchange", "");
queue.addArgument("x-dead-letter-routing-key", dlq);
arguments.forEach(queue::addArgument);
}
}
private static Binding getBinding(String exchangeName, String routingKey, String queueName) {
return new Binding(queueName, Binding.DestinationType.QUEUE, exchangeName, routingKey, null);
}
private AbstractMessageListenerContainer getMessageListenerContainerById(String listenerId) {
log.debug("Getting message listener container by id {}", listenerId);
return ((AbstractMessageListenerContainer) rabbitListenerEndpointRegistry.getListenerContainer(listenerId));
}
@Override
public void deleteQueue(String listenerId, String queueNamePrefix, String exchangeName, String routingKey, String dlq, Map<String, Object> arguments) {
String queueName = queueNamePrefix + "_" + routingKey;
removeQueueFromListener(listenerId, queueName);
Binding binding = getBinding(exchangeName, routingKey, queueName);
rabbitAdmin.removeBinding(binding);
log.debug("Removed binding");
if (rabbitAdmin.deleteQueue(queueName)) {
log.info("Deleted queue {} successfully", queueName);
} else {
log.info("Queue deletion failed");
}
}
@Override
public void addQueueToListener(String listenerId, String queueName) {
log.info("Adding queue {} to listener {}", queueName, listenerId);
if (!checkQueueExistOnListener(listenerId, queueName)) {
getMessageListenerContainerById(listenerId).addQueueNames(queueName);
}
}
@Override
public void removeQueueFromListener(String listenerId, String queueName) {
log.info("Removing queue {} from listener {}", queueName, listenerId);
if (checkQueueExistOnListener(listenerId, queueName)) {
getMessageListenerContainerById(listenerId).removeQueueNames(queueName);
rabbitAdmin.deleteQueue(queueName);
}
}
@Override
public boolean checkQueueExistOnListener(String listenerId, String queueName) {
log.debug("Checking if queue {} exists on listener {}", queueName, listenerId);
String[] queueNames = getMessageListenerContainerById(listenerId).getQueueNames();
for (String name : queueNames) {
if (name.equals(queueName)) {
log.debug("Queue with name : {} already exists on listener", queueName);
return true;
}
}
log.debug("Queue with name : {} does not exist on listener", queueName);
return false;
}
}

View File

@ -0,0 +1,23 @@
package com.knecon.fforesight.tenantcommons.queue;
import java.util.concurrent.Semaphore;
import lombok.SneakyThrows;
public class TenantEventsLock {
private final static Semaphore semaphore = new Semaphore(1);
@SneakyThrows
public static void executeInLock(Runnable runnable) {
try {
semaphore.acquire();
runnable.run();
} finally {
semaphore.release();
}
}
}

View File

@ -0,0 +1,169 @@
package com.knecon.fforesight.tenantcommons.queue;
import static com.knecon.fforesight.tenantcommons.queue.TenantRabbitListener.TENANT_CREATED_LISTENER;
import static com.knecon.fforesight.tenantcommons.queue.TenantRabbitListener.TENANT_DELETED_LISTENER;
import static com.knecon.fforesight.tenantcommons.queue.TenantRabbitListener.TENANT_SYNC_LISTENER;
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.amqp.rabbit.listener.RabbitListenerEndpointRegistry;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.EventListener;
import lombok.RequiredArgsConstructor;
@Configuration
@RequiredArgsConstructor
public class TenantMessagingConfiguration {
public static final String TENANT_CREATED_QUEUE = "tenantCreatedQueue";
public static final String TENANT_DELETED_QUEUE = "tenantDeletedQueue";
public static final String TENANT_SYNC_QUEUE = "tenantSyncQueue";
public static final String TENANT_EXCHANGE = "tenantExchange";
// time in ms after which a deletion will be executed when no consumer is present
// see: https://www.rabbitmq.com/docs/ttl#queue-ttl
public static final int QUEUE_EXPIRATION_TIME = 300000; // 5 minutes
private static final String TENANT_EVENTS_DLQ_SUFFIX = "_tenant_events_error";
private static final String TENANT_CREATED_QUEUE_SUFFIX = "_tenant_created";
private static final String TENANT_DELETED_QUEUE_SUFFIX = "_tenant_deleted";
private static final String TENANT_SYNC_QUEUE_SUFFIX = "_tenant_sync";
private final RabbitListenerEndpointRegistry rabbitListenerEndpointRegistry;
@Value("${POD_NAME:}")
private String podName;
@EventListener(ApplicationReadyEvent.class)
public void assignQueuesToListeners() {
rabbitListenerEndpointRegistry.getListenerContainer(TENANT_CREATED_LISTENER).setQueueNames(getTenantCreatedQueueName());
rabbitListenerEndpointRegistry.getListenerContainer(TENANT_DELETED_LISTENER).setQueueNames(getTenantDeletedQueueName());
rabbitListenerEndpointRegistry.getListenerContainer(TENANT_SYNC_LISTENER).setQueueNames(getTenantSyncQueueName());
}
public String getTenantCreatedQueueName() {
return getQueueNameWithSuffix(TENANT_CREATED_QUEUE_SUFFIX);
}
public String getTenantDeletedQueueName() {
return getQueueNameWithSuffix(TENANT_DELETED_QUEUE_SUFFIX);
}
public String getTenantSyncQueueName() {
return this.getQueueNameWithSuffix(TENANT_SYNC_QUEUE_SUFFIX);
}
@Bean(name = TENANT_EXCHANGE)
public TopicExchange tenantExchange(@Value("${fforesight.tenant-exchange.name:tenants-exchange}") String tenantExchangeName) {
return new TopicExchange(tenantExchangeName);
}
@Bean(TENANT_CREATED_QUEUE)
public Queue tenantCreatedQueue() {
return QueueBuilder.durable(getTenantCreatedQueueName())
.withArgument("x-dead-letter-exchange", "")
.withArgument("x-dead-letter-routing-key", getTenantEventsDLQName())
.withArgument("x-expires", QUEUE_EXPIRATION_TIME)
.build();
}
@Bean(TENANT_DELETED_QUEUE)
public Queue tenantDeletedQueue() {
return QueueBuilder.durable(getTenantDeletedQueueName())
.withArgument("x-dead-letter-exchange", "")
.withArgument("x-dead-letter-routing-key", getTenantEventsDLQName())
.withArgument("x-expires", QUEUE_EXPIRATION_TIME)
.build();
}
@Bean
public Queue tenantEventsDLQ() {
return QueueBuilder.durable(getTenantEventsDLQName()).withArgument("x-expires", QUEUE_EXPIRATION_TIME).build();
}
public String getTenantEventsDLQName() {
return getQueueNameWithSuffix(TENANT_EVENTS_DLQ_SUFFIX);
}
protected String getQueueNameWithSuffix(String suffix) {
if (!useDefaultQueueName() && podName != null && !podName.isEmpty()) {
return podName + suffix;
} else {
return getDefaultQueueName(suffix);
}
}
protected boolean useDefaultQueueName() {
return false;
}
// This method will be overridden by subclasses if the POD_NAME is not set.
// Default implementation throws an exception to ensure it's implemented if used.
protected String getDefaultQueueName(String suffix) {
throw new UnsupportedOperationException("Queue name method not implemented");
}
@Bean
public Binding tenantCreatedBinding(@Qualifier(TENANT_CREATED_QUEUE) Queue tenantCreatedQueue, @Qualifier(TENANT_EXCHANGE) TopicExchange tenantExchange) {
return BindingBuilder.bind(tenantCreatedQueue).to(tenantExchange).with("tenant.created");
}
@Bean
public Binding tenantDeletedBinding(@Qualifier(TENANT_DELETED_QUEUE) Queue tenantDeletedQueue, @Qualifier(TENANT_EXCHANGE) TopicExchange tenantExchange) {
return BindingBuilder.bind(tenantDeletedQueue).to(tenantExchange).with("tenant.delete");
}
@Bean({TENANT_SYNC_QUEUE})
public Queue tenantSyncQueue() {
return QueueBuilder.durable(this.getTenantSyncQueueName())
.withArgument("x-dead-letter-exchange", "")
.withArgument("x-dead-letter-routing-key", this.getTenantEventsDLQName())
.withArgument("x-expires", 300000)
.build();
}
@Bean
public Binding tenantSyncBinding(@Qualifier(TENANT_SYNC_QUEUE) Queue tenantCreatedQueue, @Qualifier(TENANT_EXCHANGE) TopicExchange tenantExchange) {
return BindingBuilder.bind(tenantCreatedQueue).to(tenantExchange).with("tenant.sync");
}
}

View File

@ -0,0 +1,54 @@
package com.knecon.fforesight.tenantcommons.queue;
import java.util.Optional;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;
import com.knecon.fforesight.tenantcommons.TenantProvider;
import com.knecon.fforesight.tenantcommons.model.TenantQueueProvider;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@RequiredArgsConstructor
@Service
public class TenantQueueInitializer {
private final Optional<TenantQueueProvider> tenantQueueProvider;
private final TenantProvider tenantProvider;
private final RabbitQueueFromExchangeService rabbitQueueService;
@EventListener(ApplicationReadyEvent.class)
public void onApplicationReady() {
initializeQueues();
}
@SneakyThrows
public void initializeQueues() {
tenantQueueProvider.ifPresent(tenantQueueProvider -> {
log.info("Initializing queues for all tenants.");
TenantEventsLock.executeInLock(() -> {
tenantProvider.getTenants()
.forEach(tenant -> {
tenantQueueProvider.getTenantQueueConfigurations().parallelStream()
.forEach(tqc -> rabbitQueueService.addNewQueue(tqc.getListenerId(),
tqc.getQueuePrefix(),
tqc.getExchangeName(),
tenant.getTenantId(),
tqc.getDlqName(),
tqc.getArguments()));
log.info("Initialized queues for tenant {}", tenant.getTenantId());
});
});
});
}
}

View File

@ -0,0 +1,83 @@
package com.knecon.fforesight.tenantcommons.queue;
import java.util.ArrayList;
import java.util.List;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;
import com.knecon.fforesight.tenantcommons.listener.ITenantEventHandler;
import com.knecon.fforesight.tenantcommons.model.ITenantEvent;
import com.knecon.fforesight.tenantcommons.model.TenantCreatedEvent;
import com.knecon.fforesight.tenantcommons.model.TenantResponse;
import com.knecon.fforesight.tenantcommons.model.TenantSyncEvent;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@Service
@RequiredArgsConstructor
public class TenantRabbitListener {
public static final String TENANT_CREATED_LISTENER = "tenantCreatedListener";
public static final String TENANT_DELETED_LISTENER = "tenantDeletedListener";
public static final String TENANT_SYNC_LISTENER = "tenantSyncListener";
private final List<ITenantEventHandler> eventListeners;
@SneakyThrows
@RabbitHandler
@RabbitListener(id = TENANT_CREATED_LISTENER)
public void listenOnTenantCreated(TenantCreatedEvent tenantCreatedEvent) {
this.processTenantEvent(tenantCreatedEvent);
}
@SneakyThrows
private <T extends ITenantEvent> void processTenantEvent(T event) {
TenantEventsLock.executeInLock(() -> {
List<Throwable> exceptions = new ArrayList<>();
eventListeners.stream()
.filter(listener -> listener.getEventClass().equals(event.getClass()))
.forEach(listener -> {
log.info("Processing listener {} for {} event {}", listener.getClass().getSimpleName(), event.getClass().getSimpleName(), event.getTenantId());
try {
listener.handle(event);
} catch (Exception e) {
log.error("Error handling event {} at listener: {}", event.getTenantId(), listener.getEventClass().getSimpleName(), e);
exceptions.add(e);
}
});
if (!exceptions.isEmpty()) {
log.error("Some listeners ({}) failed to handle tenant created event {}", exceptions.size(), event.getTenantId());
// TODO determine if we should do something if some listeners failed ...
}
});
}
@SneakyThrows
@RabbitHandler
@RabbitListener(id = TENANT_DELETED_LISTENER)
public void listenOnTenantDeleted(TenantResponse tenantResponse) {
this.processTenantEvent(tenantResponse);
}
@SneakyThrows
@RabbitHandler
@RabbitListener(id = TENANT_SYNC_LISTENER)
public void listenOnTenantSync(TenantSyncEvent tenantSyncEvent) {
this.processTenantEvent(tenantSyncEvent);
}
}

View File

@ -0,0 +1,26 @@
package com.knecon.fforesight.tenantcommons.task;
import static org.springframework.boot.autoconfigure.task.TaskExecutionAutoConfiguration.APPLICATION_TASK_EXECUTOR_BEAN_NAME;
import static org.springframework.scheduling.annotation.AsyncAnnotationBeanPostProcessor.DEFAULT_TASK_EXECUTOR_BEAN_NAME;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.task.TaskExecutorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
@ConditionalOnClass(ThreadPoolTaskExecutor.class)
@Configuration
public class ApplicationTaskExecutorBeanConfig {
@Lazy
@Bean(name = {APPLICATION_TASK_EXECUTOR_BEAN_NAME, DEFAULT_TASK_EXECUTOR_BEAN_NAME})
@ConditionalOnMissingBean(name = {APPLICATION_TASK_EXECUTOR_BEAN_NAME, DEFAULT_TASK_EXECUTOR_BEAN_NAME})
public ThreadPoolTaskExecutor applicationTaskExecutor(TaskExecutorBuilder builder) {
return builder.build();
}
}

View File

@ -0,0 +1,8 @@
package com.knecon.fforesight.tenantcommons.task;
import org.springframework.core.task.TaskDecorator;
// Marker interface
public interface KneconTaskDecorator extends TaskDecorator {
}

View File

@ -0,0 +1,19 @@
package com.knecon.fforesight.tenantcommons.task;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.knecon.fforesight.tenantcommons.TenantAwareTaskDecorator;
@Configuration(proxyBeanMethods = false)
public class TaskDecoratorConfiguration {
@Bean
@ConditionalOnMissingBean
public KneconTaskDecorator tenantAwareTaskDecorator() {
return new TenantAwareTaskDecorator();
}
}

View File

@ -0,0 +1,50 @@
package com.knecon.fforesight.tenantcommons.task;
import java.util.function.Supplier;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.task.TaskExecutorCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.scheduling.annotation.EnableAsync;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
@Configuration(proxyBeanMethods = false)
@PropertySource("classpath:tenant-commons-task.properties")
@ConditionalOnProperty(prefix = "management.tracing", name = "enabled", havingValue = "false")
@EnableAsync
@Slf4j
public class TaskExecutionConfiguration {
private final static Supplier<KneconTaskDecorator> IDENTITY_KNECON_TASK_DECORATOR_SUPPLIER = () -> runna -> runna;
@Value("${spring.task.execution.pool.warnPercentageThreshold:80}")
private int executorWarnPercentageThreshold;
@Bean
public TaskExecutorCustomizer taskExecutorCustomizer(ObjectProvider<KneconTaskDecorator> taskDecorator) {
return taskExecutor -> {
taskExecutor.setTaskDecorator((KneconTaskDecorator) runnable -> {
val taskDecoratorUsed = taskDecorator.getIfUnique(IDENTITY_KNECON_TASK_DECORATOR_SUPPLIER);
val decoratedRunnable = taskDecoratorUsed.decorate(runnable);
val actualQueueSize = taskExecutor.getQueueSize() + 1;
val queueOccupancyPercentage = actualQueueSize * 100.f / taskExecutor.getMaxPoolSize();
if (queueOccupancyPercentage >= executorWarnPercentageThreshold) {
log.warn("Executor pool [ " + taskExecutor + " ] queue size reached " + actualQueueSize + "/" + taskExecutor.getMaxPoolSize() +
" entries awaiting execution triggering the warn level set for " + executorWarnPercentageThreshold + "% occupancy.");
}
return decoratedRunnable;
});
};
}
}

View File

@ -0,0 +1,44 @@
package com.knecon.fforesight.tenantcommons.utils;
import com.knecon.fforesight.tenantcommons.model.MongoDBConnection;
import lombok.experimental.UtilityClass;
@UtilityClass
public class MongoConnectionStringHelper {
public static String buildGenericMongoUrl(MongoDBConnection mongoDBConnection) {
return mongoDBConnection.getPrefix() + "://" + mongoDBConnection.getAddress() + "/" + mongoDBConnection.getDatabase() + "?" + mongoDBConnection.getOptions();
}
public static String buildGenericMongoConnectionString(MongoDBConnection mongoDBConnection) {
return mongoDBConnection.getPrefix()
+ "://"
+ mongoDBConnection.getUsername()
+ ":"
+ mongoDBConnection.getPassword()
+ "@"
+ mongoDBConnection.getAddress()
+ "/?"
+ mongoDBConnection.getOptions();
}
public static String buildDatabaseMongoConnectionString(MongoDBConnection mongoDBConnection) {
return mongoDBConnection.getPrefix()
+ "://"
+ mongoDBConnection.getUsername()
+ ":"
+ mongoDBConnection.getPassword()
+ "@"
+ mongoDBConnection.getAddress()
+ "/"
+ mongoDBConnection.getDatabase()
+ "?"
+ mongoDBConnection.getOptions();
}
}

View File

@ -0,0 +1,10 @@
#
# Configure task executor specs
#
# For more available props,
# see: https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/task/TaskExecutionProperties.java
#
spring.task.execution.pool.coreSize=4
spring.task.execution.pool.maxSize=4
spring.task.execution.pool.queueCapacity=10000
spring.task.execution.threadNamePrefix=TenantAwareTaskExecutor-

View File

@ -0,0 +1,81 @@
package com.knecon.fforesight.tenantcommons;
import java.util.Collections;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
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.context.annotation.Bean;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import com.knecon.fforesight.tenantcommons.model.TenantQueueConfiguration;
import com.knecon.fforesight.tenantcommons.model.TenantQueueProvider;
import com.knecon.fforesight.tenantcommons.utils.TestMessageService;
import lombok.extern.slf4j.Slf4j;
import org.testcontainers.containers.RabbitMQContainer;
@Slf4j
@ContextConfiguration(initializers = {BasicIntegrationTest.Initializer.class})
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_EACH_TEST_METHOD)
@ImportAutoConfiguration({MultiTenancyAutoConfiguration.class})
@SuppressWarnings("PMD.TestClassWithoutTestCases")
@SpringBootTest
public abstract class BasicIntegrationTest {
static class Initializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
@SuppressWarnings("PMD")
public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
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(),
"POD_NAME=tenant-commons"
).applyTo(configurableApplicationContext.getEnvironment());
}
}
@SpringBootApplication
static class TestConfiguration {
@Bean
public DirectExchange testExchange() {
return new DirectExchange("testExchange");
}
@Bean
public TenantQueueProvider tenantQueueProvider() {
var testQueue = TenantQueueConfiguration.builder()
.listenerId("testListener")
.exchangeName("testExchange")
.queuePrefix("test")
.dlqName("test_error")
.build();
return new TenantQueueProvider(Collections.singleton(testQueue));
}
@Bean
public TestMessageService testMessageService() {
return new TestMessageService();
}
}
}

View File

@ -0,0 +1,71 @@
package com.knecon.fforesight.tenantcommons;
import com.knecon.fforesight.tenantcommons.task.TaskDecoratorConfiguration;
import com.knecon.fforesight.tenantcommons.task.TaskExecutionConfiguration;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.autoconfigure.task.TaskExecutionAutoConfiguration;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.scheduling.annotation.AsyncAnnotationBeanPostProcessor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
@Slf4j
public class TaskExecutionTest {
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(TaskExecutionAutoConfiguration.class))
.withUserConfiguration(TaskDecoratorConfiguration.class, TaskExecutionConfiguration.class);
@Test
public void taskAsyncWithTracingDisabledTest() {
this.contextRunner
.withPropertyValues("management.tracing.enabled=false")
.run(context -> {
val taskExecutor = context.getBean(AsyncAnnotationBeanPostProcessor.DEFAULT_TASK_EXECUTOR_BEAN_NAME);
assertThat(taskExecutor).isNotNull();
assertThat(taskExecutor).isInstanceOf(ThreadPoolTaskExecutor.class);
if (taskExecutor instanceof ThreadPoolTaskExecutor threadPoolTaskExecutor) {
assertThat(threadPoolTaskExecutor.getCorePoolSize()).isEqualTo(4);
assertThat(threadPoolTaskExecutor.getMaxPoolSize()).isEqualTo(4);
assertThat(threadPoolTaskExecutor.getQueueCapacity()).isEqualTo(10_000);
assertThat(threadPoolTaskExecutor.getThreadNamePrefix()).isEqualTo("TenantAwareTaskExecutor-");
}
});
}
@Test
public void taskDecoratorWithTracingDisabledTest() {
this.contextRunner
.withPropertyValues("management.tracing.enabled=false")
.run(context -> {
val tenantAwareTaskDecoratorBean = context.getBean("tenantAwareTaskDecorator");
assertThat(tenantAwareTaskDecoratorBean).isNotNull();
assertThat(tenantAwareTaskDecoratorBean).isInstanceOf(TenantAwareTaskDecorator.class);
});
}
@Test
public void taskDecoratorWithTracingEnabledTest() {
this.contextRunner
.withPropertyValues("management.tracing.enabled=true")
.run(context -> {
val tenantAwareTaskDecoratorBean = context.getBean("tenantAwareTaskDecorator");
assertThat(tenantAwareTaskDecoratorBean).isNotNull();
assertThat(tenantAwareTaskDecoratorBean).isInstanceOf(TenantAwareTaskDecorator.class);
});
}
}

View File

@ -0,0 +1,79 @@
package com.knecon.fforesight.tenantcommons;
import static com.knecon.fforesight.tenantcommons.queue.TenantMessagingConfiguration.TENANT_EXCHANGE;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import static org.junit.jupiter.api.Assertions.fail;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
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.tenantcommons.model.TenantCreatedEvent;
import com.knecon.fforesight.tenantcommons.utils.TestMessage;
import com.knecon.fforesight.tenantcommons.utils.TestMessageService;
import com.knecon.fforesight.tenantcommons.utils.TestTenantProvider;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
public class TenantQueuesIntegrationTest extends BasicIntegrationTest {
@Autowired
private RabbitTemplate rabbitTemplate;
@Autowired
private TestTenantProvider tenantProvider;
@Autowired
private TestMessageService testMessageService;
@Autowired
private RabbitAdmin rabbitAdmin;
@Value("${fforesight.tenant-exchange.name:tenants-exchange}")
String tenantExchangeName;
@Test
@SneakyThrows
public void testTenantCreatedQueue() {
TenantContext.setTenantId("tenant1");
// create a new tenant
rabbitTemplate.convertAndSend(tenantExchangeName, "tenant.created", new TenantCreatedEvent("tenant1"));
// wait for message to send and be processed
int iterations = 0;
do {
iterations++;
Thread.sleep(1000);
if (iterations > 10) {
fail("Tenant not created within 10 seconds");
}
if (!tenantProvider.getTenants().isEmpty()) {
assertThat(tenantProvider.getTenant("tenant1")).isNotNull();
break;
}
} while (true);
rabbitTemplate.convertAndSend("testExchange", "tenant1", new TestMessage("Hello Tenant Commons!"));
iterations = 0;
do {
iterations++;
Thread.sleep(1000);
if (iterations > 10) {
fail("Message not sent within 10 seconds");
}
if (!testMessageService.getMessages().isEmpty()) {
break;
}
} while (true);
assertThat(testMessageService.getMessages().size()).isEqualTo(1);
assertThat(testMessageService.getMessages().get(0).getMessage()).isEqualTo("Hello Tenant Commons!");
}
}

View File

@ -0,0 +1,13 @@
package com.knecon.fforesight.tenantcommons.utils;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class TestMessage {
private String message;
}

View File

@ -0,0 +1,44 @@
package com.knecon.fforesight.tenantcommons.utils;
import java.util.ArrayList;
import java.util.List;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class TestMessageService {
public List<TestMessage> messages = new ArrayList<>();
@PostConstruct
protected void init() {
log.info("TestMessageService initialized");
}
@RabbitHandler
@RabbitListener(id = "testListener")
public void handleTestMessage(TestMessage message) {
log.info("Received message: {}", message);
addMessage(message);
}
public void addMessage(TestMessage message) {
messages.add(message);
}
public List<TestMessage> getMessages() {
return messages;
}
}

View File

@ -0,0 +1,56 @@
package com.knecon.fforesight.tenantcommons.utils;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Service;
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, ITenantEventHandler<TenantCreatedEvent> {
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 void handle(TenantCreatedEvent event) {
tenants.add(TenantResponse.builder()
.tenantId(event.getTenantId())
.build());
}
@Override
public Class<TenantCreatedEvent> getEventClass() {
return TenantCreatedEvent.class;
}
}

View File

@ -0,0 +1,19 @@
spring:
application:
name: 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
logging.type: ${LOGGING_TYPE:CONSOLE}

View File

@ -0,0 +1,13 @@
<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>

View File

@ -0,0 +1 @@
hub.image.name.prefix=docker-dev.knecon.com/tests/