This is an automated email from the ASF dual-hosted git repository. ikamga pushed a commit to branch develop in repository https://gitbox.apache.org/repos/asf/fineract-cn-mariadb.git
commit 6f0c108d092310cdc026362a6e06e148d3952275 Author: myrle-krantz <[email protected]> AuthorDate: Tue Mar 14 10:42:19 2017 +0100 Open sourcing core.mariadb. --- .gitignore | 14 ++ HEADER | 13 ++ README.md | 41 +++++ build.gradle | 81 ++++++++++ gradle/wrapper/gradle-wrapper.jar | Bin 0 -> 54212 bytes gradle/wrapper/gradle-wrapper.properties | 6 + gradlew | 172 +++++++++++++++++++++ gradlew.bat | 84 ++++++++++ settings.gradle | 1 + .../mifos/core/mariadb/config/EnableMariaDB.java | 34 ++++ .../mariadb/config/MariaDBJavaConfiguration.java | 139 +++++++++++++++++ .../domain/ContextAwareRoutingDataSource.java | 116 ++++++++++++++ .../core/mariadb/domain/FlywayFactoryBean.java | 41 +++++ .../java/io/mifos/core/mariadb/domain/Tenant.java | 85 ++++++++++ .../io/mifos/core/mariadb/util/JdbcUrlBuilder.java | 74 +++++++++ .../core/mariadb/util/LocalDateConverter.java | 49 ++++++ .../core/mariadb/util/LocalDateTimeConverter.java | 49 ++++++ .../mifos/core/mariadb/util/MariaDBConstants.java | 49 ++++++ .../core/mariadb/util/JdbcUrlBuilderTest.java | 40 +++++ 19 files changed, 1088 insertions(+) diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..97a9529 --- /dev/null +++ b/.gitignore @@ -0,0 +1,14 @@ +.gradle +.idea +build/ +target/ + +# Ignore Gradle GUI config +gradle-app.setting + +# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) +!gradle-wrapper.jar + +*.iml + +*.log \ No newline at end of file diff --git a/HEADER b/HEADER new file mode 100644 index 0000000..d47a70e --- /dev/null +++ b/HEADER @@ -0,0 +1,13 @@ +Copyright ${year} ${name}. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/README.md b/README.md new file mode 100644 index 0000000..90a94a9 --- /dev/null +++ b/README.md @@ -0,0 +1,41 @@ +# Mifos I/O Core MariaDB + +[](https://gitter.im/mifos-initiative/mifos.io?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) + +This project is an umbrella for all Mifos I/O Core components. + +## Abstract +Mifos I/O is an application framework for digital financial services, a system to support nationwide and cross-national financial transactions and help to level and speed the creation of an inclusive, interconnected digital economy for every nation in the world. + +## Prerequisites +### Runtime +Install Java 8 as described at https://docs.oracle.com/javase/8/docs/technotes/guides/install/install_overview.html. + +### Installation +Install MariaDB as described at https://mariadb.com/kb/en/mariadb/binary-packages/. + +After installation you need to create the meta database: + + mysql -u root -pmysql + CREATE DATABASE IF NOT EXISTS system_console; + +## Multi-tenancy +Multi-tenancy is reached by providing separate data storage on a per tenant basis. + +For every tenant a new database instance is created internally. A tenant aware component provides transparent access to these resources. + +## Versioning +The version numbers follow the [Semantic Versioning](http://semver.org/) scheme. + +In addition to MAJOR.MINOR.PATCH the following postfixes are used to indicate the development state. + +* BUILD-SNAPSHOT - A release currently in development. +* RELEASE - _General availability_ indicates that this release is the best available version and is recommended for all usage. + +The versioning layout is {MAJOR}.{MINOR}.{PATCH}-{INDICATOR}[.{PATCH}]. Only milestones and release candidates can have patch versions. Some examples: + +1.2.3-BUILD-SNAPSHOT +1.3.5-RELEASE + +## License +See [LICENSE](LICENSE) file. diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..152c6e5 --- /dev/null +++ b/build.gradle @@ -0,0 +1,81 @@ +buildscript { + repositories { + jcenter(); + } +} + +plugins { + id 'com.github.hierynomus.license' version '0.13.1' +} + +group 'io.mifos.core' +version '0.1.0-BUILD-SNAPSHOT' + +ext.versions = [ + springcontext : '4.3.3.RELEASE', + springboot : '1.4.1.RELEASE', + findbugs : '3.0.1', + frameworklang : '0.1.0-BUILD-SNAPSHOT' +] + +apply plugin: 'java' +apply plugin: 'idea' +apply plugin: 'maven' +apply plugin: 'maven-publish' +apply plugin: 'license' + +tasks.withType(JavaCompile) { + sourceCompatibility = JavaVersion.VERSION_1_8 + targetCompatibility = JavaVersion.VERSION_1_8 +} + +repositories { + jcenter() + mavenLocal() +} + +dependencies { + compile( + [group: 'org.springframework', name: 'spring-context', version: versions.springcontext], + [group: 'com.google.code.findbugs', name: 'jsr305', version: versions.findbugs], + [group: 'io.mifos.core', name: 'lang', version: versions.frameworklang], + [group: 'org.springframework.boot', name: 'spring-boot-starter-data-jpa', version: versions.springboot], + [group: 'com.jolbox', name: 'bonecp', version: '0.8.0.RELEASE'], + [group: 'org.flywaydb', name: 'flyway-core', version: '4.0.1'] + ) + + //Workaround for bug described here: https://discuss.gradle.org/t/build-failure-when-4-1-0-of-net-java-dev-jna-jna-is-selected-in-place-of-3-3-0-due-to-change-in-artifacts-with-classifiers/9377/3 + //These two compiled of jna and the exclude under mariadb-java-client may be removable once + //the bug is fixed in gradle. + compile('org.mariadb.jdbc:mariadb-java-client:1.4.3') { + exclude group: 'net.java.dev.jna' + } + + compile 'net.java.dev.jna:jna:4.1.0' + compile 'net.java.dev.jna:jna-platform:4.1.0' + + testCompile( + [group: 'org.springframework.boot', name: 'spring-boot-starter-test', version: versions.springboot] + ) +} + +publishing { + publications { + mariadbPublication(MavenPublication) { + from components.java + groupId project.group + artifactId project.name + version project.version + } + } +} + +license { + header rootProject.file('HEADER') + strictCheck true + mapping { + java = 'SLASHSTAR_STYLE' + } + ext.year = Calendar.getInstance().get(Calendar.YEAR) + ext.name = 'The Mifos Initiative' +} \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..a84e6fd Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..ab59e12 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Tue Mar 14 10:20:00 CET 2017 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-3.4.1-bin.zip diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..4453cce --- /dev/null +++ b/gradlew @@ -0,0 +1,172 @@ +#!/usr/bin/env sh + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn ( ) { + echo "$*" +} + +die ( ) { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save ( ) { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=$(save "$@") + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong +if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then + cd "$(dirname "$0")" +fi + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..e95643d --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,84 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..4a2128f --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'mariadb' \ No newline at end of file diff --git a/src/main/java/io/mifos/core/mariadb/config/EnableMariaDB.java b/src/main/java/io/mifos/core/mariadb/config/EnableMariaDB.java new file mode 100644 index 0000000..b756123 --- /dev/null +++ b/src/main/java/io/mifos/core/mariadb/config/EnableMariaDB.java @@ -0,0 +1,34 @@ +/* + * Copyright 2017 The Mifos Initiative. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package io.mifos.core.mariadb.config; + +import org.springframework.context.annotation.Import; + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Inherited; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Target(ElementType.TYPE) +@Retention(RetentionPolicy.RUNTIME) +@Documented +@Inherited +@Import({MariaDBJavaConfiguration.class}) +public @interface EnableMariaDB { + +} diff --git a/src/main/java/io/mifos/core/mariadb/config/MariaDBJavaConfiguration.java b/src/main/java/io/mifos/core/mariadb/config/MariaDBJavaConfiguration.java new file mode 100644 index 0000000..2e5be65 --- /dev/null +++ b/src/main/java/io/mifos/core/mariadb/config/MariaDBJavaConfiguration.java @@ -0,0 +1,139 @@ +/* + * Copyright 2017 The Mifos Initiative. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package io.mifos.core.mariadb.config; + +import com.jolbox.bonecp.BoneCPDataSource; +import io.mifos.core.lang.ApplicationName; +import io.mifos.core.lang.config.EnableApplicationName; +import io.mifos.core.mariadb.domain.ContextAwareRoutingDataSource; +import io.mifos.core.mariadb.domain.FlywayFactoryBean; +import io.mifos.core.mariadb.util.JdbcUrlBuilder; +import io.mifos.core.mariadb.util.MariaDBConstants; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.Environment; +import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor; +import org.springframework.orm.jpa.JpaTransactionManager; +import org.springframework.orm.jpa.JpaVendorAdapter; +import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; +import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +import javax.persistence.EntityManagerFactory; +import javax.sql.DataSource; +import java.util.HashMap; +import java.util.Properties; + +@SuppressWarnings("WeakerAccess") +@Configuration +@ConditionalOnProperty(prefix = "mariadb", name = "enabled", matchIfMissing = true) +@EnableTransactionManagement +@EnableApplicationName +public class MariaDBJavaConfiguration { + + private final Environment env; + + @Autowired + public MariaDBJavaConfiguration(final Environment env) { + super(); + this.env = env; + } + + @Bean(name = MariaDBConstants.LOGGER_NAME) + public Logger logger() { + return LoggerFactory.getLogger(MariaDBConstants.LOGGER_NAME); + } + + @Bean + public LocalContainerEntityManagerFactoryBean entityManagerFactory(final DataSource dataSource) { + final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); + em.setPersistenceUnitName("metaPU"); + em.setDataSource(dataSource); + em.setPackagesToScan("io.mifos.**.repository"); + + final JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); + em.setJpaVendorAdapter(vendorAdapter); + em.setJpaProperties(additionalProperties()); + + return em; + } + + @Bean + public DataSource dataSource(@Qualifier(MariaDBConstants.LOGGER_NAME) final Logger logger) { + final BoneCPDataSource boneCPDataSource = new BoneCPDataSource(); + boneCPDataSource.setDriverClass( + this.env.getProperty(MariaDBConstants.MARIADB_DRIVER_CLASS_PROP, MariaDBConstants.MARIADB_DRIVER_CLASS_DEFAULT)); + boneCPDataSource.setJdbcUrl(JdbcUrlBuilder + .create(JdbcUrlBuilder.DatabaseType.MARIADB) + .host(this.env.getProperty(MariaDBConstants.MARIADB_HOST_PROP, MariaDBConstants.MARIADB_HOST_DEFAULT)) + .port(this.env.getProperty(MariaDBConstants.MARIADB_PORT_PROP, MariaDBConstants.MARIADB_PORT_DEFAULT)) + .instanceName(this.env.getProperty(MariaDBConstants.MARIADB_DATABASE_NAME_PROP, MariaDBConstants.MARIADB_DATABASE_NAME_DEFAULT)) + .build()); + boneCPDataSource.setUsername( + this.env.getProperty(MariaDBConstants.MARIADB_USER_PROP, MariaDBConstants.MARIADB_USER_DEFAULT)); + boneCPDataSource.setPassword( + this.env.getProperty(MariaDBConstants.MARIADB_PASSWORD_PROP, MariaDBConstants.MARIADB_PASSWORD_DEFAULT)); + boneCPDataSource.setIdleConnectionTestPeriodInMinutes( + Long.valueOf(this.env.getProperty(MariaDBConstants.BONECP_IDLE_CONNECTION_TEST_PROP, MariaDBConstants.BONECP_IDLE_CONNECTION_TEST_DEFAULT))); + boneCPDataSource.setIdleMaxAgeInMinutes( + Long.valueOf(this.env.getProperty(MariaDBConstants.BONECP_IDLE_MAX_AGE_PROP, MariaDBConstants.BONECP_IDLE_MAX_AGE_DEFAULT))); + boneCPDataSource.setMaxConnectionsPerPartition( + Integer.valueOf(this.env.getProperty(MariaDBConstants.BONECP_MAX_CONNECTION_PARTITION_PROP, MariaDBConstants.BONECP_MAX_CONNECTION_PARTITION_DEFAULT))); + boneCPDataSource.setMinConnectionsPerPartition( + Integer.valueOf(this.env.getProperty(MariaDBConstants.BONECP_MIN_CONNECTION_PARTITION_PROP, MariaDBConstants.BONECP_MIN_CONNECTION_PARTITION_DEFAULT))); + boneCPDataSource.setPartitionCount( + Integer.valueOf(this.env.getProperty(MariaDBConstants.BONECP_PARTITION_COUNT_PROP, MariaDBConstants.BONECP_PARTITION_COUNT_DEFAULT))); + boneCPDataSource.setAcquireIncrement( + Integer.valueOf(this.env.getProperty(MariaDBConstants.BONECP_ACQUIRE_INCREMENT_PROP, MariaDBConstants.BONECP_ACQUIRE_INCREMENT_DEFAULT))); + boneCPDataSource.setStatementsCacheSize( + Integer.valueOf(this.env.getProperty(MariaDBConstants.BONECP_STATEMENT_CACHE_PROP, MariaDBConstants.BONECP_STATEMENT_CACHE_DEFAULT))); + + final ContextAwareRoutingDataSource dataSource = new ContextAwareRoutingDataSource(logger, JdbcUrlBuilder.DatabaseType.MARIADB); + dataSource.setMetaDataSource(boneCPDataSource); + final HashMap<Object, Object> targetDataSources = new HashMap<>(); + dataSource.setTargetDataSources(targetDataSources); + return dataSource; + } + + @Bean + public PlatformTransactionManager transactionManager(EntityManagerFactory emf) { + final JpaTransactionManager transactionManager = new JpaTransactionManager(); + transactionManager.setEntityManagerFactory(emf); + return transactionManager; + } + + @Bean + public PersistenceExceptionTranslationPostProcessor exceptionTranslation() { + return new PersistenceExceptionTranslationPostProcessor(); + } + + @Bean + public FlywayFactoryBean flywayFactoryBean(final ApplicationName applicationName) { + return new FlywayFactoryBean(applicationName); + } + + private Properties additionalProperties() { + final Properties properties = new Properties(); + properties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect"); + return properties; + } +} diff --git a/src/main/java/io/mifos/core/mariadb/domain/ContextAwareRoutingDataSource.java b/src/main/java/io/mifos/core/mariadb/domain/ContextAwareRoutingDataSource.java new file mode 100644 index 0000000..4614d1a --- /dev/null +++ b/src/main/java/io/mifos/core/mariadb/domain/ContextAwareRoutingDataSource.java @@ -0,0 +1,116 @@ +/* + * Copyright 2017 The Mifos Initiative. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package io.mifos.core.mariadb.domain; + +import com.jolbox.bonecp.BoneCPDataSource; +import io.mifos.core.lang.TenantContextHolder; +import io.mifos.core.mariadb.util.JdbcUrlBuilder; +import io.mifos.core.mariadb.util.MariaDBConstants; +import org.slf4j.Logger; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource; + +import javax.sql.DataSource; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.concurrent.ConcurrentHashMap; + +public final class ContextAwareRoutingDataSource extends AbstractRoutingDataSource { + + private final Logger logger; + private final JdbcUrlBuilder.DatabaseType type; + private final ConcurrentHashMap<String, DataSource> dynamicDataSources; + private DataSource metaDataSource; + + public ContextAwareRoutingDataSource(@Qualifier(MariaDBConstants.LOGGER_NAME) final Logger logger, + final JdbcUrlBuilder.DatabaseType type) { + super(); + this.logger = logger; + this.type = type; + this.dynamicDataSources = new ConcurrentHashMap<>(); + } + + public void setMetaDataSource(final DataSource metaDataSource) { + this.metaDataSource = metaDataSource; + super.setDefaultTargetDataSource(metaDataSource); + } + + @Override + protected Object determineCurrentLookupKey() { + return TenantContextHolder.checkedGetIdentifier(); + } + + @Override + protected DataSource determineTargetDataSource() { + if (!TenantContextHolder.identifier().isPresent()) { + this.logger.warn("Tenant context not available."); + return super.determineTargetDataSource(); + } + + final String currentLookupKey = this.determineCurrentLookupKey().toString(); + + this.dynamicDataSources.computeIfAbsent(currentLookupKey, (key) -> { + this.logger.info("Creating new dynamic data source for {}.", currentLookupKey); + final Tenant tenant = new Tenant(currentLookupKey); + this.readAdditionalTenantInformation(tenant); + final BoneCPDataSource tenantDataSource = new BoneCPDataSource(); + tenantDataSource.setDriverClass(tenant.getDriverClass()); + tenantDataSource.setJdbcUrl(JdbcUrlBuilder + .create(this.type) + .host(tenant.getHost()) + .port(tenant.getPort()) + .instanceName(tenant.getDatabaseName()) + .build()); + tenantDataSource.setUsername(tenant.getUser()); + tenantDataSource.setPassword(tenant.getPassword()); + + final BoneCPDataSource boneCpMetaDataSource = (BoneCPDataSource) this.metaDataSource; + tenantDataSource.setIdleConnectionTestPeriodInMinutes(boneCpMetaDataSource.getIdleConnectionTestPeriodInMinutes()); + tenantDataSource.setIdleMaxAgeInMinutes(boneCpMetaDataSource.getIdleMaxAgeInMinutes()); + tenantDataSource.setMaxConnectionsPerPartition(boneCpMetaDataSource.getMaxConnectionsPerPartition()); + tenantDataSource.setMinConnectionsPerPartition(boneCpMetaDataSource.getMinConnectionsPerPartition()); + tenantDataSource.setPartitionCount(boneCpMetaDataSource.getPartitionCount()); + tenantDataSource.setAcquireIncrement(boneCpMetaDataSource.getAcquireIncrement()); + tenantDataSource.setStatementsCacheSize(boneCpMetaDataSource.getStatementsCacheSize()); + return tenantDataSource; + }); + + return this.dynamicDataSources.get(currentLookupKey); + } + + private void readAdditionalTenantInformation(final Tenant tenant) { + this.logger.info("Reading additional information for {}.", tenant.getIdentifier()); + @SuppressWarnings({"SqlDialectInspection", "SqlNoDataSourceInspection"}) final String query = "SELECT driver_class, database_name, host, port, a_user, pwd FROM seshat.tenants WHERE identifier = ?"; + try (final Connection connection = this.metaDataSource.getConnection()) { + try (final PreparedStatement preparedStatement = connection.prepareStatement(query)) { + preparedStatement.setString(1, tenant.getIdentifier()); + final ResultSet resultSet = preparedStatement.executeQuery(); + if (resultSet.next()) { + tenant.setDriverClass(resultSet.getString("driver_class")); + tenant.setDatabaseName(resultSet.getString("database_name")); + tenant.setHost(resultSet.getString("host")); + tenant.setPort(resultSet.getString("port")); + tenant.setUser(resultSet.getString("a_user")); + tenant.setPassword(resultSet.getString("pwd")); + } + } + } catch (SQLException ex) { + throw new IllegalArgumentException("Could not fetch information for tenant '" + tenant.getIdentifier() + "'", ex); + } + } +} diff --git a/src/main/java/io/mifos/core/mariadb/domain/FlywayFactoryBean.java b/src/main/java/io/mifos/core/mariadb/domain/FlywayFactoryBean.java new file mode 100644 index 0000000..a01ee7b --- /dev/null +++ b/src/main/java/io/mifos/core/mariadb/domain/FlywayFactoryBean.java @@ -0,0 +1,41 @@ +/* + * Copyright 2017 The Mifos Initiative. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package io.mifos.core.mariadb.domain; + +import io.mifos.core.lang.ApplicationName; +import org.flywaydb.core.Flyway; + +import javax.sql.DataSource; + +public class FlywayFactoryBean { + + private final ApplicationName applicationName; + + public FlywayFactoryBean(final ApplicationName applicationName) { + super(); + this.applicationName = applicationName; + } + + public Flyway create(final DataSource dataSource) { + final Flyway flyway = new Flyway(); + flyway.setDataSource(dataSource); + flyway.setLocations("db/migrations/mariadb"); + flyway.setTable(this.applicationName.getServiceName() + "_schema_version"); + flyway.setBaselineOnMigrate(true); + flyway.setBaselineVersionAsString("0"); + return flyway; + } +} diff --git a/src/main/java/io/mifos/core/mariadb/domain/Tenant.java b/src/main/java/io/mifos/core/mariadb/domain/Tenant.java new file mode 100644 index 0000000..7997cce --- /dev/null +++ b/src/main/java/io/mifos/core/mariadb/domain/Tenant.java @@ -0,0 +1,85 @@ +/* + * Copyright 2017 The Mifos Initiative. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package io.mifos.core.mariadb.domain; + +@SuppressWarnings("WeakerAccess") +public final class Tenant { + + private final String identifier; + private String driverClass; + private String databaseName; + private String host; + private String port; + private String user; + private String password; + + public Tenant(final String identifier) { + super(); + this.identifier = identifier; + } + + public String getIdentifier() { + return identifier; + } + + public String getDriverClass() { + return driverClass; + } + + public void setDriverClass(String driverClass) { + this.driverClass = driverClass; + } + + public String getDatabaseName() { + return databaseName; + } + + public void setDatabaseName(String databaseName) { + this.databaseName = databaseName; + } + + public String getHost() { + return host; + } + + public void setHost(String host) { + this.host = host; + } + + public String getPort() { + return port; + } + + public void setPort(String port) { + this.port = port; + } + + public String getUser() { + return user; + } + + public void setUser(String user) { + this.user = user; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } +} diff --git a/src/main/java/io/mifos/core/mariadb/util/JdbcUrlBuilder.java b/src/main/java/io/mifos/core/mariadb/util/JdbcUrlBuilder.java new file mode 100644 index 0000000..3c2576d --- /dev/null +++ b/src/main/java/io/mifos/core/mariadb/util/JdbcUrlBuilder.java @@ -0,0 +1,74 @@ +/* + * Copyright 2017 The Mifos Initiative. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package io.mifos.core.mariadb.util; + +public final class JdbcUrlBuilder { + + private final DatabaseType type; + private String host; + private String port; + private String instanceName; + + private JdbcUrlBuilder(final DatabaseType type) { + super(); + this.type = type; + } + + public static JdbcUrlBuilder create(final DatabaseType type) { + return new JdbcUrlBuilder(type); + } + + public JdbcUrlBuilder host(final String host) { + this.host = host; + return this; + } + + public JdbcUrlBuilder port(final String port) { + this.port = port; + return this; + } + + public JdbcUrlBuilder instanceName(final String instanceName) { + this.instanceName = instanceName; + return this; + } + + public String build() { + switch (this.type) { + case MARIADB: + return this.type.prefix() + + this.host + ":" + + this.port + + (this.instanceName != null ? "/" + this.instanceName : ""); + default: + throw new IllegalArgumentException("Unknown database type '" + this.type.name() + "'"); + } + } + + public enum DatabaseType { + MARIADB("jdbc:mariadb://"); + + private final String prefix; + + DatabaseType(final String prefix) { + this.prefix = prefix; + } + + String prefix() { + return this.prefix; + } + } +} diff --git a/src/main/java/io/mifos/core/mariadb/util/LocalDateConverter.java b/src/main/java/io/mifos/core/mariadb/util/LocalDateConverter.java new file mode 100644 index 0000000..73b4f0b --- /dev/null +++ b/src/main/java/io/mifos/core/mariadb/util/LocalDateConverter.java @@ -0,0 +1,49 @@ +/* + * Copyright 2017 The Mifos Initiative. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package io.mifos.core.mariadb.util; + +import io.mifos.core.lang.DateConverter; + +import javax.persistence.AttributeConverter; +import javax.persistence.Converter; +import java.sql.Date; +import java.time.LocalDate; + +@Converter +public class LocalDateConverter implements AttributeConverter<LocalDate, Date> { + + public LocalDateConverter() { + super(); + } + + @Override + public Date convertToDatabaseColumn(final LocalDate attribute) { + if (attribute == null) { + return null; + } else { + return new Date(DateConverter.toEpochDay(attribute)); + } + } + + @Override + public LocalDate convertToEntityAttribute(final Date dbData) { + if (dbData == null) { + return null; + } else { + return DateConverter.toLocalDate(DateConverter.fromEpochMillis(dbData.getTime())); + } + } +} diff --git a/src/main/java/io/mifos/core/mariadb/util/LocalDateTimeConverter.java b/src/main/java/io/mifos/core/mariadb/util/LocalDateTimeConverter.java new file mode 100644 index 0000000..f78fa94 --- /dev/null +++ b/src/main/java/io/mifos/core/mariadb/util/LocalDateTimeConverter.java @@ -0,0 +1,49 @@ +/* + * Copyright 2017 The Mifos Initiative. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package io.mifos.core.mariadb.util; + +import io.mifos.core.lang.DateConverter; + +import javax.persistence.AttributeConverter; +import javax.persistence.Converter; +import java.sql.Timestamp; +import java.time.LocalDateTime; + +@Converter +public class LocalDateTimeConverter implements AttributeConverter<LocalDateTime, Timestamp> { + + public LocalDateTimeConverter() { + super(); + } + + @Override + public Timestamp convertToDatabaseColumn(final LocalDateTime attribute) { + if (attribute == null) { + return null; + } else { + return new Timestamp(DateConverter.toEpochMillis(attribute)); + } + } + + @Override + public LocalDateTime convertToEntityAttribute(final Timestamp dbData) { + if (dbData == null) { + return null; + } else { + return DateConverter.fromEpochMillis(dbData.getTime()); + } + } +} diff --git a/src/main/java/io/mifos/core/mariadb/util/MariaDBConstants.java b/src/main/java/io/mifos/core/mariadb/util/MariaDBConstants.java new file mode 100644 index 0000000..fb626c0 --- /dev/null +++ b/src/main/java/io/mifos/core/mariadb/util/MariaDBConstants.java @@ -0,0 +1,49 @@ +/* + * Copyright 2017 The Mifos Initiative. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package io.mifos.core.mariadb.util; + +public interface MariaDBConstants { + + String LOGGER_NAME = "maridb-logger"; + + String MARIADB_DRIVER_CLASS_PROP = "mariadb.driverClass"; + String MARIADB_DRIVER_CLASS_DEFAULT = "org.mariadb.jdbc.Driver"; + String MARIADB_DATABASE_NAME_PROP = "mariadb.database"; + String MARIADB_DATABASE_NAME_DEFAULT = "seshat"; + String MARIADB_HOST_PROP = "mariadb.host"; + String MARIADB_HOST_DEFAULT = "localhost"; + String MARIADB_PORT_PROP = "mariadb.port"; + String MARIADB_PORT_DEFAULT = "3306"; + String MARIADB_USER_PROP = "mariadb.user"; + String MARIADB_USER_DEFAULT = "root"; + String MARIADB_PASSWORD_PROP = "mariadb.password"; + String MARIADB_PASSWORD_DEFAULT = "mysql"; + + String BONECP_IDLE_MAX_AGE_PROP = "bonecp.idleMaxAgeInMinutes"; + String BONECP_IDLE_MAX_AGE_DEFAULT = "240"; + String BONECP_IDLE_CONNECTION_TEST_PROP = "bonecp.idleConnectionTestPeriodInMinutes"; + String BONECP_IDLE_CONNECTION_TEST_DEFAULT = "60"; + String BONECP_MAX_CONNECTION_PARTITION_PROP = "bonecp.maxConnectionsPerPartition"; + String BONECP_MAX_CONNECTION_PARTITION_DEFAULT = "16"; + String BONECP_MIN_CONNECTION_PARTITION_PROP = "bonecp.minConnectionsPerPartition"; + String BONECP_MIN_CONNECTION_PARTITION_DEFAULT = "4"; + String BONECP_PARTITION_COUNT_PROP = "bonecp.partitionCount"; + String BONECP_PARTITION_COUNT_DEFAULT = "2"; + String BONECP_ACQUIRE_INCREMENT_PROP = "bonecp.acquireIncrement"; + String BONECP_ACQUIRE_INCREMENT_DEFAULT = "4"; + String BONECP_STATEMENT_CACHE_PROP = "bonecp.statementsCacheSize"; + String BONECP_STATEMENT_CACHE_DEFAULT = "128"; +} diff --git a/src/test/java/io/mifos/core/mariadb/util/JdbcUrlBuilderTest.java b/src/test/java/io/mifos/core/mariadb/util/JdbcUrlBuilderTest.java new file mode 100644 index 0000000..550e5bc --- /dev/null +++ b/src/test/java/io/mifos/core/mariadb/util/JdbcUrlBuilderTest.java @@ -0,0 +1,40 @@ +/* + * Copyright 2017 The Mifos Initiative. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package io.mifos.core.mariadb.util; + +import org.junit.Assert; +import org.junit.Test; + +public class JdbcUrlBuilderTest { + + private final static String MARIADB_JDBC_URL = "jdbc:mariadb://localhost:3306/comp_test"; + + public JdbcUrlBuilderTest() { + super(); + } + + @Test + public void shouldCreateMysqlUrl() { + final String mariaDbJdbcUrl = JdbcUrlBuilder + .create(JdbcUrlBuilder.DatabaseType.MARIADB) + .host("localhost") + .port("3306") + .instanceName("comp_test") + .build(); + + Assert.assertEquals(MARIADB_JDBC_URL, mariaDbJdbcUrl); + } +} \ No newline at end of file
