commit 0268f0788bf9ace4bebb0e3690b542550b626461 Author: siujamo Date: Tue Jun 2 14:01:53 2026 +0800 refactor: migrate from repo onixbyte/onixbyte-toolbox to module repos diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..d01b18f --- /dev/null +++ b/.editorconfig @@ -0,0 +1,42 @@ +[*] +charset = utf-8 +end_of_line = lf +indent_size = 4 +indent_style = space +insert_final_newline = true +max_line_length = 100 +tab_width = 4 + +[*.less] +indent_size = 2 + +[*.proto] +indent_size = 2 +tab_width = 2 + +[*.sass] +indent_size = 2 + +[*.scss] +indent_size = 2 + +[*.vue] +indent_size = 2 +tab_width = 2 + +[{*.bash,*.sh,*.zsh}] +indent_size = 2 +tab_width = 2 + +[{*.default,*.yaml,*.yml}] +indent_size = 2 + +[{*.har,*.jsb2,*.jsb3,*.json,*.jsonc,*.postman_collection,*.postman_collection.json,*.postman_environment,*.postman_environment.json,.babelrc,.eslintrc,.prettierrc,.stylelintrc,.ws-context,jest.config}] +indent_size = 2 + +[{*.pb,*.textproto,*.txtpb}] +indent_size = 2 +tab_width = 2 + +[{*.ps1,*.psd1,*.psm1}] +max_line_length = 115 diff --git a/.github/workflows/build-and-deploy.yml b/.github/workflows/build-and-deploy.yml new file mode 100644 index 0000000..8e1abce --- /dev/null +++ b/.github/workflows/build-and-deploy.yml @@ -0,0 +1,96 @@ +# Publishes onixbyte-tuple to Maven Central when a version tag is pushed to main. +# +# Supported tag format: ..[-suffix] (e.g. 3.3.1, 3.3.1-alpha) + +name: Publish Package to Maven Central + +on: + push: + tags: + - '[0-9]*.[0-9]*.[0-9]*' + +jobs: + publish: + name: Build and Publish + runs-on: ubuntu-latest + permissions: + contents: read + + steps: + - name: Checkout + uses: actions/checkout@v4.2.2 + with: + fetch-depth: 0 + + - name: Verify Tag is on Main Branch + run: | + if ! git merge-base --is-ancestor HEAD origin/main; then + echo "::error::Tag ${{ github.ref_name }} does not point to a commit on the main branch" + echo "Tags must be pushed after the commit is merged to main." + exit 1 + fi + echo "✓ Tag ${{ github.ref_name }} is on main" + + - name: Extract Version + id: version + run: | + VERSION="${{ github.ref_name }}" + echo "version=${VERSION}" >> $GITHUB_OUTPUT + echo "Version: ${VERSION}" + + - name: Setup GPG TTY + run: export GPG_TTY=$(tty) + + - name: Import PGP Private Key + uses: crazy-max/ghaction-import-gpg@v6.3.0 + with: + gpg_private_key: ${{ secrets.GPG_PRIVATE_KEY }} + passphrase: ${{ secrets.GPG_PASSPHRASE }} + trust_level: 5 + + - name: Creating PGP Ring Key + run: | + mkdir -p ~/.gnupg + echo ${{ secrets.GPG_PASSPHRASE }} | gpg --batch --yes --pinentry-mode loopback --passphrase-fd 0 --export-secret-keys -o ~/.gnupg/gpg_key.ring + + - name: Restore gradle.properties + env: + GRADLE_PROPERTIES: ${{ secrets.GRADLE_PROPERTIES }} + shell: bash + run: | + mkdir -p ~/.gradle/ + echo "GRADLE_USER_HOME=${HOME}/.gradle" >> $GITHUB_ENV + echo "${GRADLE_PROPERTIES}" > ~/.gradle/gradle.properties + + - name: Set up JDK 17 + uses: actions/setup-java@v4 + with: + java-version: "17" + distribution: "corretto" + + - name: Setup Gradle + uses: gradle/actions/setup-gradle@v4.4.1 + + - name: Grant Execution Authority to Gradlew + run: chmod +x ./gradlew + + - name: Build with Gradle + env: + VERSION: ${{ steps.version.outputs.version }} + run: ./gradlew build "-PartefactVersion=${VERSION}" + + - name: List Output Items + run: ls -l ./build/libs + + - name: Publish to Maven Central + env: + VERSION: ${{ steps.version.outputs.version }} + run: ./gradlew publish "-PartefactVersion=${VERSION}" + + - name: Create Deployment on Central Publisher Portal + run: | + curl --fail -X 'POST' \ + 'https://ossrh-staging-api.central.sonatype.com/manual/upload/defaultRepository/com.onixbyte?publishing_type=user_managed' \ + -H 'accept: */*' \ + -H 'Authorization: Bearer ${{ secrets.MAVEN_PORTAL_TOKEN }}' \ + -d '' diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..79b8c8c --- /dev/null +++ b/.gitignore @@ -0,0 +1,42 @@ +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### IntelliJ IDEA ### +.idea +.idea/modules.xml +.idea/jarRepositories.xml +.idea/compiler.xml +.idea/libraries/ +*.iws +*.iml +*.ipr + +### Eclipse ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ + +### Mac OS ### +.DS_Store + +### Gradle ### +.gradle \ No newline at end of file diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..b18c455 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,62 @@ +# Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our project +a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, +gender identity and expression, level of experience, nationality, personal appearance, race, +religion, or sexual identity and orientation. + +## Our Standards + +Examples of behaviour that contributes to creating a positive environment include: + +- Using welcoming and inclusive language +- Being respectful of differing viewpoints and experiences +- Gracefully accepting constructive criticism +- Focusing on what is best for the community +- Showing empathy towards other community members + +Examples of unacceptable behaviour by participants include: + +- The use of sexualised language or imagery, and unwelcome sexual attention or advances +- Trolling, insulting, or derogatory comments +- Personal or political attacks +- Public or private harassment +- Publishing others’ private information, such as a physical or electronic address, without + explicit permission +- Other conduct which could reasonably be considered inappropriate in a professional setting + +## Enforcement Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable behaviour and are +expected to take appropriate and fair corrective action in response to any instances of +unacceptable behaviour. + +Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, +code, wiki edits, issues, and other contributions that do not align with this Code of Conduct, and +will communicate reasons for moderation decisions when appropriate. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces when an individual is +representing the project or its community. Examples of representing a project or community include +using an official project email address, posting via an official social media account, or acting as +an appointed representative at an online or offline event. + +## Enforcement + +Instances of abusive, harassing, or unacceptable behaviour may be reported by contacting the +project team at [opensource@onixbyte.com](mailto:opensource@onixbyte.com). All complaints will be +reviewed and investigated and will result in a response that is deemed necessary and appropriate to +the circumstances. The project team is obligated to maintain confidentiality with regard to the +reporter of an incident. + +Project maintainers who do not follow or enforce the Code of Conduct in good faith may face +temporary or permanent repercussions as determined by other members of the project's leadership. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant](https://www.contributor-covenant.org/), +version 1.4, available at https://www.contributor-covenant.org/version/1/4/ + diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..5ed8874 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,61 @@ +# Contributing to OnixByte Toolbox + +We appreciate your interest in contributing to our Java Enterprise Utility Library. Contributions +are welcome in various forms such as code, documentation, bug reports, and test cases. To ensure a +smooth collaboration, please follow the guidelines outlined below. + +## Getting Started + +The OnixByte Toolbox is an open-source Java library designed to ease Java enterprise +application development. It is built with Java 17, and we require contributors to use OpenJDK 17. + +## Development Setup + +There is no need for manual setup beyond ensuring you have JDK 17 and a stable internet connection. +Our project uses Gradle Wrapper for building, simplifying the setup process. + +```shell +./gradlew build +``` + +## Branching Strategy + +We follow the `git-flow` branching model. Contributors should fork this repository and create their +work on separate branches prefixed with `feature/` or `hotfix/` as appropriate. + +## Code Style + +Please adhere to the coding standards specified in our `.editorconfig` file in the root of +the repository. Consistent style helps in maintaining readability and uniformity across the codebase. + +## Commit Messages + +We require that commit messages follow this structure: + +```text +type[(scope)]: subject + +[body] + +[BREAKING CHANGE: breaking changes] +``` + +This format helps in auto-generating changelogs and understanding the purpose behind changes. + +## Submitting Contributions + +1. Fork the repository. +2. Create a branch: `git checkout -b feature/my-new-feature` or `git checkout -b hotfix/my-fix`. +3. Make your changes and commit them. +4. Push to the branch: `git push origin feature/my-new-feature`. +5. Create a Pull Request with a succinct subject and a detailed body. + +## Testing + +We encourage using JUnit Jupiter for unit and integration tests. Pull Requests with accompanying +test reports are prioritised for review and merging. + +## License + +By contributing to the OnixByte Toolbox, you agree that your contributions will be licensed under the +MIT license. If you do not agree to this, please refrain from contributing. diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..8c2f4a4 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024-2025 OnixByte + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..d77c49d --- /dev/null +++ b/README.md @@ -0,0 +1,38 @@ +# Module `guid` + +## Introduction + +Module `guid` serves as a guid creator for other `JDevKit` modules. You can also use this module as a guid creator standards. + +We have already implemented `SnowflakeGuidCreator`, you can also implement a custom guid creations by implementing `com.onixbyte.identitygenerator.IdentityGenerator`. + +## Example usage + +### A UUID creator + +```java +GuidCreator uuidCreator = (GuidCreator) UUID::randomUUID; +``` + +### A custom guid creator + +Assume that you need serial guid creator. + +```java +@Component +public class CustomGuidCreator implementes GuidCreator { + + public final RedisTemplate serialRedisTemplate; + + @Autowired + public CustomGuidCreator(RedisTemplate serialRedisTemplate) { + this.serialRedisTemplate = serialRedisTemplate; + } + + @Override public String nextId() { + return "SOME_PREFIX" + serialRedisTemplate.opsForValue().get("some_serial_key"); + } + +} +``` + diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..2aeae2c --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,131 @@ +/* + * Copyright (c) 2024-2026 OnixByte + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +import java.net.URI + +plugins { + java + id("java-library") + id("maven-publish") + id("signing") +} + +val artefactVersion: String by project + +version = artefactVersion +val projectUrl: String by project +val projectGithubUrl: String by project +val licenseName: String by project +val licenseUrl: String by project + +repositories { + mavenCentral() +} + +java { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + withSourcesJar() + withJavadocJar() +} + +tasks.withType { + options.encoding = "UTF-8" +} + +tasks.withType { + exclude("logback.xml") +} + +dependencies { + compileOnly(libs.slf4j) + implementation(libs.logback) + testImplementation(platform(libs.junit.bom)) + testImplementation(libs.junit.jupiter) +} + +tasks.test { + useJUnitPlatform() +} + +publishing { + publications { + create("identityGenerator") { + groupId = group.toString() + artifactId = "identity-generator" + version = artefactVersion + + pom { + name = "OnixByte Identity Generator" + description = "The module for generating GUIDs of JDevKit." + url = projectUrl + + licenses { + license { + name = licenseName + url = licenseUrl + } + } + + scm { + connection = "scm:git:git://github.com:OnixByte/JDevKit.git" + developerConnection = "scm:git:git://github.com:OnixByte/JDevKit.git" + url = projectGithubUrl + } + + developers { + developer { + id = "zihluwang" + name = "Zihlu Wang" + email = "real@zihluwang.me" + timezone = "Asia/Hong_Kong" + } + + developer { + id = "siujamo" + name = "Siu Jam'o" + email = "jamo.siu@gmail.com" + timezone = "Asia/Shanghai" + } + } + } + + from(components["java"]) + + signing { + setRequired(project.hasProperty("signing.keyId")) + sign(publishing.publications["identityGenerator"]) + } + } + + repositories { + maven { + name = "sonatypeNexus" + url = URI(providers.gradleProperty("repo.maven-central.host").get()) + credentials { + username = providers.gradleProperty("repo.maven-central.username").get() + password = providers.gradleProperty("repo.maven-central.password").get() + } + } + } + } +} diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..646fb18 --- /dev/null +++ b/gradle.properties @@ -0,0 +1,27 @@ +# +# Copyright (c) 2024-2025 OnixByte +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. +# + +artefactVersion=3.3.0 +projectUrl=https://github.com/onixbyte/onixbyte-tuple +projectGithubUrl=git@github.com:onixbyte/onixbyte-tuple.git +licenseName=MIT +licenseUrl= diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml new file mode 100644 index 0000000..42c64d6 --- /dev/null +++ b/gradle/libs.versions.toml @@ -0,0 +1,10 @@ +[versions] +slf4j = "2.0.17" +logback = "1.5.26" +junit = "5.11.4" + +[libraries] +slf4j = { group = "org.slf4j", name = "slf4j-api", version.ref = "slf4j" } +logback = { group = "ch.qos.logback", name = "logback-classic", version.ref = "logback" } +junit-bom = { group = "org.junit", name = "junit-bom", version.ref = "junit" } +junit-jupiter = { group = "org.junit.jupiter", name = "junit-jupiter", version.ref = "junit" } diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..a4b76b9 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..79eb9d0 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.10.2-all.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..f5feea6 --- /dev/null +++ b/gradlew @@ -0,0 +1,252 @@ +#!/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. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# 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/HEAD/platforms/jvm/plugins-application/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 + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s +' "$PWD" ) || exit + +# 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 + if ! command -v java >/dev/null 2>&1 + then + 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 +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + 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 + + +# 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"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +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/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..9d21a21 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,94 @@ +@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 +@rem SPDX-License-Identifier: Apache-2.0 +@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=. +@rem This is normally unused +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. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +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/src/main/java/com/onixbyte/identitygenerator/IdentityGenerator.java b/src/main/java/com/onixbyte/identitygenerator/IdentityGenerator.java new file mode 100644 index 0000000..d9317ea --- /dev/null +++ b/src/main/java/com/onixbyte/identitygenerator/IdentityGenerator.java @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2024-2026 OnixByte + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package com.onixbyte.identitygenerator; + +/** + * The {@code IdentityGenerator} is a generic interface for generating globally unique identifiers + * (GUIDs) of a specific type. + *

