diff --git a/.github/workflows/java-release.yml b/.github/workflows/java-release.yml new file mode 100644 index 0000000..b51ab54 --- /dev/null +++ b/.github/workflows/java-release.yml @@ -0,0 +1,220 @@ +name: java-build + +on: + #태그를 트리거로 사용하시려면 주석을 제거하시고 사용하시면 됩니다# + #push: + # tags: + # - 'v*' + workflow_dispatch: + inputs: + version: + description: 'The version to release (e.g., 1.0.11)' + required: true + default: '1.0.11' + +jobs: + build-native-libs: + strategy: + fail-fast: false + matrix: + include: + - os: windows-latest + rust_target: x86_64-pc-windows-msvc + lib_name: braillify_java.dll + artifact_name: braillify-dll + native_path: windows-x86_64 + java_version: '8' + + - os: ubuntu-latest + rust_target: x86_64-unknown-linux-gnu + lib_name: libbraillify_java.so + artifact_name: braillify-so + native_path: linux-x86_64 + java_version: '8' + + - os: macos-15-intel + rust_target: x86_64-apple-darwin + lib_name: libbraillify_java.dylib + artifact_name: braillify-dylib-x86 + native_path: darwin-x86_64 + java_version: '8' + + - os: macos-15 + rust_target: aarch64-apple-darwin + lib_name: libbraillify_java.dylib + artifact_name: braillify-dylib-aarch64 + native_path: darwin-aarch64 + java_version: '11' + + runs-on: ${{ matrix.os }} + + defaults: + run: + working-directory: packages/java + + steps: + - name: Checkout required subtree only + uses: actions/checkout@v4 + + - name: Set version + id: set_version + shell: bash + run: | + if [[ "${{ github.event_name }}" == "workflow_dispatch" ]]; then + VERSION="${{ github.event.inputs.version }}" + else + VERSION="${GITHUB_REF#refs/tags/v}" + fi + echo "version=$VERSION" >> $GITHUB_OUTPUT + + - name: Update Cargo.toml version + braillify dependency version + shell: bash + run: | + python - <<'PY' + import re + from pathlib import Path + + version = "${{ steps.set_version.outputs.version }}" + path = Path("Cargo.toml") + + if not path.exists(): + raise SystemExit(f"Cargo.toml not found at: {path.resolve()}") + + s = path.read_text(encoding="utf-8") + s2, n_ver = re.subn(r'(?m)^(version\s*=\s*)".*"$', rf'\1"{version}"', s) + s3, n_dep = re.subn(r'(?m)^(braillify\s*=\s*)".*"$', rf'\1"{version}"', s2) + + if n_ver == 0: + raise SystemExit("Failed to update Cargo.toml: no 'version = \"...\"' line found.") + if n_dep == 0: + raise SystemExit("Failed to update Cargo.toml: no 'braillify = \"...\"' line found.") + + path.write_text(s3, encoding="utf-8") + print(f"Updated Cargo.toml: package version -> {version}, braillify dependency -> {version}") + PY + + - name: Set up JDK + uses: actions/setup-java@v4 + with: + java-version: ${{ matrix.java_version }} + distribution: 'temurin' + + - name: Set up Rust toolchain + uses: dtolnay/rust-toolchain@stable + with: + targets: ${{ matrix.rust_target }} + + - name: Grant execute permission for gradlew + if: runner.os != 'Windows' + run: chmod +x gradlew + + - name: Build native library (Windows) + if: runner.os == 'Windows' + shell: cmd + run: gradlew.bat cargoBuild --no-daemon + + - name: Build native library (Unix) + if: runner.os != 'Windows' + shell: bash + run: ./gradlew cargoBuild --no-daemon + + + - name: Upload native library artifact + uses: actions/upload-artifact@v4 + with: + name: ${{ matrix.artifact_name }} + path: ${{ github.workspace }}/packages/java/build/cargo-target/${{ matrix.rust_target }}/release/${{ matrix.lib_name }} + if-no-files-found: error + + assemble-jar: + runs-on: ubuntu-latest + needs: build-native-libs + + defaults: + run: + working-directory: packages/java + + steps: + - name: Checkout required subtree only + uses: actions/checkout@v4 + with: + fetch-depth: 1 + sparse-checkout: | + packages/java + packages/java/jar + sparse-checkout-cone-mode: true + + - name: Set version + id: set_version + shell: bash + run: | + if [[ "${{ github.event_name }}" == "workflow_dispatch" ]]; then + VERSION="${{ github.event.inputs.version }}" + else + VERSION="${GITHUB_REF#refs/tags/v}" + fi + echo "version=$VERSION" >> $GITHUB_OUTPUT + + - name: Set up JDK 8 + uses: actions/setup-java@v4 + with: + java-version: '8' + distribution: 'temurin' + + - name: Download native library artifacts + uses: actions/download-artifact@v4 + with: + path: native-libs + + - name: downloaded artifacts + shell: bash + run: ls -R "$GITHUB_WORKSPACE/native-libs" + + - name: Move native libraries + shell: bash + run: | + mkdir -p src/main/resources/natives/windows-x86_64 + mv "$GITHUB_WORKSPACE/native-libs/braillify-dll/braillify_java.dll" src/main/resources/natives/windows-x86_64/ + + mkdir -p src/main/resources/natives/linux-x86_64 + mv "$GITHUB_WORKSPACE/native-libs/braillify-so/libbraillify_java.so" src/main/resources/natives/linux-x86_64/ + + mkdir -p src/main/resources/natives/macos-x86_64 + mv "$GITHUB_WORKSPACE/native-libs/braillify-dylib-x86/libbraillify_java.dylib" src/main/resources/natives/macos-x86_64/ + + mkdir -p src/main/resources/natives/macos-aarch64 + mv "$GITHUB_WORKSPACE/native-libs/braillify-dylib-aarch64/libbraillify_java.dylib" src/main/resources/natives/macos-aarch64/ + + - name: Grant execute permission for gradlew + if: runner.os != 'Windows' + run: chmod +x gradlew + + - name: Assemble Universal JAR + run: ${{ github.workspace }}/packages/java/gradlew deployJar -PreleaseVersion=${{ steps.set_version.outputs.version }} --no-daemon + + - name: Copy jar into repo jar/ folder + shell: bash + run: | + mkdir -p "$GITHUB_WORKSPACE/packages/java/jar" + cp "$GITHUB_WORKSPACE/packages/java/build/libs/braillify-java-${{ steps.set_version.outputs.version }}.jar" "$GITHUB_WORKSPACE/packages/java/jar/" + + echo "== jar folder ==" + ls -al "$GITHUB_WORKSPACE/packages/java/jar" + + - name: Commit & push jar to repository + shell: bash + run: | + cd "$GITHUB_WORKSPACE" + + git config user.name "github-actions[bot]" + git config user.email "github-actions[bot]@users.noreply.github.com" + + git add packages/java/jar + + if git diff --cached --quiet; then + echo "No changes to commit." + exit 0 + fi + + git commit -m "chore(release): add universal jar ${{ steps.set_version.outputs.version }}" + git push \ No newline at end of file diff --git a/packages/java/.gitignore b/packages/java/.gitignore new file mode 100644 index 0000000..3617cb7 --- /dev/null +++ b/packages/java/.gitignore @@ -0,0 +1,25 @@ +*.log +*.lock +*.tmp +*.temp +.DS_Store +Thumbs.db +.idea/ +.vscode/ +*.iml +*.ipr +*.iws +.project +.classpath +.settings +.factorypath +build/ +out/ +dist/ +bin/ +**/target/ +Cargo.lock +output.txt + +.gradle/ +!gradle/wrapper/gradle-wrapper.jar \ No newline at end of file diff --git a/packages/java/Cargo.toml b/packages/java/Cargo.toml new file mode 100644 index 0000000..d010e3e --- /dev/null +++ b/packages/java/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "braillify-java" +version = "1.0.11" +edition = "2021" + +[lib] +crate-type = ["cdylib"] + +[dependencies] +braillify = "1.0.11" +jni = "0.21.1" diff --git a/packages/java/build.gradle.kts b/packages/java/build.gradle.kts new file mode 100644 index 0000000..3c40549 --- /dev/null +++ b/packages/java/build.gradle.kts @@ -0,0 +1,148 @@ +import org.gradle.api.GradleException +import org.gradle.api.file.DuplicatesStrategy +import org.gradle.api.tasks.bundling.Jar +import org.gradle.api.tasks.compile.JavaCompile + +plugins { + id("java") + id("maven-publish") + application +} + +data class NativeConfig( + val rustTarget: String, + val nativeLibName: String, + val nativePath: String +) + +val osName = System.getProperty("os.name").lowercase() +val osArch = System.getProperty("os.arch").lowercase() + +val nativeConfig: NativeConfig = when { + osName.contains("win") -> NativeConfig( + rustTarget = "x86_64-pc-windows-msvc", + nativeLibName = "braillify_java.dll", + nativePath = "windows-x86_64" + ) + + osName.contains("nix") || osName.contains("nux") -> NativeConfig( + rustTarget = "x86_64-unknown-linux-gnu", + nativeLibName = "libbraillify_java.so", + nativePath = "linux-x86_64" + ) + + osName.contains("mac") && (osArch == "aarch64" || osArch == "arm64") -> NativeConfig( + rustTarget = "aarch64-apple-darwin", + nativeLibName = "libbraillify_java.dylib", + nativePath = "darwin-aarch64" + ) + + osName.contains("mac") -> NativeConfig( + rustTarget = "x86_64-apple-darwin", + nativeLibName = "libbraillify_java.dylib", + nativePath = "darwin-x86_64" + ) + + else -> throw GradleException("Unsupported OS for cargo build: $osName ($osArch)") +} + +group = "com.devfive" +version = project.findProperty("releaseVersion") ?: "1.0.11" + +application { + mainClass.set("com.devfive.Braillify") +} + +repositories { + mavenCentral() +} + +dependencies { + implementation("org.scijava:native-lib-loader:2.5.0") + testImplementation(platform("org.junit:junit-bom:5.10.0")) + testImplementation("org.junit.jupiter:junit-jupiter") +} + +tasks.test { + useJUnitPlatform() +} + +tasks.withType { + duplicatesStrategy = DuplicatesStrategy.EXCLUDE +} + +val rustProjectDir = file("src/main/java/com/devfive") +val cargoTargetDir = layout.buildDirectory.dir("cargo-target").get().asFile + +tasks.register("cargoBuild") { + workingDir(rustProjectDir) + environment("CARGO_TARGET_DIR", cargoTargetDir.absolutePath) + + commandLine( + "cargo", + "build", + "--release", + "--target", + nativeConfig.rustTarget + ) +} + +tasks.register("copyNativeLib") { + dependsOn("cargoBuild") + from("${cargoTargetDir}/${nativeConfig.rustTarget}/release/${nativeConfig.nativeLibName}") + into("src/main/resources/natives/${nativeConfig.nativePath}") +} + + +tasks.named("processResources") { + dependsOn("copyNativeLib") +} + +tasks.named("jar") { + manifest { + attributes["Main-Class"] = "com.devfive.Braillify" + } + + from(sourceSets.main.get().output) + from(configurations.runtimeClasspath.get().map { if (it.isDirectory) it else zipTree(it) }) +} + +tasks.register("deployJar") { + archiveBaseName.set(project.name) + + manifest { + attributes["Main-Class"] = "com.devfive.Braillify" + } + + val compileJava = tasks.named("compileJava") + dependsOn(compileJava) + from(compileJava.map { it.destinationDirectory }) + from("src/main/resources") + from(configurations.runtimeClasspath.get().map { if (it.isDirectory) it else zipTree(it) }) +} + +val prebuiltJar = layout.projectDirectory.file("jar/${project.name}-${project.version}.jar") + +publishing { + publications { + create("mavenPrebuilt") { + groupId = project.group.toString() + artifactId = project.name + version = project.version.toString() + + artifact(prebuiltJar.asFile) { + extension = "jar" + } + + pom { + name.set(project.name) + licenses { + license { + name.set("Apache License 2.0") + url.set("https://www.apache.org/licenses/LICENSE-2.0") + } + } + } + } + } +} \ No newline at end of file diff --git a/packages/java/gradle/wrapper/gradle-wrapper.jar b/packages/java/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..249e583 Binary files /dev/null and b/packages/java/gradle/wrapper/gradle-wrapper.jar differ diff --git a/packages/java/gradle/wrapper/gradle-wrapper.properties b/packages/java/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..de89399 --- /dev/null +++ b/packages/java/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Sun Oct 26 16:52:13 KST 2025 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.10-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/packages/java/gradlew b/packages/java/gradlew new file mode 100644 index 0000000..1b6c787 --- /dev/null +++ b/packages/java/gradlew @@ -0,0 +1,234 @@ +#!/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 \ + "$@" + +# 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/packages/java/gradlew.bat b/packages/java/gradlew.bat new file mode 100644 index 0000000..107acd3 --- /dev/null +++ b/packages/java/gradlew.bat @@ -0,0 +1,89 @@ +@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%" == "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%"=="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/packages/java/jar/braillify-java-1.0.11.jar b/packages/java/jar/braillify-java-1.0.11.jar new file mode 100644 index 0000000..56bbc3c Binary files /dev/null and b/packages/java/jar/braillify-java-1.0.11.jar differ diff --git a/packages/java/settings.gradle.kts b/packages/java/settings.gradle.kts new file mode 100644 index 0000000..d6f8202 --- /dev/null +++ b/packages/java/settings.gradle.kts @@ -0,0 +1,2 @@ +rootProject.name = "braillify-java" + diff --git a/packages/java/src/lib.rs b/packages/java/src/lib.rs new file mode 100644 index 0000000..43ee694 --- /dev/null +++ b/packages/java/src/lib.rs @@ -0,0 +1,92 @@ +use jni::objects::{JClass, JString}; +use jni::sys::{jbyteArray, jstring}; +use jni::JNIEnv; +use braillify as braillify_core; + +fn throw_braillify_exception(env: &mut JNIEnv, msg: &str) { + let _ = env.throw_new("com/devfive/BraillifyException", msg); +} + +fn throw_runtime_exception(env: &mut JNIEnv, msg: &str) { + let _ = env.throw_new("java/lang/RuntimeException", msg); +} + +fn get_input_string(env: &mut JNIEnv, input: JString) -> Option { + match env.get_string(&input) { + Ok(s) => Some(s.into()), + Err(e) => { + throw_runtime_exception(env, &format!("입력 문자열을 읽는 데 실패했습니다: {e}")); + None + } + } +} + +#[no_mangle] +pub extern "system" fn Java_com_devfive_Braillify_encodeToUnicode( + mut env: JNIEnv, + _class: JClass, + input: JString, +) -> jstring { + let Some(input_str) = get_input_string(&mut env, input) else { + return std::ptr::null_mut(); + }; + + let mut out = String::with_capacity(input_str.len()); + + for c in input_str.chars() { + let char_str = c.to_string(); + match braillify_core::encode_to_unicode(&char_str) { + Ok(encoded) => out.push_str(&encoded), + Err(e) => { + throw_braillify_exception( + &mut env, + &format!("점자 유니코드 변환 실패 (문자: '{c}'): {e}"), + ); + return std::ptr::null_mut(); + } + } + } + + match env.new_string(out) { + Ok(s) => s.into_raw(), + Err(e) => { + throw_runtime_exception(&mut env, &format!("결과 문자열 생성 실패: {e}")); + std::ptr::null_mut() + } + } +} + +#[no_mangle] +pub extern "system" fn Java_com_devfive_Braillify_encode( + mut env: JNIEnv, + _class: JClass, + input: JString, +) -> jbyteArray { + let Some(input_str) = get_input_string(&mut env, input) else { + return std::ptr::null_mut(); + }; + + let mut out: Vec = Vec::new(); + + for c in input_str.chars() { + let char_str = c.to_string(); + match braillify_core::encode(&char_str) { + Ok(bytes) => out.extend_from_slice(&bytes), + Err(e) => { + throw_braillify_exception( + &mut env, + &format!("점자 바이트 변환 실패 (문자: '{c}'): {e}"), + ); + return std::ptr::null_mut(); + } + } + } + + match env.byte_array_from_slice(&out) { + Ok(arr) => arr.into_raw(), + Err(e) => { + throw_runtime_exception(&mut env, &format!("바이트 배열 생성 실패: {e}")); + std::ptr::null_mut() + } + } +} diff --git a/packages/java/src/main/java/com/devfive/Braillify.java b/packages/java/src/main/java/com/devfive/Braillify.java new file mode 100644 index 0000000..0b0def3 --- /dev/null +++ b/packages/java/src/main/java/com/devfive/Braillify.java @@ -0,0 +1,82 @@ +/* + * Copyright 2026-2026 the original author or 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. + */ +package com.devfive; + +import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; + +/** + * The main entry point for the Braillify library. + * This class handles the automatic loading of the platform-specific native library + * and exposes the native encoding methods to Java. + * + * @author Yejeong Ham + * @since 1.0.11 + */ +public class Braillify { + + static { + try { + loadNative(); + } catch (Exception e) { + throw new RuntimeException("Failed to load native library", e); + } + } + + private static void loadNative() throws Exception { + String os = System.getProperty("os.name").toLowerCase(); + String arch = System.getProperty("os.arch").toLowerCase(); + String platform; + String libName; + + if (os.contains("win")) { + platform = "windows-x86_64"; + libName = "braillify_java.dll"; + } else if (os.contains("linux")) { + platform = "linux-x86_64"; + libName = "libbraillify_java.so"; + } else if (os.contains("mac")) { + if (arch.contains("aarch64") || arch.contains("arm")) { + platform = "macos-aarch64"; + } else { + platform = "macos-x86_64"; + } + libName = "libbraillify_java.dylib"; + } else { + throw new UnsupportedOperationException("Unsupported OS: " + os); + } + + String resourcePath = "/natives/" + platform + "/" + libName; + + InputStream in = Braillify.class.getResourceAsStream(resourcePath); + if (in == null) { + throw new RuntimeException("Native library not found: " + resourcePath); + } + + Path tempFile = Files.createTempFile("braillify-", libName); + tempFile.toFile().deleteOnExit(); + + Files.copy(in, tempFile, StandardCopyOption.REPLACE_EXISTING); + in.close(); + + System.load(tempFile.toAbsolutePath().toString()); + } + + public static native String encodeToUnicode(String input); + public static native byte[] encode(String input); +} diff --git a/packages/java/src/main/java/com/devfive/BraillifyException.java b/packages/java/src/main/java/com/devfive/BraillifyException.java new file mode 100644 index 0000000..9017424 --- /dev/null +++ b/packages/java/src/main/java/com/devfive/BraillifyException.java @@ -0,0 +1,33 @@ +/* + * Copyright 2026-2026 the original author or 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. + */ +package com.devfive; + +/** + * A custom RuntimeException for the Braillify library. + * + * @author Yejeong Ham + * @since 1.0.11 + */ +public class BraillifyException extends RuntimeException { + + public BraillifyException(String message) { + super(message); + } + + public BraillifyException(String message, Throwable cause) { + super(message, cause); + } +} \ No newline at end of file diff --git a/packages/java/src/main/resources/.gitkeep b/packages/java/src/main/resources/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/packages/java/src/main/resources/natives/windows-x86_64/braillify_java.dll b/packages/java/src/main/resources/natives/windows-x86_64/braillify_java.dll new file mode 100644 index 0000000..9e48754 Binary files /dev/null and b/packages/java/src/main/resources/natives/windows-x86_64/braillify_java.dll differ