From commits-return-1236-archive-asf-public=cust-asf.ponee.io@fineract.apache.org Mon Jan 22 16:10:05 2018 Return-Path: X-Original-To: archive-asf-public@eu.ponee.io Delivered-To: archive-asf-public@eu.ponee.io Received: from cust-asf.ponee.io (cust-asf.ponee.io [163.172.22.183]) by mx-eu-01.ponee.io (Postfix) with ESMTP id 78460180609 for ; Mon, 22 Jan 2018 16:10:05 +0100 (CET) Received: by cust-asf.ponee.io (Postfix) id 67104160C3A; Mon, 22 Jan 2018 15:10:05 +0000 (UTC) Delivered-To: archive-asf-public@cust-asf.ponee.io Received: from mail.apache.org (hermes.apache.org [140.211.11.3]) by cust-asf.ponee.io (Postfix) with SMTP id 05D0F160C4E for ; Mon, 22 Jan 2018 16:10:02 +0100 (CET) Received: (qmail 53542 invoked by uid 500); 22 Jan 2018 15:10:02 -0000 Mailing-List: contact commits-help@fineract.apache.org; run by ezmlm Precedence: bulk List-Help: List-Unsubscribe: List-Post: List-Id: Reply-To: dev@fineract.apache.org Delivered-To: mailing list commits@fineract.apache.org Received: (qmail 53385 invoked by uid 99); 22 Jan 2018 15:10:02 -0000 Received: from ec2-52-202-80-70.compute-1.amazonaws.com (HELO gitbox.apache.org) (52.202.80.70) by apache.org (qpsmtpd/0.29) with ESMTP; Mon, 22 Jan 2018 15:10:02 +0000 Received: by gitbox.apache.org (ASF Mail Server at gitbox.apache.org, from userid 33) id 7720A81FC4; Mon, 22 Jan 2018 15:10:01 +0000 (UTC) Date: Mon, 22 Jan 2018 15:10:02 +0000 To: "commits@fineract.apache.org" Subject: [fineract-cn-cassandra] 01/05: Open sourcing core.cassandra. MIME-Version: 1.0 Content-Type: text/plain; charset=utf-8 Content-Transfer-Encoding: 8bit From: myrle@apache.org In-Reply-To: <151663380136.22869.196159577589289981@gitbox.apache.org> References: <151663380136.22869.196159577589289981@gitbox.apache.org> X-Git-Host: gitbox.apache.org X-Git-Repo: fineract-cn-cassandra X-Git-Refname: refs/heads/develop X-Git-Reftype: branch X-Git-Rev: 29e99b22d39a72e9b2677466a66691f71e18836f X-Git-NotificationType: diff X-Git-Multimail-Version: 1.5.dev Auto-Submitted: auto-generated Message-Id: <20180122151001.7720A81FC4@gitbox.apache.org> This is an automated email from the ASF dual-hosted git repository. myrle pushed a commit to branch develop in repository https://gitbox.apache.org/repos/asf/fineract-cn-cassandra.git commit 29e99b22d39a72e9b2677466a66691f71e18836f Author: myrle-krantz AuthorDate: Tue Mar 14 10:01:59 2017 +0100 Open sourcing core.cassandra. --- .gitignore | 14 ++ HEADER | 13 ++ LICENSE | 201 +++++++++++++++++++++ README.md | 45 +++++ build.gradle | 72 ++++++++ gradle/wrapper/gradle-wrapper.jar | Bin 0 -> 54212 bytes gradle/wrapper/gradle-wrapper.properties | 6 + gradlew | 172 ++++++++++++++++++ gradlew.bat | 84 +++++++++ settings.gradle | 1 + .../config/CassandraConnectorConfiguration.java | 86 +++++++++ .../core/cassandra/config/EnableCassandra.java | 35 ++++ .../core/cassandra/core/CassandraJourney.java | 93 ++++++++++ .../cassandra/core/CassandraJourneyFactory.java | 41 +++++ .../core/cassandra/core/CassandraJourneyRoute.java | 73 ++++++++ .../cassandra/core/CassandraJourneyWaypoint.java | 35 ++++ .../cassandra/core/CassandraSessionProvider.java | 193 ++++++++++++++++++++ .../cassandra/core/KeyspaceDoesntExistYet.java | 27 +++ .../mifos/core/cassandra/core/OptionProvider.java | 82 +++++++++ .../core/ReplicationStrategyResolver.java | 52 ++++++ .../core/TenantAwareCassandraMapperProvider.java | 83 +++++++++ .../cassandra/core/TenantAwareEntityTemplate.java | 64 +++++++ .../io/mifos/core/cassandra/domain/Tenant.java | 87 +++++++++ .../util/CassandraConnectorConstants.java | 41 +++++ .../mifos/core/cassandra/util/CodecRegistry.java | 48 +++++ .../core/cassandra/util/ContactPointUtils.java | 46 +++++ .../core/cassandra/util/LocalDateTimeCodec.java | 66 +++++++ .../core/cassandra/core/OptionProviderTest.java | 66 +++++++ .../core/ReplicationStrategyResolverTest.java | 47 +++++ .../core/cassandra/util/ContactPointUtilsTest.java | 66 +++++++ 30 files changed, 1939 insertions(+) diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..536de5a --- /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/LICENSE b/LICENSE new file mode 100644 index 0000000..8dada3e --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + 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..5e2da0d --- /dev/null +++ b/README.md @@ -0,0 +1,45 @@ +# Mifos I/O Core Cassandra + +[![Join the chat at https://gitter.im/mifos-initiative/mifos.io](https://badges.gitter.im/Join%20Chat.svg)](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 Apache Cassandra as described at https://wiki.apache.org/cassandra/GettingStarted. + +After installation you need to create the meta keyspace: + + cqlsh + CREATE KEYSPACE IF NOT EXISTS system_console + WITH REPLICATION = { + 'class' : 'SimpleStrategy', + 'replication_factor' : 3 + }; + +## Multi-tenancy +Multi-tenancy is reached by providing separate data storage on a per tenant basis. + +For every tenant a new keyspace 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..d255d4b --- /dev/null +++ b/build.gradle @@ -0,0 +1,72 @@ +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: 'com.datastax.cassandra', name: 'cassandra-driver-core', version: '3.0.1'], + [group: 'com.datastax.cassandra', name: 'cassandra-driver-mapping', version: '3.0.1'], + [group: 'com.datastax.cassandra', name: 'cassandra-driver-extras', version: '3.0.1'] + ) + + testCompile( + [group: 'org.springframework.boot', name: 'spring-boot-starter-test', version: versions.springboot] + ) +} + + +publishing { + publications { + cassandraPublication(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..6a1cf85 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..beb1e46 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Tue Mar 14 09:53:15 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..3a97b9a --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'cassandra' \ No newline at end of file diff --git a/src/main/java/io/mifos/core/cassandra/config/CassandraConnectorConfiguration.java b/src/main/java/io/mifos/core/cassandra/config/CassandraConnectorConfiguration.java new file mode 100644 index 0000000..357d64c --- /dev/null +++ b/src/main/java/io/mifos/core/cassandra/config/CassandraConnectorConfiguration.java @@ -0,0 +1,86 @@ +/* + * 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.cassandra.config; + +import io.mifos.core.cassandra.core.CassandraJourneyFactory; +import io.mifos.core.cassandra.core.CassandraSessionProvider; +import io.mifos.core.cassandra.core.TenantAwareCassandraMapperProvider; +import io.mifos.core.cassandra.core.TenantAwareEntityTemplate; +import io.mifos.core.cassandra.util.CassandraConnectorConstants; +import io.mifos.core.lang.ApplicationName; +import io.mifos.core.lang.config.EnableApplicationName; +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; + +@SuppressWarnings("WeakerAccess") +@Configuration +@ConditionalOnProperty(prefix = "cassandra", name = "enabled", matchIfMissing = true) +@EnableApplicationName +public class CassandraConnectorConfiguration { + + private final Environment env; + + private final ApplicationName applicationName; + + @Autowired + public CassandraConnectorConfiguration(final ApplicationName applicationName, final Environment env) { + super(); + this.applicationName = applicationName; + this.env = env; + } + + @Bean(name = CassandraConnectorConstants.LOGGER_NAME) + public Logger loggerBean() { + return LoggerFactory.getLogger(CassandraConnectorConstants.LOGGER_NAME); + } + + @Bean + public CassandraSessionProvider cassandraSessionProvider(@Qualifier(CassandraConnectorConstants.LOGGER_NAME) final Logger logger) { + final CassandraSessionProvider cassandraSessionProvider = new CassandraSessionProvider(this.env, logger); + cassandraSessionProvider.setAdminClusterName( + this.env.getProperty(CassandraConnectorConstants.CLUSTER_NAME_PROP, CassandraConnectorConstants.CLUSTER_NAME_PROP_DEFAULT)); + cassandraSessionProvider.setAdminContactPoints( + this.env.getProperty(CassandraConnectorConstants.CONTACT_POINTS_PROP, CassandraConnectorConstants.CONTACT_POINTS_PROP_DEFAULT)); + cassandraSessionProvider.setAdminKeyspace( + this.env.getProperty(CassandraConnectorConstants.KEYSPACE_PROP, CassandraConnectorConstants.KEYSPACE_PROP_DEFAULT)); + + cassandraSessionProvider.touchAdminSession(); + + return cassandraSessionProvider; + } + + @Bean + public TenantAwareCassandraMapperProvider cassandraMapperProvider(@Qualifier(CassandraConnectorConstants.LOGGER_NAME) final Logger logger, final CassandraSessionProvider cassandraSessionProvider) { + return new TenantAwareCassandraMapperProvider(this.env, logger, cassandraSessionProvider); + } + + @Bean + public TenantAwareEntityTemplate tenantAwareEntityTemplate(final CassandraSessionProvider cassandraSessionProvider, + final TenantAwareCassandraMapperProvider tenantAwareCassandraMapperProvider) { + return new TenantAwareEntityTemplate(cassandraSessionProvider, tenantAwareCassandraMapperProvider); + } + + @Bean + public CassandraJourneyFactory cassandraJourneyFactory(@Qualifier(CassandraConnectorConstants.LOGGER_NAME) final Logger logger) { + return new CassandraJourneyFactory(logger, this.applicationName); + } +} diff --git a/src/main/java/io/mifos/core/cassandra/config/EnableCassandra.java b/src/main/java/io/mifos/core/cassandra/config/EnableCassandra.java new file mode 100644 index 0000000..b8e5193 --- /dev/null +++ b/src/main/java/io/mifos/core/cassandra/config/EnableCassandra.java @@ -0,0 +1,35 @@ +/* + * 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.cassandra.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; + +@SuppressWarnings("unused") +@Target(ElementType.TYPE) +@Retention(RetentionPolicy.RUNTIME) +@Documented +@Inherited +@Import({CassandraConnectorConfiguration.class}) +public @interface EnableCassandra { + +} diff --git a/src/main/java/io/mifos/core/cassandra/core/CassandraJourney.java b/src/main/java/io/mifos/core/cassandra/core/CassandraJourney.java new file mode 100644 index 0000000..fdc8666 --- /dev/null +++ b/src/main/java/io/mifos/core/cassandra/core/CassandraJourney.java @@ -0,0 +1,93 @@ +/* + * 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.cassandra.core; + +import com.datastax.driver.core.DataType; +import com.datastax.driver.core.KeyspaceMetadata; +import com.datastax.driver.core.ParseUtils; +import com.datastax.driver.core.ResultSet; +import com.datastax.driver.core.Row; +import com.datastax.driver.core.Session; +import com.datastax.driver.core.TableMetadata; +import com.datastax.driver.core.querybuilder.QueryBuilder; +import com.datastax.driver.core.schemabuilder.SchemaBuilder; +import io.mifos.core.lang.ApplicationName; +import org.slf4j.Logger; + +import java.util.Objects; + +@SuppressWarnings({"WeakerAccess", "unused"}) +public class CassandraJourney { + + private final Logger logger; + private final ApplicationName applicationName; + private final Session session; + private final String schemaTableName; + + public CassandraJourney(final Logger logger, final ApplicationName applicationName, final Session session) { + super(); + this.applicationName = applicationName; + this.logger = logger; + this.session = session; + this.schemaTableName = this.applicationName.getServiceName() + "_cassandra_schema_table"; + } + + public void start(final CassandraJourneyRoute cassandraJourneyRoute) { + // check for version + final ResultSet resultSet = session.execute( + QueryBuilder + .select("hash_value") + .from(this.schemaTableName) + .where(QueryBuilder.eq("version", cassandraJourneyRoute.getVersion())) + ); + + if (!resultSet.isExhausted()) { + final Row row = resultSet.one(); + final Integer fetchedHashValue = row.get("hash_value", Integer.class); + if (!Objects.equals(fetchedHashValue, cassandraJourneyRoute.getHashValue())) { + throw new IllegalStateException("Version mismatch for " + cassandraJourneyRoute.getVersion()); + } + } else { + cassandraJourneyRoute.getCassandraJourneyWaypoints() + .forEach(waypoint -> this.session.execute(waypoint.getStatement())); + + this.session.execute( + QueryBuilder + .insertInto(this.schemaTableName) + .value("version", cassandraJourneyRoute.getVersion()) + .value("hash_value", cassandraJourneyRoute.getHashValue()) + ); + } + } + + void init() { + final KeyspaceMetadata keyspaceMetadata = + session.getCluster().getMetadata().getKeyspace(session.getLoggedKeyspace()); + final TableMetadata schemaTable = keyspaceMetadata.getTable(ParseUtils.quote(this.schemaTableName)); + if (schemaTable == null) { + try { + session.execute(SchemaBuilder + .createTable(this.schemaTableName) + .addPartitionKey("version", DataType.text()) + .addColumn("hash_value", DataType.cint()) + .buildInternal() + ); + } catch (final Throwable th) { + this.logger.warn("Schema table for {0} already exists.", this.applicationName.getServiceName()); + } + } + } +} diff --git a/src/main/java/io/mifos/core/cassandra/core/CassandraJourneyFactory.java b/src/main/java/io/mifos/core/cassandra/core/CassandraJourneyFactory.java new file mode 100644 index 0000000..e4c9eaa --- /dev/null +++ b/src/main/java/io/mifos/core/cassandra/core/CassandraJourneyFactory.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.cassandra.core; + +import io.mifos.core.lang.ApplicationName; +import org.slf4j.Logger; + +@SuppressWarnings("unused") +public class CassandraJourneyFactory { + + private final Logger logger; + private final ApplicationName applicationName; + + public CassandraJourneyFactory(final Logger logger, final ApplicationName applicationName) { + super(); + this.logger = logger; + this.applicationName = applicationName; + } + + public CassandraJourney create(final CassandraSessionProvider cassandraSessionProvider) { + final CassandraJourney cassandraJourney = new CassandraJourney( + this.logger, this.applicationName, cassandraSessionProvider.getTenantSession() + ); + + cassandraJourney.init(); + return cassandraJourney; + } +} diff --git a/src/main/java/io/mifos/core/cassandra/core/CassandraJourneyRoute.java b/src/main/java/io/mifos/core/cassandra/core/CassandraJourneyRoute.java new file mode 100644 index 0000000..3d84bf6 --- /dev/null +++ b/src/main/java/io/mifos/core/cassandra/core/CassandraJourneyRoute.java @@ -0,0 +1,73 @@ +/* + * 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.cassandra.core; + +import org.springframework.util.Assert; + +import java.util.ArrayList; + +@SuppressWarnings("WeakerAccess") +public class CassandraJourneyRoute { + + private final String version; + private final ArrayList cassandraJourneyWaypoints; + private CassandraJourneyRoute(final String version, + final ArrayList cassandraJourneyWaypoints) { + super(); + this.version = version; + this.cassandraJourneyWaypoints = cassandraJourneyWaypoints; + } + + public static Builder plan(final String version) { + return new Builder(version); + } + + public ArrayList getCassandraJourneyWaypoints() { + return this.cassandraJourneyWaypoints; + } + + public String getVersion() { + return this.version; + } + + public Integer getHashValue() { + return 31 * this.cassandraJourneyWaypoints.stream().mapToInt(CassandraJourneyWaypoint::getHashValue).sum(); + } + + public static class Builder { + + private final String version; + private ArrayList cassandraJourneyWaypoints; + + private Builder(final String version) { + super(); + this.version = version; + } + + public Builder addWaypoint(final String statement) { + if (this.cassandraJourneyWaypoints == null) { + this.cassandraJourneyWaypoints = new ArrayList<>(); + } + this.cassandraJourneyWaypoints.add(new CassandraJourneyWaypoint(statement)); + return this; + } + + public CassandraJourneyRoute build() { + Assert.notNull(this.cassandraJourneyWaypoints); + return new CassandraJourneyRoute(this.version, this.cassandraJourneyWaypoints); + } + } +} diff --git a/src/main/java/io/mifos/core/cassandra/core/CassandraJourneyWaypoint.java b/src/main/java/io/mifos/core/cassandra/core/CassandraJourneyWaypoint.java new file mode 100644 index 0000000..db87b34 --- /dev/null +++ b/src/main/java/io/mifos/core/cassandra/core/CassandraJourneyWaypoint.java @@ -0,0 +1,35 @@ +/* + * 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.cassandra.core; + +@SuppressWarnings("WeakerAccess") +public class CassandraJourneyWaypoint { + + private final String statement; + + public CassandraJourneyWaypoint(final String statement) { + super(); + this.statement = statement; + } + + public String getStatement() { + return this.statement; + } + + public Integer getHashValue() { + return this.statement.hashCode(); + } +} diff --git a/src/main/java/io/mifos/core/cassandra/core/CassandraSessionProvider.java b/src/main/java/io/mifos/core/cassandra/core/CassandraSessionProvider.java new file mode 100644 index 0000000..7ce7850 --- /dev/null +++ b/src/main/java/io/mifos/core/cassandra/core/CassandraSessionProvider.java @@ -0,0 +1,193 @@ +/* + * 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.cassandra.core; + +import com.datastax.driver.core.Cluster; +import com.datastax.driver.core.Session; +import com.datastax.driver.core.exceptions.InvalidQueryException; +import com.datastax.driver.mapping.Mapper; +import com.datastax.driver.mapping.MappingManager; +import io.mifos.core.cassandra.domain.Tenant; +import io.mifos.core.cassandra.util.CassandraConnectorConstants; +import io.mifos.core.cassandra.util.CodecRegistry; +import io.mifos.core.cassandra.util.ContactPointUtils; +import io.mifos.core.cassandra.util.LocalDateTimeCodec; +import io.mifos.core.lang.ServiceException; +import io.mifos.core.lang.TenantContextHolder; +import org.slf4j.Logger; +import org.springframework.core.env.Environment; +import org.springframework.util.Assert; + +import javax.annotation.Nonnull; +import javax.annotation.PreDestroy; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.locks.StampedLock; + +@SuppressWarnings("WeakerAccess") +public class CassandraSessionProvider { + + private final Environment env; + private final Logger logger; + private final ConcurrentHashMap clusterCache; + private final ConcurrentHashMap sessionCache; + private final StampedLock mapperLock = new StampedLock(); + private String adminClusterName; + private String adminContactPoints; + private String adminKeyspace; + private MappingManager adminSessionMappingManager; + + public CassandraSessionProvider(@Nonnull final Environment env, @Nonnull final Logger logger) { + super(); + Assert.notNull(env, "An environment must be given."); + Assert.notNull(logger, "A logger must be given."); + this.env = env; + this.logger = logger; + this.clusterCache = new ConcurrentHashMap<>(); + this.sessionCache = new ConcurrentHashMap<>(); + } + + public void setAdminClusterName(@Nonnull final String adminClusterName) { + Assert.notNull(adminClusterName, "A cluster name must be given."); + Assert.hasText(adminClusterName, "A cluster name must be given."); + this.adminClusterName = adminClusterName; + } + + public void setAdminContactPoints(@Nonnull final String adminContactPoints) { + Assert.notNull(adminContactPoints, "At least one contact point must be given."); + Assert.hasText(adminContactPoints, "At least one contact point must be given."); + this.adminContactPoints = adminContactPoints; + } + + public void setAdminKeyspace(@Nonnull final String adminKeyspace) { + Assert.notNull(adminKeyspace, "An keyspace must be given."); + Assert.hasText(adminKeyspace, "An keyspace must be given."); + this.adminKeyspace = adminKeyspace; + } + + @Nonnull + public Session getAdminSession() { + if (this.adminClusterName == null + || this.adminContactPoints == null + || this.adminKeyspace == null) { + throw new IllegalStateException("Cluster name, contact points, and keyspace must be set to retrieve an admin session."); + } + + try { + return this.getSession(this.adminClusterName, this.adminContactPoints, this.adminKeyspace); + } catch (final KeyspaceDoesntExistYet ignored) { + final Cluster cluster = this.clusterCache.get(adminClusterName); + try (final Session session = cluster.newSession()) { + session.execute("CREATE KEYSPACE " + this.adminKeyspace + " WITH REPLICATION = " + + ReplicationStrategyResolver.replicationStrategy( + env.getProperty(CassandraConnectorConstants.DEFAULT_REPLICATION_TYPE, + CassandraConnectorConstants.DEFAULT_REPLICATION_TYPE_DEFAULT), + env.getProperty(CassandraConnectorConstants.DEFAULT_REPLICATION_REPLICAS, + CassandraConnectorConstants.DEFAULT_REPLICATION_REPLICAS_DEFAULT))); + + return this.getSession(this.adminClusterName, this.adminContactPoints, this.adminKeyspace); + } + } + } + + @Nonnull + public Session getTenantSession() { + return TenantContextHolder.identifier() + .map(this::getTenantSession) + .orElseThrow(() -> + new IllegalArgumentException("Could not find tenant identifier, make sure you set an identifier using TenantContextHolder.")); + } + + @Nonnull + public Session getTenantSession(@Nonnull final String identifier) { + Assert.notNull(identifier, "A tenant identifier must be given."); + Assert.hasText(identifier, "A tenant identifier must be given."); + + final Mapper tenantInfoMapper = this.getAdminSessionMappingManager().mapper(Tenant.class); + tenantInfoMapper.setDefaultDeleteOptions(OptionProvider.deleteConsistencyLevel(this.env)); + tenantInfoMapper.setDefaultGetOptions(OptionProvider.readConsistencyLevel(this.env)); + tenantInfoMapper.setDefaultSaveOptions(OptionProvider.writeConsistencyLevel(this.env)); + final Tenant tenantInfo = tenantInfoMapper.get(identifier); + if (tenantInfo == null) throw ServiceException.notFound("Tenant [" + identifier + "] unknown."); + return this.getSession(tenantInfo.getClusterName(), tenantInfo.getContactPoints(), tenantInfo.getKeyspace()); + } + + @Nonnull + public Session getSession(@Nonnull final String clusterName, + @Nonnull final String contactPoints, + @Nonnull final String keyspace) { + Assert.notNull(clusterName, "A cluster name must be given."); + Assert.hasText(clusterName, "A cluster name must be given."); + Assert.notNull(contactPoints, "At least one contact point must be given."); + Assert.hasText(contactPoints, "At least one contact point must be given."); + Assert.notNull(keyspace, "A keyspace must be given."); + Assert.hasText(keyspace, "A keyspace must be given."); + + this.sessionCache.computeIfAbsent(keyspace, (sessionKey) -> { + this.logger.info("Create new session for keyspace [" + keyspace + "]."); + + final Cluster cluster = this.clusterCache.computeIfAbsent(clusterName, + (clusterKey) -> getCluster(clusterKey, contactPoints)); + try { + CodecRegistry.apply(cluster); + return cluster.connect(keyspace); + } catch (final InvalidQueryException ex) { + throw new KeyspaceDoesntExistYet("Could not connect keyspace!", ex); + } + }); + + return this.sessionCache.get(keyspace); + } + + private Cluster getCluster(@Nonnull final String clusterName, @Nonnull final String contactPoints) { + CodecRegistry.register(new LocalDateTimeCodec()); + + final Cluster.Builder clusterBuilder = Cluster.builder() + .withClusterName(clusterName); + ContactPointUtils.process(clusterBuilder, contactPoints); + return clusterBuilder.build(); + } + + @Nonnull + public MappingManager getAdminSessionMappingManager() { + if (this.adminSessionMappingManager == null) { + final long lockStamp = this.mapperLock.writeLock(); + try { + if (this.adminSessionMappingManager == null) { + this.adminSessionMappingManager = new MappingManager(this.getAdminSession()); + } + } finally { + this.mapperLock.unlockWrite(lockStamp); + } + } + + return this.adminSessionMappingManager; + } + + public void touchAdminSession() { + this.getAdminSession(); + } + + @PreDestroy + private void cleanUp() { + this.logger.info("Clean up cluster connections."); + + this.sessionCache.values().forEach(Session::close); + this.sessionCache.clear(); + + this.clusterCache.values().forEach(Cluster::close); + this.clusterCache.clear(); + } +} diff --git a/src/main/java/io/mifos/core/cassandra/core/KeyspaceDoesntExistYet.java b/src/main/java/io/mifos/core/cassandra/core/KeyspaceDoesntExistYet.java new file mode 100644 index 0000000..ac49004 --- /dev/null +++ b/src/main/java/io/mifos/core/cassandra/core/KeyspaceDoesntExistYet.java @@ -0,0 +1,27 @@ +/* + * 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.cassandra.core; + +import com.datastax.driver.core.exceptions.InvalidQueryException; + +/** + * @author Myrle Krantz + */ +class KeyspaceDoesntExistYet extends IllegalArgumentException { + KeyspaceDoesntExistYet(String s, InvalidQueryException ex) { + super(s, ex); + } +} diff --git a/src/main/java/io/mifos/core/cassandra/core/OptionProvider.java b/src/main/java/io/mifos/core/cassandra/core/OptionProvider.java new file mode 100644 index 0000000..eac9f7d --- /dev/null +++ b/src/main/java/io/mifos/core/cassandra/core/OptionProvider.java @@ -0,0 +1,82 @@ +/* + * 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.cassandra.core; + +import com.datastax.driver.core.ConsistencyLevel; +import com.datastax.driver.mapping.Mapper; +import io.mifos.core.cassandra.util.CassandraConnectorConstants; +import org.springframework.core.env.Environment; +import org.springframework.util.Assert; + +import javax.annotation.Nonnull; +import java.util.HashMap; + +@SuppressWarnings("WeakerAccess") +public final class OptionProvider { + + private static final HashMap CACHED_OPTIONS = new HashMap<>(); + + private OptionProvider() { + super(); + } + + @Nonnull + public static Mapper.Option deleteConsistencyLevel(@Nonnull final Environment env) { + Assert.notNull(env, "An environment must be given!"); + if (OptionProvider.CACHED_OPTIONS.isEmpty()) { + OptionProvider.lazyOptionInit(env); + } + return OptionProvider.CACHED_OPTIONS.get(CassandraConnectorConstants.CONSISTENCY_LEVEL_DELETE_PROP); + } + + @Nonnull + public static Mapper.Option readConsistencyLevel(@Nonnull final Environment env) { + Assert.notNull(env, "An environment must be given!"); + if (OptionProvider.CACHED_OPTIONS.isEmpty()) { + OptionProvider.lazyOptionInit(env); + } + return OptionProvider.CACHED_OPTIONS.get(CassandraConnectorConstants.CONSISTENCY_LEVEL_READ_PROP); + } + + @Nonnull + public static Mapper.Option writeConsistencyLevel(@Nonnull final Environment env) { + Assert.notNull(env, "An environment must be given!"); + if (OptionProvider.CACHED_OPTIONS.isEmpty()) { + OptionProvider.lazyOptionInit(env); + } + return OptionProvider.CACHED_OPTIONS.get(CassandraConnectorConstants.CONSISTENCY_LEVEL_WRITE_PROP); + } + + private static void lazyOptionInit(final Environment env) { + OptionProvider.CACHED_OPTIONS.put(CassandraConnectorConstants.CONSISTENCY_LEVEL_DELETE_PROP, + Mapper.Option.consistencyLevel( + ConsistencyLevel.valueOf( + env.getProperty(CassandraConnectorConstants.CONSISTENCY_LEVEL_DELETE_PROP, + CassandraConnectorConstants.CONSISTENCY_LEVEL_PROP_DEFAULT)))); + + OptionProvider.CACHED_OPTIONS.put(CassandraConnectorConstants.CONSISTENCY_LEVEL_READ_PROP, + Mapper.Option.consistencyLevel( + ConsistencyLevel.valueOf( + env.getProperty(CassandraConnectorConstants.CONSISTENCY_LEVEL_READ_PROP, + CassandraConnectorConstants.CONSISTENCY_LEVEL_PROP_DEFAULT)))); + + OptionProvider.CACHED_OPTIONS.put(CassandraConnectorConstants.CONSISTENCY_LEVEL_WRITE_PROP, + Mapper.Option.consistencyLevel( + ConsistencyLevel.valueOf( + env.getProperty(CassandraConnectorConstants.CONSISTENCY_LEVEL_WRITE_PROP, + CassandraConnectorConstants.CONSISTENCY_LEVEL_PROP_DEFAULT)))); + } +} diff --git a/src/main/java/io/mifos/core/cassandra/core/ReplicationStrategyResolver.java b/src/main/java/io/mifos/core/cassandra/core/ReplicationStrategyResolver.java new file mode 100644 index 0000000..2464558 --- /dev/null +++ b/src/main/java/io/mifos/core/cassandra/core/ReplicationStrategyResolver.java @@ -0,0 +1,52 @@ +/* + * 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.cassandra.core; + +@SuppressWarnings("WeakerAccess") +public class ReplicationStrategyResolver { + + private ReplicationStrategyResolver() { + super(); + } + + public static String replicationStrategy(final String type, final String replicas) { + final StringBuilder builder = new StringBuilder(); + if (type.equalsIgnoreCase("Simple")) { + builder.append("{'class': 'SimpleStrategy', "); + builder.append("'replication_factor': "); + builder.append(replicas); + builder.append("}"); + return builder.toString(); + } else if (type.equalsIgnoreCase("Network")) { + builder.append("{'class': 'NetworkTopologyStrategy', "); + + final String[] splitReplicas = replicas.split(","); + for (int i = 0; i < splitReplicas.length; i++) { + final String[] replicaDataCenter = splitReplicas[i].split(":"); + builder.append("'").append(replicaDataCenter[0].trim()).append("': "); + builder.append(replicaDataCenter[1].trim()); + if ((i + 1) < splitReplicas.length) { + builder.append(", "); + } + } + + builder.append("}"); + return builder.toString(); + } else { + throw new IllegalArgumentException("Unknown replication strategy: " + type); + } + } +} diff --git a/src/main/java/io/mifos/core/cassandra/core/TenantAwareCassandraMapperProvider.java b/src/main/java/io/mifos/core/cassandra/core/TenantAwareCassandraMapperProvider.java new file mode 100644 index 0000000..c82b299 --- /dev/null +++ b/src/main/java/io/mifos/core/cassandra/core/TenantAwareCassandraMapperProvider.java @@ -0,0 +1,83 @@ +/* + * 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.cassandra.core; + +import com.datastax.driver.core.Session; +import com.datastax.driver.mapping.Mapper; +import com.datastax.driver.mapping.MappingManager; +import io.mifos.core.lang.TenantContextHolder; +import org.slf4j.Logger; +import org.springframework.core.env.Environment; +import org.springframework.util.Assert; + +import javax.annotation.Nonnull; +import java.util.concurrent.ConcurrentHashMap; + +public class TenantAwareCassandraMapperProvider { + + private final Environment env; + private final Logger logger; + private final CassandraSessionProvider cassandraSessionProvider; + private final ConcurrentHashMap managerCache; + + public TenantAwareCassandraMapperProvider(@Nonnull final Environment env, @Nonnull final Logger logger, + @Nonnull final CassandraSessionProvider cassandraSessionProvider) { + super(); + Assert.notNull(env, "An environment must be given."); + Assert.notNull(logger, "A logger must be given."); + Assert.notNull(cassandraSessionProvider, "A Cassandra session provider must be given."); + this.env = env; + this.logger = logger; + this.cassandraSessionProvider = cassandraSessionProvider; + this.managerCache = new ConcurrentHashMap<>(); + } + + @SuppressWarnings("WeakerAccess") + @Nonnull + public Mapper getMapper(@Nonnull final Class type) { + Assert.notNull(type, "A type must be given."); + if (TenantContextHolder.identifier().isPresent()) { + final String identifier = TenantContextHolder.checkedGetIdentifier(); + return this.getMapper(identifier, type); + } else { + throw new IllegalArgumentException("Could not find tenant identifier, make sure you set an identifier using TenantContextHolder."); + } + } + + @SuppressWarnings("WeakerAccess") + @Nonnull + public Mapper getMapper(@Nonnull final String identifier, @Nonnull final Class type) { + Assert.notNull(identifier, "A tenant identifier must be given."); + Assert.hasText(identifier, "A tenant identifier must be given."); + Assert.notNull(type, "A type must be given."); + + this.managerCache.computeIfAbsent(identifier, (key) -> { + this.logger.info("Create new mapping mapper for tenant [" + identifier + "] and type [" + type.getSimpleName() + "]."); + final Session session = this.cassandraSessionProvider.getTenantSession(identifier); + + final MappingManager mappingManager = new MappingManager(session); + + final Mapper typedMapper = mappingManager.mapper(type); + typedMapper.setDefaultDeleteOptions(OptionProvider.deleteConsistencyLevel(this.env)); + typedMapper.setDefaultGetOptions(OptionProvider.readConsistencyLevel(this.env)); + typedMapper.setDefaultSaveOptions(OptionProvider.writeConsistencyLevel(this.env)); + + return mappingManager; + }); + + return this.managerCache.get(identifier).mapper(type); + } +} diff --git a/src/main/java/io/mifos/core/cassandra/core/TenantAwareEntityTemplate.java b/src/main/java/io/mifos/core/cassandra/core/TenantAwareEntityTemplate.java new file mode 100644 index 0000000..065b0eb --- /dev/null +++ b/src/main/java/io/mifos/core/cassandra/core/TenantAwareEntityTemplate.java @@ -0,0 +1,64 @@ +/* + * 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.cassandra.core; + +import com.datastax.driver.core.ResultSet; +import com.datastax.driver.core.Statement; +import com.datastax.driver.mapping.Mapper; + +import javax.annotation.Nonnull; +import java.util.List; +import java.util.Optional; + +public class TenantAwareEntityTemplate { + + private final CassandraSessionProvider cassandraSessionProvider; + private final TenantAwareCassandraMapperProvider tenantAwareCassandraMapperProvider; + + public TenantAwareEntityTemplate(final CassandraSessionProvider cassandraSessionProvider, + final TenantAwareCassandraMapperProvider tenantAwareCassandraMapperProvider) { + super(); + this.cassandraSessionProvider = cassandraSessionProvider; + this.tenantAwareCassandraMapperProvider = tenantAwareCassandraMapperProvider; + } + + @SuppressWarnings("unchecked") + public void save(final T entity) { + final Mapper mapper = this.tenantAwareCassandraMapperProvider.getMapper((Class) entity.getClass()); + mapper.save(entity); + } + + @Nonnull + public Optional findById(final Class type, final Object... identifier) { + final Mapper mapper = this.tenantAwareCassandraMapperProvider.getMapper(type); + return Optional.ofNullable(mapper.get(identifier)); + } + + + @Nonnull + public List fetchByKeys(final Class type, final Object... keys) { + final Mapper mapper = this.tenantAwareCassandraMapperProvider.getMapper(type); + final Statement query = mapper.getQuery(keys); + final ResultSet resultSet = this.cassandraSessionProvider.getTenantSession().execute(query); + return mapper.map(resultSet).all(); + } + + @SuppressWarnings("unchecked") + public void delete(final T entity) { + final Mapper mapper = this.tenantAwareCassandraMapperProvider.getMapper((Class) entity.getClass()); + mapper.delete(entity); + } +} diff --git a/src/main/java/io/mifos/core/cassandra/domain/Tenant.java b/src/main/java/io/mifos/core/cassandra/domain/Tenant.java new file mode 100644 index 0000000..c015d25 --- /dev/null +++ b/src/main/java/io/mifos/core/cassandra/domain/Tenant.java @@ -0,0 +1,87 @@ +/* + * 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.cassandra.domain; + +import com.datastax.driver.mapping.annotations.Column; +import com.datastax.driver.mapping.annotations.PartitionKey; +import com.datastax.driver.mapping.annotations.Table; + +@Table(keyspace = "seshat", name = "tenants") +public final class Tenant { + + @PartitionKey + private String identifier; + + @Column(name = "cluster_name") + private String clusterName; + + @Column(name = "contact_points") + private String contactPoints; + + @Column(name = "keyspace_name") + private String keyspace; + + public Tenant() { + super(); + } + + public String getIdentifier() { + return identifier; + } + + public void setIdentifier(String identifier) { + this.identifier = identifier; + } + + public String getClusterName() { + return clusterName; + } + + public void setClusterName(String clusterName) { + this.clusterName = clusterName; + } + + public String getContactPoints() { + return contactPoints; + } + + public void setContactPoints(String contactPoints) { + this.contactPoints = contactPoints; + } + + public String getKeyspace() { + return keyspace; + } + + public void setKeyspace(String keyspace) { + this.keyspace = keyspace; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + Tenant that = (Tenant) o; + + return identifier.equals(that.identifier); + } + + @Override + public int hashCode() { + return identifier.hashCode(); + } +} diff --git a/src/main/java/io/mifos/core/cassandra/util/CassandraConnectorConstants.java b/src/main/java/io/mifos/core/cassandra/util/CassandraConnectorConstants.java new file mode 100644 index 0000000..2e6cc6d --- /dev/null +++ b/src/main/java/io/mifos/core/cassandra/util/CassandraConnectorConstants.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.cassandra.util; + +public interface CassandraConnectorConstants { + + String LOGGER_NAME = "cassandra-logger"; + + String CLUSTER_NAME_PROP = "cassandra.clusterName"; + String CLUSTER_NAME_PROP_DEFAULT = "staging_cluster"; + + String CONTACT_POINTS_PROP = "cassandra.contactPoints"; + String CONTACT_POINTS_PROP_DEFAULT = "127.0.0.1:9042,127.0.0.2:9042,127.0.0.3:9042"; + + String KEYSPACE_PROP = "cassandra.keyspace"; + String KEYSPACE_PROP_DEFAULT = "seshat"; + + String CONSISTENCY_LEVEL_READ_PROP = "cassandra.cl.read"; + String CONSISTENCY_LEVEL_WRITE_PROP = "cassandra.cl.write"; + String CONSISTENCY_LEVEL_DELETE_PROP = "cassandra.cl.delete"; + String CONSISTENCY_LEVEL_PROP_DEFAULT = "LOCAL_QUORUM"; + + String DEFAULT_REPLICATION_TYPE = "cassandra.default.replication.type"; + String DEFAULT_REPLICATION_REPLICAS = "cassandra.default.replication.replicas"; + + String DEFAULT_REPLICATION_TYPE_DEFAULT = "Simple"; + String DEFAULT_REPLICATION_REPLICAS_DEFAULT = "1"; +} diff --git a/src/main/java/io/mifos/core/cassandra/util/CodecRegistry.java b/src/main/java/io/mifos/core/cassandra/util/CodecRegistry.java new file mode 100644 index 0000000..3111529 --- /dev/null +++ b/src/main/java/io/mifos/core/cassandra/util/CodecRegistry.java @@ -0,0 +1,48 @@ +/* + * 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.cassandra.util; + +import com.datastax.driver.core.Cluster; +import com.datastax.driver.core.TypeCodec; +import org.springframework.util.Assert; + +import javax.annotation.Nonnull; +import java.util.ArrayList; +import java.util.Arrays; + +public final class CodecRegistry { + + private static final ArrayList> REGISTERED_CODECS = new ArrayList<>(); + + private CodecRegistry() { + super(); + } + + @SuppressWarnings({ + "unchecked" + }) + public static void register(@Nonnull final TypeCodec... typeCodec) { + Assert.notNull(typeCodec, "A type codec must be given."); + Assert.notEmpty(typeCodec, "At least one type code must be given."); + CodecRegistry.REGISTERED_CODECS.addAll(Arrays.asList(typeCodec)); + } + + public static void apply(@Nonnull final Cluster cluster) { + Assert.notNull(cluster, "A cluster must be given."); + cluster.getConfiguration().getCodecRegistry().register(CodecRegistry.REGISTERED_CODECS); + CodecRegistry.REGISTERED_CODECS.clear(); + } +} diff --git a/src/main/java/io/mifos/core/cassandra/util/ContactPointUtils.java b/src/main/java/io/mifos/core/cassandra/util/ContactPointUtils.java new file mode 100644 index 0000000..5d09d29 --- /dev/null +++ b/src/main/java/io/mifos/core/cassandra/util/ContactPointUtils.java @@ -0,0 +1,46 @@ +/* + * 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.cassandra.util; + +import com.datastax.driver.core.Cluster; + +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.UnknownHostException; + +public class ContactPointUtils { + + private ContactPointUtils() { + super(); + } + + public static void process(final Cluster.Builder clusterBuilder, final String contactPoints) { + final String[] splitContactPoints = contactPoints.split(","); + for (final String contactPoint : splitContactPoints) { + if (contactPoint.contains(":")) { + final String[] address = contactPoint.split(":"); + clusterBuilder.addContactPointsWithPorts( + new InetSocketAddress(address[0].trim(), Integer.valueOf(address[1].trim()))); + } else { + try { + clusterBuilder.addContactPoints(InetAddress.getByName(contactPoint.trim())); + } catch (final UnknownHostException uhex) { + throw new IllegalArgumentException("Host not found!", uhex); + } + } + } + } +} diff --git a/src/main/java/io/mifos/core/cassandra/util/LocalDateTimeCodec.java b/src/main/java/io/mifos/core/cassandra/util/LocalDateTimeCodec.java new file mode 100644 index 0000000..2c75241 --- /dev/null +++ b/src/main/java/io/mifos/core/cassandra/util/LocalDateTimeCodec.java @@ -0,0 +1,66 @@ +/* + * 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.cassandra.util; + +import com.datastax.driver.core.DataType; +import com.datastax.driver.core.ParseUtils; +import com.datastax.driver.core.ProtocolVersion; +import com.datastax.driver.core.TypeCodec; +import com.datastax.driver.core.exceptions.InvalidTypeException; +import io.mifos.core.lang.DateConverter; + +import java.nio.ByteBuffer; +import java.time.LocalDateTime; + +public class LocalDateTimeCodec extends TypeCodec { + + public LocalDateTimeCodec() { + super(DataType.timestamp(), LocalDateTime.class); + } + + @Override + public ByteBuffer serialize(final LocalDateTime value, final ProtocolVersion protocolVersion) throws InvalidTypeException { + final Long epochMillis = DateConverter.toEpochMillis(value); + return TypeCodec.bigint().serializeNoBoxing(epochMillis, protocolVersion); + } + + @Override + public LocalDateTime deserialize(final ByteBuffer bytes, final ProtocolVersion protocolVersion) throws InvalidTypeException { + final Long epochMillis = TypeCodec.bigint().deserializeNoBoxing(bytes, protocolVersion); + return DateConverter.fromEpochMillis(epochMillis); + } + + @Override + public LocalDateTime parse(final String value) throws InvalidTypeException { + final String toParse; + if (ParseUtils.isQuoted(value)) { + toParse = ParseUtils.unquote(value); + } else { + toParse = value; + } + + if (ParseUtils.isLongLiteral(toParse)) { + return DateConverter.fromEpochMillis(Long.parseLong(toParse)); + } else { + return DateConverter.fromIsoString(toParse); + } + } + + @Override + public String format(final LocalDateTime value) throws InvalidTypeException { + return ParseUtils.quote(DateConverter.toIsoString(value)); + } +} diff --git a/src/test/java/io/mifos/core/cassandra/core/OptionProviderTest.java b/src/test/java/io/mifos/core/cassandra/core/OptionProviderTest.java new file mode 100644 index 0000000..90984c0 --- /dev/null +++ b/src/test/java/io/mifos/core/cassandra/core/OptionProviderTest.java @@ -0,0 +1,66 @@ +/* + * 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.cassandra.core; + +import io.mifos.core.cassandra.util.CassandraConnectorConstants; +import org.junit.Assert; +import org.junit.Test; +import org.mockito.Mockito; +import org.springframework.core.env.Environment; + +public class OptionProviderTest { + + public OptionProviderTest() { + super(); + } + + @Test + public void shouldFillOptions() { + final Environment environment = Mockito.mock(Environment.class); + Mockito. + when( + environment.getProperty(CassandraConnectorConstants.CONSISTENCY_LEVEL_DELETE_PROP, + CassandraConnectorConstants.CONSISTENCY_LEVEL_PROP_DEFAULT)) + .thenReturn(CassandraConnectorConstants.CONSISTENCY_LEVEL_PROP_DEFAULT); + + Mockito. + when( + environment.getProperty(CassandraConnectorConstants.CONSISTENCY_LEVEL_READ_PROP, + CassandraConnectorConstants.CONSISTENCY_LEVEL_PROP_DEFAULT)) + .thenReturn(CassandraConnectorConstants.CONSISTENCY_LEVEL_PROP_DEFAULT); + + Mockito. + when( + environment.getProperty(CassandraConnectorConstants.CONSISTENCY_LEVEL_WRITE_PROP, + CassandraConnectorConstants.CONSISTENCY_LEVEL_PROP_DEFAULT)) + .thenReturn(CassandraConnectorConstants.CONSISTENCY_LEVEL_PROP_DEFAULT); + + Assert.assertNotNull(OptionProvider.readConsistencyLevel(environment)); + Assert.assertNotNull(OptionProvider.writeConsistencyLevel(environment)); + Assert.assertNotNull(OptionProvider.deleteConsistencyLevel(environment)); + Assert.assertNotNull(OptionProvider.readConsistencyLevel(environment)); + Assert.assertNotNull(OptionProvider.writeConsistencyLevel(environment)); + Assert.assertNotNull(OptionProvider.deleteConsistencyLevel(environment)); + + Mockito.verify(environment, Mockito.times(3)).getProperty(Mockito.anyString(), Mockito.anyString()); + } + + @Test(expected = IllegalArgumentException.class) + public void shouldFailFillOptionsEnvironmentNull() { + //noinspection ConstantConditions + OptionProvider.readConsistencyLevel(null); + } +} diff --git a/src/test/java/io/mifos/core/cassandra/core/ReplicationStrategyResolverTest.java b/src/test/java/io/mifos/core/cassandra/core/ReplicationStrategyResolverTest.java new file mode 100644 index 0000000..086a562 --- /dev/null +++ b/src/test/java/io/mifos/core/cassandra/core/ReplicationStrategyResolverTest.java @@ -0,0 +1,47 @@ +/* + * 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.cassandra.core; + +import org.junit.Assert; +import org.junit.Test; + +public class ReplicationStrategyResolverTest { + + private static final String SIMPLE_STRATEGY = "{'class': 'SimpleStrategy', 'replication_factor': 3}"; + private static final String NETWORK_STRATEGY = "{'class': 'NetworkTopologyStrategy', 'DC1': 2, 'DC2': 2}"; + + public ReplicationStrategyResolverTest() { + super(); + } + + @Test + public void shouldCreateSimpleStrategy() { + final String simpleStrategy = ReplicationStrategyResolver.replicationStrategy("Simple", "3"); + Assert.assertEquals(SIMPLE_STRATEGY, simpleStrategy); + } + + @Test + public void shouldCreateNetworkTopologyStrategy() { + final String networkStrategy = ReplicationStrategyResolver.replicationStrategy("Network", "DC1:2,DC2:2"); + Assert.assertEquals(NETWORK_STRATEGY, networkStrategy); + } + + @Test(expected = IllegalArgumentException.class) + public void shouldFailUnknownStrategy() { + ReplicationStrategyResolver.replicationStrategy("unknown", "1"); + Assert.fail(); + } +} \ No newline at end of file diff --git a/src/test/java/io/mifos/core/cassandra/util/ContactPointUtilsTest.java b/src/test/java/io/mifos/core/cassandra/util/ContactPointUtilsTest.java new file mode 100644 index 0000000..8249f6b --- /dev/null +++ b/src/test/java/io/mifos/core/cassandra/util/ContactPointUtilsTest.java @@ -0,0 +1,66 @@ +/* + * 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.cassandra.util; + +import com.datastax.driver.core.Cluster; +import org.junit.Assert; +import org.junit.Test; + +import java.net.InetSocketAddress; +import java.util.List; + +public class ContactPointUtilsTest { + + public ContactPointUtilsTest() { + super(); + } + + @Test + public void shouldAddSimpleContactPoints() { + final String contactPoints = "127.0.0.1,127.0.0.2,127.0.0.3"; + + final Cluster.Builder clusterBuilder = Cluster.builder(); + ContactPointUtils.process(clusterBuilder, contactPoints); + final List addedClusterPoints = clusterBuilder.getContactPoints(); + Assert.assertTrue(addedClusterPoints.size() == 3); + for (final InetSocketAddress address : addedClusterPoints) { + Assert.assertTrue(contactPoints.contains(address.getAddress().getHostAddress())); + } + } + + @Test + public void shouldAddComplexContactPoints() { + final String contactPoints = "127.0.0.1:1234,127.0.0.2:2345,127.0.0.3:3456"; + + final Cluster.Builder clusterBuilder = Cluster.builder(); + ContactPointUtils.process(clusterBuilder, contactPoints); + final List addedClusterPoints = clusterBuilder.getContactPoints(); + + Assert.assertTrue(addedClusterPoints.size() == 3); + + final InetSocketAddress firstAddress = addedClusterPoints.get(0); + Assert.assertEquals("127.0.0.1", firstAddress.getAddress().getHostAddress()); + Assert.assertEquals(1234, firstAddress.getPort()); + + final InetSocketAddress secondAddress = addedClusterPoints.get(1); + Assert.assertEquals("127.0.0.2", secondAddress.getAddress().getHostAddress()); + Assert.assertEquals(2345, secondAddress.getPort()); + + final InetSocketAddress thirdAddress = addedClusterPoints.get(2); + Assert.assertEquals("127.0.0.3", thirdAddress.getAddress().getHostAddress()); + Assert.assertEquals(3456, thirdAddress.getPort()); + } +} -- To stop receiving notification emails like this one, please contact myrle@apache.org.