diff --git a/.github/workflows/android.yml b/.github/workflows/android.yml index c28c665..a39094a 100644 --- a/.github/workflows/android.yml +++ b/.github/workflows/android.yml @@ -19,6 +19,15 @@ jobs: java-version: '17' distribution: 'adopt' + - name: Building Java-Kotlin-Maven Interop Sample + working-directory: ./JavaKotlinMavenInterop + run: | + chmod +x gradlew + ./gradlew :kotlin-lib:publishToMavenLocal + ./gradlew :java-app-gradle:run + cd java-app-maven + mvn compile exec:java + - name: JVM Console working-directory: ./JVMConsole run: | @@ -54,3 +63,4 @@ jobs: run: | chmod +x gradlew ./gradlew assemble + diff --git a/.gitignore b/.gitignore index d6232d4..4a1c7ff 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,3 @@ - # Created by https://www.gitignore.io/api/c,git,c++,java,cmake,xcode,kotlin,android,intellij,visualstudiocode # Edit at https://www.gitignore.io/?templates=c,git,c++,java,cmake,xcode,kotlin,android,intellij,visualstudiocode @@ -257,7 +256,6 @@ fabric.properties .mtj.tmp/ # Package Files # -*.jar *.war *.nar *.ear @@ -327,3 +325,6 @@ DerivedData/ **/xcshareddata/WorkspaceSettings.xcsettings # End of https://www.gitignore.io/api/c,git,c++,java,cmake,xcode,kotlin,android,intellij,visualstudiocode + +# Custom +JavaKotlinMavenInterop/java-app-maven/target diff --git a/JavaKotlinMavenInterop/README.md b/JavaKotlinMavenInterop/README.md new file mode 100644 index 0000000..852cf9f --- /dev/null +++ b/JavaKotlinMavenInterop/README.md @@ -0,0 +1,97 @@ +# Java-Kotlin-Maven Interop Sample + +This sample shows how a Java project using either Gradle or Maven can use Realm Kotlin. + +This can be a problem for multiple reasons: + +- The main app is written in Java and do not want to introduce Kotlin code directly into + that codebase. + +- The main app is using Maven as a build system, which is incompatible with Kotlin + Multiplatform as it only supports Gradle. + +In order to work around this we introduce a seperate Gradle Module containing the Realm code, +and then that module will expose an interface that is consumable from Java. This module will +then be publish to either MavenLocal or some other Nexus as this will allow the Java app to +find it regardless of it using Gradle or Maven. + +In this sample project we call the abstraction `RealmRepository` which expose a CRUD like +interface, but it should be modified to fit the context of the project. + + +## Requirements + +- JDK 11 +- The project can be opened in IntelliJ, which will support both Gradle and Maven in the same project, making it possible + to edit all modules from there. + +## How to Run + +1. Deploy the Kotlin library to Maven Local using: + + ``` + >./gradlew :kotlin-lib:publishToMavenLocal + + ``` + +2. Run the Java App using Gradle: + + ``` + >./gradlew :java-app-gradle:run + + ``` + +3. Run the Java App using Maven: + + ``` + > cd java-app-maven + > mvn compile exec:java + + ``` + + +## Publish The Kotlin library + +The Kotlin library contains a skeleton setup for deploying both to MavenLocal as well as a custom Nexus. You deply to +each by using: + +```shell +# Publish to Maven Local +> ./gradlew :kotlin-lib:publishToMavenLocal + +# Publish to a custom nexus +> ./gradlew :kotlin-lib:publishAllPublicationsToCustomNexusRepository +``` + +Note, you need to setup credentials and URLs for the custom nexus inside the the [build.gradle.kts](kotlin-lib/build.gradkle.kts) file. +The artifacts are not signed, and this will need to be added if required by the Nexus. + + +## Consume from Maven + +Once deployed, the Kotlin library can be consumed like any other Maven artifact: + +```xml + + + + + com.mongodb.devicesync + kotlin-lib + 1.0-SNAPSHOT + + + + +``` + +or Gradle: + +```gradle +dependencies { + implementation("com.mongodb.devicesync:kotlin-lib:1.0-SNAPSHOT") +} +``` + + + diff --git a/JavaKotlinMavenInterop/Screenshots/java-kotlin-maven-interop.png b/JavaKotlinMavenInterop/Screenshots/java-kotlin-maven-interop.png new file mode 100644 index 0000000..6e71039 Binary files /dev/null and b/JavaKotlinMavenInterop/Screenshots/java-kotlin-maven-interop.png differ diff --git a/JavaKotlinMavenInterop/build.gradle.kts b/JavaKotlinMavenInterop/build.gradle.kts new file mode 100644 index 0000000..4789347 --- /dev/null +++ b/JavaKotlinMavenInterop/build.gradle.kts @@ -0,0 +1,5 @@ +plugins { + kotlin("jvm") version "1.9.21" apply false + id("io.realm.kotlin") version "1.13.0" apply false +} +rootProject.extra["realmVersion"] = "1.13.0" diff --git a/JavaKotlinMavenInterop/gradle/wrapper/gradle-wrapper.jar b/JavaKotlinMavenInterop/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..249e583 Binary files /dev/null and b/JavaKotlinMavenInterop/gradle/wrapper/gradle-wrapper.jar differ diff --git a/JavaKotlinMavenInterop/gradle/wrapper/gradle-wrapper.properties b/JavaKotlinMavenInterop/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..d0d403e --- /dev/null +++ b/JavaKotlinMavenInterop/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-all.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/JavaKotlinMavenInterop/gradlew b/JavaKotlinMavenInterop/gradlew new file mode 100755 index 0000000..a69d9cb --- /dev/null +++ b/JavaKotlinMavenInterop/gradlew @@ -0,0 +1,240 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# 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 +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +APP_NAME="Gradle" +APP_BASE_NAME=${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='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# 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 ;; #( + MSYS* | 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" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/JavaKotlinMavenInterop/gradlew.bat b/JavaKotlinMavenInterop/gradlew.bat new file mode 100644 index 0000000..53a6b23 --- /dev/null +++ b/JavaKotlinMavenInterop/gradlew.bat @@ -0,0 +1,91 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@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 Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@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="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +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 execute + +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 + +: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 %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 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! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/JavaKotlinMavenInterop/java-app-gradle/build.gradle.kts b/JavaKotlinMavenInterop/java-app-gradle/build.gradle.kts new file mode 100644 index 0000000..aabce9e --- /dev/null +++ b/JavaKotlinMavenInterop/java-app-gradle/build.gradle.kts @@ -0,0 +1,25 @@ +plugins { + java + application +} + +group = "com.mongodb.devicesync" +version = "1.0.0-SNAPSHOT" + +repositories { + mavenCentral() +} + +dependencies { + implementation(project(":kotlin-lib")) +} + +application { + mainClass.set("com.mongodb.devicesync.javainterop.gradle.JavaGradleApp") +} + +java { + toolchain { + languageVersion.set(JavaLanguageVersion.of(11)) + } +} \ No newline at end of file diff --git a/JavaKotlinMavenInterop/java-app-gradle/src/main/java/com/mongodb/devicesync/javainterop/gradle/JavaGradleApp.java b/JavaKotlinMavenInterop/java-app-gradle/src/main/java/com/mongodb/devicesync/javainterop/gradle/JavaGradleApp.java new file mode 100644 index 0000000..c6ce84f --- /dev/null +++ b/JavaKotlinMavenInterop/java-app-gradle/src/main/java/com/mongodb/devicesync/javainterop/gradle/JavaGradleApp.java @@ -0,0 +1,85 @@ +package com.mongodb.devicesync.javainterop.gradle; + +import com.mongodb.devicesync.kotlin.CancellationToken; +import com.mongodb.devicesync.kotlin.Person; +import com.mongodb.devicesync.kotlin.RealmRepository; +import io.realm.kotlin.MutableRealm; +import io.realm.kotlin.notifications.InitialResults; +import io.realm.kotlin.notifications.ResultsChange; +import io.realm.kotlin.notifications.UpdatedResults; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CountDownLatch; + +/** + * Java app demonstrating how you can work with Realm Kotlin. + * + * Since Realm Kotlin is required to be written in Kotlin and use + * Kotlin specific features like coroutines, we have hidden the + * implementation behind a Java friendly interface, which the + * Java app can then interact with. + */ +public class JavaGradleApp { + public static void main(String[] args) throws InterruptedException { + RealmRepository repository = new RealmRepository(); + + println("Opening Realm"); + repository.openRealm(); + + println("Write data"); + List persons = new ArrayList<>(); + for (int i = 0; i < 5; i++) { + Person umanagedPerson = new Person(); + umanagedPerson.setName("Person-" + i); + umanagedPerson.setAge(i); + persons.add(umanagedPerson); + } + repository.writeData(persons); + + println("Query data"); + List result = repository.readData("age <= 3"); + for (Person person : result) { + println(person.toString()); + } + + println("Listen to data changes"); + // Use latches to control the timing for the purpose of this app. + CountDownLatch initialUpdateLatch = new CountDownLatch(1); + CountDownLatch waitForUpdateLatch = new CountDownLatch(1); + CancellationToken listenerToken = repository.updatesAsCallbacks((ResultsChange change) -> { + // Updates will happen on the thread determined by dispatcher running + // the flow on the Kotlin side. In this case a custom worker thread. + if (change instanceof InitialResults) { + println("Initial event: (size=" + change.getList().size() + ")"); + initialUpdateLatch.countDown(); + } else if (change instanceof UpdatedResults) { + UpdatedResults c = (UpdatedResults) change; + println("Update event: (" + + "insertions=" + c.getInsertions().length + + ", deletions=" + c.getDeletions().length + + ", changes=" + c.getChanges().length + + ")"); + waitForUpdateLatch.countDown(); + } else { + throw new IllegalStateException(); + } + }); + initialUpdateLatch.await(); + + println("Update data"); + repository.updateData((MutableRealm realm) -> { + realm.findLatest(result.get(0)).setName("UpdatedName"); + }); + waitForUpdateLatch.await(); + + println("Close Realm"); + listenerToken.cancel(); + repository.closeRealm(); + } + + private static void println(String message) { + System.out.println("JavaApp: " + message); + } + +} diff --git a/JavaKotlinMavenInterop/java-app-maven/pom.xml b/JavaKotlinMavenInterop/java-app-maven/pom.xml new file mode 100644 index 0000000..a2e8c8a --- /dev/null +++ b/JavaKotlinMavenInterop/java-app-maven/pom.xml @@ -0,0 +1,86 @@ + + + 4.0.0 + + com.mongodb.devicesync + java-app-maven + 1.0.0-SNAPSHOT + + + UTF-8 + 11 + 11 + + + + + mavenCentral + https://repo1.maven.org/maven2/ + + + + + + + com.mongodb.devicesync + kotlin-lib + 1.0-SNAPSHOT + + + + + src/main/java + + + org.codehaus.mojo + exec-maven-plugin + 1.6.0 + + com.mongodb.devicesync.javainterop.maven.JavaMavenApp + + + + + diff --git a/JavaKotlinMavenInterop/java-app-maven/src/main/java/com/mongodb/devicesync/javainterop/maven/JavaMavenApp.java b/JavaKotlinMavenInterop/java-app-maven/src/main/java/com/mongodb/devicesync/javainterop/maven/JavaMavenApp.java new file mode 100644 index 0000000..8bf169b --- /dev/null +++ b/JavaKotlinMavenInterop/java-app-maven/src/main/java/com/mongodb/devicesync/javainterop/maven/JavaMavenApp.java @@ -0,0 +1,85 @@ +package com.mongodb.devicesync.javainterop.maven; + +import com.mongodb.devicesync.kotlin.CancellationToken; +import com.mongodb.devicesync.kotlin.Person; +import com.mongodb.devicesync.kotlin.RealmRepository; +import io.realm.kotlin.MutableRealm; +import io.realm.kotlin.notifications.InitialResults; +import io.realm.kotlin.notifications.ResultsChange; +import io.realm.kotlin.notifications.UpdatedResults; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CountDownLatch; + +/** + * Java app demonstrating how you can work with Realm Kotlin. + * + * Since Realm Kotlin is required to be written in Kotlin and use + * Kotlin specific features like coroutines, we have hidden the + * implementation behind a Java friendly interface, which the + * Java app can then interact with. + */ +public class JavaMavenApp { + public static void main(String[] args) throws InterruptedException { + RealmRepository repository = new RealmRepository(); + + println("Opening Realm"); + repository.openRealm(); + + println("Write data"); + List persons = new ArrayList<>(); + for (int i = 0; i < 5; i++) { + Person umanagedPerson = new Person(); + umanagedPerson.setName("Person-" + i); + umanagedPerson.setAge(i); + persons.add(umanagedPerson); + } + repository.writeData(persons); + + println("Query data"); + List result = repository.readData("age <= 3"); + for (Person person : result) { + println(person.toString()); + } + + println("Listen to data changes"); + // Use latches to control the timing for the purpose of this app. + CountDownLatch initialUpdateLatch = new CountDownLatch(1); + CountDownLatch waitForUpdateLatch = new CountDownLatch(1); + CancellationToken listenerToken = repository.updatesAsCallbacks((ResultsChange change) -> { + // Updates will happen on the thread determined by dispatcher running + // the flow on the Kotlin side. In this case a custom worker thread. + if (change instanceof InitialResults) { + println("Initial event: (size=" + change.getList().size() + ")"); + initialUpdateLatch.countDown(); + } else if (change instanceof UpdatedResults) { + UpdatedResults c = (UpdatedResults) change; + println("Update event: (" + + "insertions=" + c.getInsertions().length + + ", deletions=" + c.getDeletions().length + + ", changes=" + c.getChanges().length + + ")"); + waitForUpdateLatch.countDown(); + } else { + throw new IllegalStateException(); + } + }); + initialUpdateLatch.await(); + + println("Update data"); + repository.updateData((MutableRealm realm) -> { + realm.findLatest(result.get(0)).setName("UpdatedName"); + }); + waitForUpdateLatch.await(); + + println("Close Realm"); + listenerToken.cancel(); + repository.closeRealm(); + } + + private static void println(String message) { + System.out.println("JavaApp: " + message); + } + +} diff --git a/JavaKotlinMavenInterop/kotlin-lib/build.gradle.kts b/JavaKotlinMavenInterop/kotlin-lib/build.gradle.kts new file mode 100644 index 0000000..aa02f15 --- /dev/null +++ b/JavaKotlinMavenInterop/kotlin-lib/build.gradle.kts @@ -0,0 +1,64 @@ +import java.net.URI + +plugins { + kotlin("jvm") + id("io.realm.kotlin") + `maven-publish` + signing +} + +group = "com.mongodb.devicesync" +version = "1.0-SNAPSHOT" + +repositories { + mavenCentral() +} + +java { + withSourcesJar() + withJavadocJar() +} + +publishing { + publications { + create("RealmKotlinInterface") { + from(components["kotlin"]) + groupId = project.group as String + artifactId = "kotlin-lib" + version = project.version as String + artifact(tasks["javadocJar"]) + artifact(tasks["sourcesJar"]) + } + } + repositories { + mavenLocal() + maven { + this.name = "CustomNexus" + credentials { + username = "" + password = "" + } + if((project.version as String).endsWith("-SNAPSHOT")) { + url = URI("https://pathToNexus.com/relativePathToSnaphots") + } else { + url = URI("https://pathToNexus.com/relativePathToReleases") + } + } + } +} + +dependencies { + api("io.realm.kotlin:library-sync-jvm:1.13.0") + api("io.reactivex.rxjava3:rxjava:3.0.0") + api("org.jetbrains.kotlinx:kotlinx-coroutines-rx3:1.3.9") + testImplementation(platform("org.junit:junit-bom:5.9.1")) + testImplementation("org.junit.jupiter:junit-jupiter") +} + +kotlin { + jvmToolchain(11) +} + +tasks.test { + useJUnitPlatform() +} \ No newline at end of file diff --git a/JavaKotlinMavenInterop/kotlin-lib/src/main/kotlin/com/mongodb/devicesync/kotlin/RealmRepository.kt b/JavaKotlinMavenInterop/kotlin-lib/src/main/kotlin/com/mongodb/devicesync/kotlin/RealmRepository.kt new file mode 100644 index 0000000..e657620 --- /dev/null +++ b/JavaKotlinMavenInterop/kotlin-lib/src/main/kotlin/com/mongodb/devicesync/kotlin/RealmRepository.kt @@ -0,0 +1,102 @@ +package com.mongodb.devicesync.kotlin + +import io.reactivex.rxjava3.core.Observable +import io.realm.kotlin.MutableRealm +import io.realm.kotlin.Realm +import io.realm.kotlin.RealmConfiguration +import io.realm.kotlin.ext.query +import io.realm.kotlin.notifications.ResultsChange +import io.realm.kotlin.types.BaseRealmObject +import kotlinx.coroutines.CoroutineName +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.Job +import kotlinx.coroutines.asCoroutineDispatcher +import kotlinx.coroutines.cancel +import kotlinx.coroutines.flow.collect +import kotlinx.coroutines.launch +import kotlinx.coroutines.rx3.asObservable +import java.util.concurrent.Executors + +class CancellationToken(val job: Job) { + fun cancel() { + job.cancel() + } +} + +class RealmRepository { + + interface UpdateCallback { + fun update(realm: MutableRealm) + } + + interface EventCallback { + fun update(item: ResultsChange) + } + + lateinit var realm: Realm + val realmDispatchers = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() - 1).asCoroutineDispatcher() + val realmScope: CoroutineScope = CoroutineScope(CoroutineName("RealmScope") + realmDispatchers) + + fun openRealm() { + val config = RealmConfiguration.Builder(schema = setOf(Person::class, Child::class)) + .name("javainterop-example.realm") + .build() + Realm.deleteRealm(config) // Cleanup any old test data + realm = Realm.open(config) + } + + fun closeRealm() { + checkRealm() + realmScope.cancel("Closing Realm") + realmDispatchers.close() + realm.close() + } + + fun writeData(person: Person): Person { + return realm.writeBlocking { + copyToRealm(person) + } + } + + fun writeData(list: List) { + realm.writeBlocking { + list.forEach { person: Person -> + copyToRealm(person) + } + } + } + + fun updateData(callback: UpdateCallback) { + realm.writeBlocking { + callback.update(this) + } + } + + fun readData(query: String): List { + return realm.query(query).find() + } + + @OptIn(ExperimentalCoroutinesApi::class) + fun updatesAsRxJavaObserverable(): Observable> { + return realm.query("TRUEPREDICATE").asFlow().asObservable() + } + + // Expose as callbacks with a cancellation token + fun updatesAsCallbacks(callback: EventCallback): CancellationToken { + val job: Job = realmScope.launch { + realm.query("TRUEPREDICATE").asFlow() + .collect { event: ResultsChange -> + callback.update(event) + } + } + return CancellationToken(job) + } + + private fun checkRealm() { + if (!this::realm.isInitialized) { + throw IllegalStateException("Realm must be opened before calling any other functions.") + } + } +} diff --git a/JavaKotlinMavenInterop/kotlin-lib/src/main/kotlin/com/mongodb/devicesync/kotlin/Schema.kt b/JavaKotlinMavenInterop/kotlin-lib/src/main/kotlin/com/mongodb/devicesync/kotlin/Schema.kt new file mode 100644 index 0000000..a7c70d4 --- /dev/null +++ b/JavaKotlinMavenInterop/kotlin-lib/src/main/kotlin/com/mongodb/devicesync/kotlin/Schema.kt @@ -0,0 +1,36 @@ +package com.mongodb.devicesync.kotlin + +import io.realm.kotlin.ext.realmListOf +import io.realm.kotlin.types.RealmList +import io.realm.kotlin.types.RealmObject +import io.realm.kotlin.types.annotations.PersistedName +import io.realm.kotlin.types.annotations.PrimaryKey +import org.mongodb.kbson.ObjectId + +class Person: RealmObject { + @PrimaryKey + @PersistedName("_id") + var id = ObjectId() + var name: String = "" + var age: Int = 0 + var children: RealmList = realmListOf() + var favoriteChild: Child? = null + + // Expose method making it easier to use from Java + fun setChildren(children: ArrayList) { + children.addAll(children) + } + + override fun toString(): String { + return "Person(id=$id, name='$name', age=$age, children=$children, favoriteChild=$favoriteChild)" + } +} + +class Child(s: String) : RealmObject { + // No-arg constructor required by Realm + constructor(): this("") + @PrimaryKey + @PersistedName("_id") + var id = ObjectId() + var name: String = s +} \ No newline at end of file diff --git a/JavaKotlinMavenInterop/settings.gradle b/JavaKotlinMavenInterop/settings.gradle new file mode 100644 index 0000000..7a28a37 --- /dev/null +++ b/JavaKotlinMavenInterop/settings.gradle @@ -0,0 +1,4 @@ +rootProject.name = 'JavaKotlinMavenInterop' +include 'kotlin-lib' +include 'java-app-gradle' + diff --git a/README.md b/README.md index cf0954a..9bc0d96 100644 --- a/README.md +++ b/README.md @@ -18,6 +18,8 @@ Samples are based on Kotlin `1.8.20`. | [Kotlin Multiplatform Demo](./MultiplatformDemo):
Kotlin Multiplatform demo running on Android/iOS/macOS and JVM with Compose Desktop. | | | | [JVM Console Application](./JVMConsole):
Simple Java Console Application using Realm-Kotlin. | | [App Services usage samples](./AppServicesUsageSamples):
Atlas App Services usage samples with Realm-Kotlin. | +| [Java-Kotlin-Maven Interop Demo](./JavaKotlinMavenInterop):
Sample project showing how Realm Kotlin can be consumed by a Java project using Maven. | + | External Project | | | | |---|---|---|---|