+ * The type of ID is determined by the class implementing this interface. + *

+ * + *

Example usage:

+ *
{@code
+ * public class StringGuidCreator implements IdentityGenerator {
+ *     private final AtomicLong counter = new AtomicLong();
+ *
+ *     @Override
+ *     public String nextId() {
+ *         return UUID.randomUUID().toString() + "-" + counter.incrementAndGet();
+ *     }
+ * }
+ *
+ * public class Example {
+ *     public static void main(String[] args) {
+ *         IdentityGenerator guidCreator = new StringGuidCreator();
+ *         String guid = guidCreator.nextId();
+ *         System.out.println("Generated GUID: " + guid);
+ *     }
+ * }
+ * }
+ * + * @param this represents the type of the Global Unique Identifier + * @author zihluwang + * @version 3.0.0 + */ +public interface IdentityGenerator { + + /** + * Generates and returns the next globally unique ID. + * + * @return the next globally unique ID + */ + IdType nextId(); + +} diff --git a/src/main/java/com/onixbyte/identitygenerator/exceptions/TimingException.java b/src/main/java/com/onixbyte/identitygenerator/exceptions/TimingException.java new file mode 100644 index 0000000..0468f3c --- /dev/null +++ b/src/main/java/com/onixbyte/identitygenerator/exceptions/TimingException.java @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2024-2026 OnixByte + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package com.onixbyte.identitygenerator.exceptions; + +/** + * The {@code TimingException} class represents an exception that is thrown when there is an error + * related to time sequence. + *

+ * Instances of TimingException can be created with or without a message and a cause. The message + * provides a description of the exception, while the cause represents the underlying cause of the + * exception and provides additional information about the error. + * + * @author zihluwang + * @since 3.0.0 + */ +public class TimingException extends RuntimeException { + + /** + * A custom exception that is thrown when there is an issue with timing or scheduling. + */ + public TimingException() { + } + + /** + * A custom exception that is thrown when there is an issue with timing or scheduling with + * customised error message. + * + * @param message customised message + */ + public TimingException(String message) { + super(message); + } + + /** + * A custom exception that is thrown when there is an issue with timing or scheduling with + * customised error message. + * + * @param message customised message + * @param cause the cause of this exception + */ + public TimingException(String message, Throwable cause) { + super(message, cause); + } + + /** + * A custom exception that is thrown when there is an issue with timing or scheduling with + * customised error message. + * + * @param cause the cause of this exception + */ + public TimingException(Throwable cause) { + super(cause); + } +} diff --git a/src/main/java/com/onixbyte/identitygenerator/impl/SequentialUuidGenerator.java b/src/main/java/com/onixbyte/identitygenerator/impl/SequentialUuidGenerator.java new file mode 100644 index 0000000..e9cad69 --- /dev/null +++ b/src/main/java/com/onixbyte/identitygenerator/impl/SequentialUuidGenerator.java @@ -0,0 +1,95 @@ +/* + * Copyright (c) 2024-2026 OnixByte + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package com.onixbyte.identitygenerator.impl; + +import com.onixbyte.identitygenerator.IdentityGenerator; + +import java.nio.ByteBuffer; +import java.security.SecureRandom; +import java.util.UUID; + +/** + * A {@code SequentialUuidGenerator} is responsible for generating UUIDs following the + * UUID version 7 specification, which combines a timestamp with random bytes to create time-ordered + * unique identifiers. + *

+ * This implementation utilises a cryptographically strong {@link SecureRandom} instance to produce + * the random component of the UUID. The first 6 bytes of the UUID encode the current timestamp in + * milliseconds, ensuring that generated UUIDs are roughly ordered by creation time. + *

+ * The generated UUID adheres strictly to the layout and variant bits of UUID version 7 as defined + * in the specification. + * + * @author zihluwang + * @author siujamo + * @version 3.0.0 + */ +public class SequentialUuidGenerator implements IdentityGenerator { + + private final SecureRandom random; + + /** + * Constructs a new {@code SequentialUuidGenerator} with its own {@link SecureRandom} instance. + */ + public SequentialUuidGenerator() { + this.random = new SecureRandom(); + } + + /** + * Generates and returns the next UUID version 7 identifier. + * + * @return a {@link UUID} instance representing a unique, time-ordered identifier + */ + @Override + public UUID nextId() { + var value = randomBytes(); + var buf = ByteBuffer.wrap(value); + var high = buf.getLong(); + var low = buf.getLong(); + return new UUID(high, low); + } + + /** + * Produces a byte array representation of a UUID version 7, + * combining the current timestamp with random bytes. + * + * @return a 16-byte array conforming to UUIDv7 layout and variant bits + */ + private byte[] randomBytes() { + var value = new byte[16]; + random.nextBytes(value); + + var timestamp = ByteBuffer.allocate(Long.BYTES); + timestamp.putLong(System.currentTimeMillis()); + + System.arraycopy(timestamp.array(), 2, value, 0, 6); + + // Set version to 7 (UUIDv7) + value[6] = (byte) ((value[6] & 0x0F) | 0x70); + + // Set variant bits as per RFC 4122 + value[8] = (byte) ((value[8] & 0x3F) | 0x80); + + return value; + } +} diff --git a/src/main/java/com/onixbyte/identitygenerator/impl/SnowflakeIdentityGenerator.java b/src/main/java/com/onixbyte/identitygenerator/impl/SnowflakeIdentityGenerator.java new file mode 100644 index 0000000..041cef4 --- /dev/null +++ b/src/main/java/com/onixbyte/identitygenerator/impl/SnowflakeIdentityGenerator.java @@ -0,0 +1,207 @@ +/* + * Copyright (c) 2024-2026 OnixByte + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package com.onixbyte.identitygenerator.impl; + +import com.onixbyte.identitygenerator.IdentityGenerator; +import com.onixbyte.identitygenerator.exceptions.TimingException; + +import java.time.LocalDateTime; +import java.time.ZoneId; + +/** + * The {@code SnowflakeIdentityGenerator} generates unique identifiers using the + * Snowflake algorithm, which combines a timestamp, worker ID, and data centre ID to create 64-bit + * long integers. The bit distribution for the generated IDs is as follows: + *

    + *
  • 1 bit for sign
  • + *
  • 41 bits for timestamp (in milliseconds)
  • + *
  • 5 bits for data centre ID
  • + *
  • 5 bits for worker ID
  • + *
  • 12 bits for sequence number (per millisecond)
  • + *
+ *

+ * When initialising a {@link SnowflakeIdentityGenerator}, you must provide the worker ID and data + * centre ID, ensuring they are within the valid range defined by the bit size. The generator + * maintains an internal sequence number that increments for IDs generated within the + * same millisecond. If the system clock moves backward, an exception is thrown to prevent + * generating IDs with repeated timestamps. + * + * @author zihluwang + * @version 3.0.0 + */ +public final class SnowflakeIdentityGenerator implements IdentityGenerator { + + /** + * Default custom epoch. + * + * @value 2015-01-01T00:00:00Z + */ + private static final long DEFAULT_CUSTOM_EPOCH = 1_420_070_400_000L; + + /** + * The start epoch timestamp to generate IDs from. + */ + private final long startEpoch; + + /** + * The number of bits reserved for the data centre ID. + */ + private static final long DATA_CENTRE_ID_BITS = 5L; + + /** + * The number of bits reserved for the worker ID. + */ + private static final long WORKER_ID_BITS = 5L; + + /** + * The worker ID assigned to this generator. + */ + private final long workerId; + + /** + * The data centre ID assigned to this generator. + */ + private final long dataCentreId; + + /** + * The current sequence number. + */ + private long sequence = 0L; + + /** + * The timestamp of the last generated ID. + */ + private long lastTimestamp = -1L; + + /** + * Constructs a SnowflakeGuidGenerator with the default start epoch and custom worker ID, data + * centre ID. + * + * @param dataCentreId the data centre ID (between 0 and 31) + * @param workerId the worker ID (between 0 and 31) + */ + public SnowflakeIdentityGenerator(long dataCentreId, long workerId) { + this(dataCentreId, workerId, DEFAULT_CUSTOM_EPOCH); + } + + /** + * Constructs a SnowflakeGuidGenerator with a custom epoch, worker ID, and data centre ID. + * + * @param dataCentreId the data centre ID (between 0 and 31) + * @param workerId the worker ID (between 0 and 31) + * @param startEpoch the custom epoch timestamp (in milliseconds) to start generating IDs from + * @throws IllegalArgumentException if the start epoch is greater than the current timestamp, + * or if the worker ID or data centre ID is out of range + */ + public SnowflakeIdentityGenerator(long dataCentreId, long workerId, long startEpoch) { + if (startEpoch > currentTimestamp()) { + throw new IllegalArgumentException("Start Epoch can not be greater than current timestamp!"); + } + + var maxWorkerId = ~(-1L << WORKER_ID_BITS); + if (workerId > maxWorkerId || workerId < 0) { + throw new IllegalArgumentException(String.format("Worker Id can't be greater than %d or less than 0", + maxWorkerId)); + } + + var maxDataCentreId = ~(-1L << DATA_CENTRE_ID_BITS); + if (dataCentreId > maxDataCentreId || dataCentreId < 0) { + throw new IllegalArgumentException(String.format("Data Centre Id can't be greater than %d or less than 0", + maxDataCentreId)); + } + + this.startEpoch = startEpoch; + this.workerId = workerId; + this.dataCentreId = dataCentreId; + } + + /** + * Generates the next unique ID. + * + * @return the generated unique ID + * @throws TimingException if the system clock moves backwards, indicating an invalid sequence + * of timestamps. + */ + @Override + public synchronized Long nextId() { + var timestamp = currentTimestamp(); + + // if the current time is less than the timestamp of the last ID generation, it means that + // the system clock has been set back and an exception should be thrown + if (timestamp < lastTimestamp) { + throw new TimingException("Clock moved backwards. Refusing to generate id for %d milliseconds" + .formatted(lastTimestamp - timestamp)); + } + + // if generated at the same time, perform intra-millisecond sequences + var sequenceBits = 12L; + if (lastTimestamp == timestamp) { + var sequenceMask = ~(-1L << sequenceBits); + sequence = (sequence + 1) & sequenceMask; + // sequence overflow in milliseconds + if (sequence == 0) { + // block to the next millisecond, get a new timestamp + timestamp = awaitToNextMillis(lastTimestamp); + } + } else { + // timestamp change, sequence reset in milliseconds + sequence = 0L; + } + + // timestamp of last ID generation + lastTimestamp = timestamp; + + // shifted and put together by or operations to form a 64-bit ID + var timestampLeftShift = sequenceBits + WORKER_ID_BITS + DATA_CENTRE_ID_BITS; + var dataCentreIdShift = sequenceBits + WORKER_ID_BITS; + return ((timestamp - startEpoch) << timestampLeftShift) + | (dataCentreId << dataCentreIdShift) + | (workerId << sequenceBits) + | sequence; + } + + /** + * Blocks until the next millisecond to obtain a new timestamp. + * + * @param lastTimestamp the timestamp when the last ID was generated + * @return the current timestamp + */ + private long awaitToNextMillis(long lastTimestamp) { + var timestamp = currentTimestamp(); + while (timestamp <= lastTimestamp) { + timestamp = currentTimestamp(); + } + return timestamp; + } + + /** + * Returns the current timestamp in milliseconds. + * + * @return the current timestamp + */ + private long currentTimestamp() { + return LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(); + } + +} + diff --git a/src/main/resources/logback.xml b/src/main/resources/logback.xml new file mode 100644 index 0000000..85b705f --- /dev/null +++ b/src/main/resources/logback.xml @@ -0,0 +1,39 @@ + + + + + + + + + + + ${COLOURFUL_OUTPUT} + + + + + +