diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..55dce6a --- /dev/null +++ b/.gitattributes @@ -0,0 +1,11 @@ +#region Gradle +/gradlew text eol=lf +#endregion + +#region Java +*.jar binary +#endregion + +#region Windows +*.bat text eol=crlf +#endregion diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..9940d12 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,107 @@ +name: Publish Release + +on: + release: + types: [published] + +env: + # --- GLOBAL OVERRIDES --- + # Modify these variables to override default GitHub context + PROJECT_NAME: ${{ github.event.repository.name }} + RELEASE_TAG: ${{ github.ref_name }} + COMMIT_URL: https://gitea.cheppyjam.ru/${{ github.repository }}/commit # overrode: ${{ github.server_url }} + CHANGELOG_FILE: "changelog.md" + # ------------------------ + +jobs: + build-and-release: + runs-on: ubuntu-latest + permissions: + contents: write + + steps: + - name: Checkout code + uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Set up JDK + uses: actions/setup-java@v4 + with: + java-version: '25' + distribution: 'temurin' + cache: 'gradle' + + - name: Configure Outputs + id: config + run: | + VERSION=${RELEASE_TAG#v} + echo "version=$VERSION" >> $GITHUB_OUTPUT + + echo "RELEASE_BODY<> $GITHUB_ENV + echo "${{ github.event.release.body }}" >> $GITHUB_ENV + echo "EOF" >> $GITHUB_ENV + + - name: Generate Changelog + id: changelog + run: | + git fetch --prune --unshallow --tags || git fetch --tags + + echo "# Release Notes" > $CHANGELOG_FILE + echo "" >> $CHANGELOG_FILE + + if [ ! -z "$RELEASE_BODY" ]; then + echo "$RELEASE_BODY" >> $CHANGELOG_FILE + echo "" >> $CHANGELOG_FILE + fi + + echo "## Changelog" >> $CHANGELOG_FILE + echo "" >> $CHANGELOG_FILE + + PREVIOUS_TAG=$(git describe --tags --abbrev=0 HEAD~1 2>/dev/null || echo "") + + if [ -z "$PREVIOUS_TAG" ]; then + LOG_RANGE="${RELEASE_TAG}" + echo "This is the first release." >> $CHANGELOG_FILE + else + LOG_RANGE="${PREVIOUS_TAG}..${RELEASE_TAG}" + fi + + FORMAT_STR="* %s ([\`%h\`]($COMMIT_URL/%H))" + + FEATS=$(git log $LOG_RANGE --grep="^feat" --pretty=format:"$FORMAT_STR" || true) + if [ ! -z "$FEATS" ]; then + echo "### New Features" >> $CHANGELOG_FILE + echo "$FEATS" >> $CHANGELOG_FILE + echo "" >> $CHANGELOG_FILE + fi + + FIXES=$(git log $LOG_RANGE --grep="^fix" --pretty=format:"$FORMAT_STR" || true) + if [ ! -z "$FIXES" ]; then + echo "### Bug Fixes" >> $CHANGELOG_FILE + echo "$FIXES" >> $CHANGELOG_FILE + echo "" >> $CHANGELOG_FILE + fi + + MAINTENANCE=$(git log $LOG_RANGE --grep="^chore\|^refactor\|^perf\|^style" --pretty=format:"$FORMAT_STR" || true) + if [ ! -z "$MAINTENANCE" ]; then + echo "### Maintenance" >> $CHANGELOG_FILE + echo "$MAINTENANCE" >> $CHANGELOG_FILE + echo "" >> $CHANGELOG_FILE + fi + + - name: Make gradlew executable + run: chmod +x gradlew + + - name: Build with Gradle + run: ./gradlew build + + - name: Update Release + uses: softprops/action-gh-release@v2 + with: + tag_name: ${{ env.RELEASE_TAG }} + name: "${{ env.PROJECT_NAME }} ${{ env.RELEASE_TAG }}" + body_path: ${{ env.CHANGELOG_FILE }} + files: build/libs/*.jar + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b818f29 --- /dev/null +++ b/.gitignore @@ -0,0 +1,17 @@ +#region Visual Studio Code +.vscode/ +*.code-workspace +#endregion + +#region Java +bin/ +build/ +run/ +#endregion + +#region Gradle +.gradle/ + +!gradle-wrapper.jar +!gradle-wrapper.properties +#endregion \ No newline at end of file diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..53653a4 --- /dev/null +++ b/gradle.properties @@ -0,0 +1,6 @@ +group=org.axolotsh +version=1.0-SNAPSHOT + +org.gradle.configuration-cache=true +org.gradle.parallel=true +org.gradle.caching=true diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml new file mode 100644 index 0000000..078e6e7 --- /dev/null +++ b/gradle/libs.versions.toml @@ -0,0 +1,12 @@ +# This file was generated by the Gradle 'init' task. +# https://docs.gradle.org/current/userguide/version_catalogs.html#sec::toml-dependencies-format + +[versions] +commons-math3 = "3.6.1" +guava = "33.5.0-jre" +junit-jupiter = "6.0.1" + +[libraries] +commons-math3 = { module = "org.apache.commons:commons-math3", version.ref = "commons-math3" } +guava = { module = "com.google.guava:guava", version.ref = "guava" } +junit-jupiter = { module = "org.junit.jupiter:junit-jupiter", version.ref = "junit-jupiter" } diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..b1b8ef5 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..df6a6ad --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,9 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-9.5.1-bin.zip +networkTimeout=10000 +retries=0 +retryBackOffMs=500 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..b9bb139 --- /dev/null +++ b/gradlew @@ -0,0 +1,248 @@ +#!/bin/sh + +# +# Copyright © 2015 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/3d91ce3b8caaf77ad09f381f43615b715b53f72c/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\n' "$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 + + + +# 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" ) + + 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, 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" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# 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..24c62d5 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,82 @@ +@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, and ensure extensions are enabled +setlocal EnableExtensions + +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 + +"%COMSPEC%" /c exit 1 + +: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 + +"%COMSPEC%" /c exit 1 + +:execute +@rem Setup the command line + + + +@rem Execute Gradle +@rem endlocal doesn't take effect until after the line is parsed and variables are expanded +@rem which allows us to clear the local environment before executing the java command +endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel + +:exitWithErrorLevel +@rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts +"%COMSPEC%" /c exit %ERRORLEVEL% diff --git a/plugin-utils/build.gradle.kts b/plugin-utils/build.gradle.kts new file mode 100644 index 0000000..7a6bbd6 --- /dev/null +++ b/plugin-utils/build.gradle.kts @@ -0,0 +1,59 @@ +plugins { + id("java-library") + id("maven-publish") +} + +group = providers.gradleProperty("group").get() +version = providers.gradleProperty("version").get() + +repositories { + mavenCentral() + maven("https://repo.papermc.io/repository/maven-public/") + + maven { + name = "axolotsh-repository" + url = uri("https://maven.axolotsh.org/snapshots") + } +} + +dependencies { + compileOnly("org.projectlombok:lombok:1.18.46") + annotationProcessor("org.projectlombok:lombok:1.18.46") + + compileOnly("com.google.inject:guice:7.0.0") + + compileOnly("dev.jorel:commandapi-paper-core:11.2.0") + + compileOnly("io.papermc.paper:paper-api:26.1.2.build.+") +} + +java { + toolchain.languageVersion = JavaLanguageVersion.of(25) +} + +publishing { + publications { + create("mavenJava") { + from(components["java"]) + + groupId = project.group.toString() + artifactId = project.name + version = project.version.toString() + } + } + + repositories { + maven { + name = "Reposilite" + + val releasesUrl = "https://maven.axolotsh.org/releases" + val snapshotsUrl = "https://maven.axolotsh.org/snapshots" + url = uri(if (version.toString().endsWith("SNAPSHOT")) snapshotsUrl else releasesUrl) + + credentials { + username = providers.gradleProperty("reposiliteUser").orNull ?: "admin" + password = providers.gradleProperty("reposilitePassword").orNull ?: "password" + } + } + } +} diff --git a/plugin-utils/src/main/java/org/axolotsh/pluginutils/CommandUtils.java b/plugin-utils/src/main/java/org/axolotsh/pluginutils/CommandUtils.java new file mode 100644 index 0000000..7863d80 --- /dev/null +++ b/plugin-utils/src/main/java/org/axolotsh/pluginutils/CommandUtils.java @@ -0,0 +1,12 @@ +package org.axolotsh.pluginutils; + +import net.kyori.adventure.text.Component; + +import dev.jorel.commandapi.CommandAPIPaper; +import dev.jorel.commandapi.exceptions.WrapperCommandSyntaxException; + +public class CommandUtils { + public static WrapperCommandSyntaxException failCommand(Component component) { + return CommandAPIPaper.failWithAdventureComponent(component); + } +} diff --git a/plugin-utils/src/main/java/org/axolotsh/pluginutils/ComponentUtils.java b/plugin-utils/src/main/java/org/axolotsh/pluginutils/ComponentUtils.java new file mode 100644 index 0000000..b06ec9f --- /dev/null +++ b/plugin-utils/src/main/java/org/axolotsh/pluginutils/ComponentUtils.java @@ -0,0 +1,73 @@ +package org.axolotsh.pluginutils; + +import org.bukkit.OfflinePlayer; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import lombok.Getter; +import lombok.experimental.Accessors; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.minimessage.MiniMessage; +import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver; + +@Accessors(chain = true, fluent = true) +public class ComponentUtils { + @Getter + private static final MiniMessage mm = MiniMessage.miniMessage(); + + public static Component component(Object input) { + if (input instanceof Component component) + return component; + + if (input instanceof Player player) + return component(player); + if (input instanceof OfflinePlayer offlinePlayer) + return component(offlinePlayer); + + if (input instanceof ItemStack item) + return component(item); + if (input instanceof Entity entity) + return component(entity); + + return component(input.toString()); + } + + public static Component component(String miniMessage) { + return mm.deserialize(miniMessage); + } + + public static Component component(String miniMessage, TagResolver... tags) { + return mm.deserialize(miniMessage, tags); + } + + public static Component component(ItemStack item) { + return item.displayName().hoverEvent(item.asHoverEvent()); + } + + public static Component component(Entity entity) { + var name = entity.customName(); + if (name == null || name.equals(Component.empty())) + name = entity.name(); + return name.hoverEvent(entity.asHoverEvent()); + } + + public static Component component(Player player) { + return player.name().hoverEvent(player.asHoverEvent()); + } + + public static Component component(OfflinePlayer offlinePlayer) { + var player = offlinePlayer.getPlayer(); + if (player != null) + return component(player); + return component(offlinePlayer.getName()); + } + + public static String miniMessage(Object input) { + return miniMessage(component(input)); + } + + public static String miniMessage(Component component) { + return mm.serialize(component); + } +} diff --git a/plugin-utils/src/main/java/org/axolotsh/pluginutils/ConfigurationUtils.java b/plugin-utils/src/main/java/org/axolotsh/pluginutils/ConfigurationUtils.java new file mode 100644 index 0000000..5b461d1 --- /dev/null +++ b/plugin-utils/src/main/java/org/axolotsh/pluginutils/ConfigurationUtils.java @@ -0,0 +1,35 @@ +package org.axolotsh.pluginutils; + +import java.util.Map; + +import com.google.gson.Gson; +import com.google.gson.reflect.TypeToken; + +public class ConfigurationUtils { + private static final Gson GSON = new Gson(); + + public static Map serialize(T obj) { + return serialize(GSON, obj); + } + + public static Map serialize(Gson gson, T obj) { + if (obj == null) + return Map.of(); + + var json = gson.toJsonTree(obj); + return gson.fromJson(json, new TypeToken>() { + }.getType()); + } + + public static T deserialize(Map map, Class clazz) { + return deserialize(GSON, map, clazz); + } + + public static T deserialize(Gson gson, Map map, Class clazz) { + if (map == null || map.isEmpty()) + return null; + + var json = gson.toJsonTree(map); + return gson.fromJson(json, clazz); + } +} diff --git a/plugin-utils/src/main/java/org/axolotsh/pluginutils/InventoryUtils.java b/plugin-utils/src/main/java/org/axolotsh/pluginutils/InventoryUtils.java new file mode 100644 index 0000000..555d334 --- /dev/null +++ b/plugin-utils/src/main/java/org/axolotsh/pluginutils/InventoryUtils.java @@ -0,0 +1,20 @@ +package org.axolotsh.pluginutils; + +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.PlayerInventory; + +public class InventoryUtils { + public static ItemStack handItem(Player player) { + return handItem(player.getInventory()); + } + + public static ItemStack handItem(PlayerInventory inventory) { + var mainHand = inventory.getItemInMainHand(); + if (mainHand.getType() != Material.AIR) + return mainHand; + + return inventory.getItemInOffHand(); + } +} diff --git a/plugin-utils/src/main/java/org/axolotsh/pluginutils/configuration/LocalizationConfiguration.java b/plugin-utils/src/main/java/org/axolotsh/pluginutils/configuration/LocalizationConfiguration.java new file mode 100644 index 0000000..4bcaecf --- /dev/null +++ b/plugin-utils/src/main/java/org/axolotsh/pluginutils/configuration/LocalizationConfiguration.java @@ -0,0 +1,50 @@ +package org.axolotsh.pluginutils.configuration; + +import java.io.File; +import java.util.Locale; +import java.util.Map; + +import org.axolotsh.pluginutils.ConfigurationUtils; +import org.axolotsh.pluginutils.dependency_injection.entities.IConfiguration; +import org.bukkit.plugin.Plugin; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +@Accessors(chain = true, fluent = true) +@AllArgsConstructor +@NoArgsConstructor +@Builder(toBuilder = true) +public class LocalizationConfiguration implements IConfiguration { + @Builder.Default + private String directory = "localization"; + + public File directory(Plugin plugin) { + return directory(plugin.getDataFolder()); + } + + public File directory(File parent) { + return new File(parent, directory); + } + + @Builder.Default + private String defaultLocale = "en-US"; + + public Locale defaultLocale() { + return Locale.of(defaultLocale); + } + + public Map serialize() { + return ConfigurationUtils.serialize(this); + } + + public static LocalizationConfiguration deserialize(Map args) { + return ConfigurationUtils.deserialize(args, LocalizationConfiguration.class); + } + + public static LocalizationConfiguration defaultConfiguration() { + return builder().build(); + } +} \ No newline at end of file diff --git a/plugin-utils/src/main/java/org/axolotsh/pluginutils/dependency_injection/BaseJavaPlugin.java b/plugin-utils/src/main/java/org/axolotsh/pluginutils/dependency_injection/BaseJavaPlugin.java new file mode 100644 index 0000000..6308b0e --- /dev/null +++ b/plugin-utils/src/main/java/org/axolotsh/pluginutils/dependency_injection/BaseJavaPlugin.java @@ -0,0 +1,157 @@ +package org.axolotsh.pluginutils.dependency_injection; + +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +import org.axolotsh.pluginutils.dependency_injection.entities.ICommand; +import org.axolotsh.pluginutils.dependency_injection.entities.IConfiguration; +import org.axolotsh.pluginutils.dependency_injection.entities.ITask; +import org.bukkit.Server; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.serialization.ConfigurationSerialization; +import org.bukkit.event.Listener; +import org.bukkit.plugin.PluginManager; +import org.bukkit.plugin.java.JavaPlugin; +import org.bukkit.scheduler.BukkitScheduler; +import org.slf4j.Logger; + +import com.google.inject.Guice; +import com.google.inject.Inject; +import com.google.inject.Injector; + +public abstract class BaseJavaPlugin extends JavaPlugin { + @Inject + protected JavaPlugin javaPlugin; + + @Inject + protected Server server; + + @Inject + protected PluginManager pluginManager; + + @Inject + protected BukkitScheduler scheduler; + + @Inject + protected FileConfiguration fileConfiguration; + + @Inject + protected Set listeners; + + @Inject + protected Set commands; + + @Inject + protected Set configurations; + + @Inject + protected Set tasks; + + @Inject + protected Logger logger; + + protected Injector createInjector(JavaPluginModule module) { + var injector = Guice.createInjector(module); + + injector.injectMembers(this); + + return injector; + } + + protected void registerListeners() { + for (var listener : listeners) { + pluginManager.registerEvents(listener, this); + logger.trace("Event listener '{}' registered.", listener.getClass().getName()); + } + } + + protected void registerCommands() { + var subcommandsMap = mapSubcommands(); + + for (var command : commands) { + var clazzName = command.getClass().getName(); + + for (var permission : command.permissions()) { + pluginManager.addPermission(permission); + logger.trace("Command '{}' permission '{}' registered.", + clazzName, + permission.getName()); + } + + var commandInfo = command.command(); + var subcommands = subcommandsMap.getOrDefault(command, Collections.emptySet()); + for (var subcommand : subcommands) + commandInfo = commandInfo.withSubcommand(subcommand.command()); + + command.command().register(this); + logger.trace("Command '{}' registered.", clazzName); + } + } + + private Map> mapSubcommands() { + Map, ICommand> commandsByClazz = commands.stream() + .collect(Collectors.toMap( + x -> x.getClass(), + cmd -> cmd, + (existing, replacement) -> existing)); + + Map> result = new HashMap<>(); + for (var command : commands) + result.put(command, new HashSet<>()); + + for (var command : commands) { + var clazzName = command.getClass().getName(); + + command.parentCommand().ifPresent(parentClazz -> { + var parent = commandsByClazz.get(parentClazz); + + if (parent == null) { + logger.error("Parent command '{}' for command '{}' cannot be found.", + parentClazz.getName(), + clazzName); + } else + result.get(parent).add(command); + }); + } + + return result; + } + + protected void registerConfiguration() { + for (var configuration : configurations) { + var clazz = configuration.getClass(); + var clazzName = clazz.getName(); + + ConfigurationSerialization.registerClass(clazz); + logger.trace("Configuration '{}' registered.", clazzName); + } + } + + protected void registerTasks() { + for (var task : tasks) { + var taskClassName = task.getClass().getName(); + + var delay = task.delay(); + if (delay < 0) + throw new IllegalArgumentException( + String.format( + "Exception while registering '%s' task\nThe delay value cannot be less than 0. Found: %s", + taskClassName, delay)); + + var period = task.period(); + if (period <= 0) + throw new IllegalArgumentException( + String.format( + "Exception while registering '%s' task\nThe period value cannot be less or equal 0. Found: %s", + taskClassName, period)); + + scheduler.runTaskTimer(javaPlugin, task::run, delay, period); + logger.trace("Task '{}' registered.", taskClassName); + } + } +} diff --git a/plugin-utils/src/main/java/org/axolotsh/pluginutils/dependency_injection/JavaPluginModule.java b/plugin-utils/src/main/java/org/axolotsh/pluginutils/dependency_injection/JavaPluginModule.java new file mode 100644 index 0000000..3ef1c52 --- /dev/null +++ b/plugin-utils/src/main/java/org/axolotsh/pluginutils/dependency_injection/JavaPluginModule.java @@ -0,0 +1,55 @@ +package org.axolotsh.pluginutils.dependency_injection; + +import org.bukkit.Server; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.plugin.PluginManager; +import org.bukkit.plugin.java.JavaPlugin; +import org.bukkit.scheduler.BukkitScheduler; +import org.slf4j.Logger; + +import com.google.inject.Provides; +import com.google.inject.Singleton; + +public abstract class JavaPluginModule extends PluginModule { + protected final JavaPlugin javaPlugin; + + protected JavaPluginModule(JavaPlugin javaPlugin) { + this.javaPlugin = javaPlugin; + } + + @Provides + @Singleton + protected JavaPlugin provideJavaPlugin() { + return javaPlugin; + } + + @Provides + @Singleton + protected Server provideServer(JavaPlugin plugin) { + return plugin.getServer(); + } + + @Provides + @Singleton + protected PluginManager providePluginManager(Server server) { + return server.getPluginManager(); + } + + @Provides + @Singleton + protected BukkitScheduler provideScheduler(Server server) { + return server.getScheduler(); + } + + @Provides + @Singleton + protected FileConfiguration provideFileConfiguration(JavaPlugin plugin) { + return plugin.getConfig(); + } + + @Provides + @Singleton + protected Logger provideLogger(JavaPlugin plugin) { + return plugin.getSLF4JLogger(); + } +} diff --git a/plugin-utils/src/main/java/org/axolotsh/pluginutils/dependency_injection/PluginModule.java b/plugin-utils/src/main/java/org/axolotsh/pluginutils/dependency_injection/PluginModule.java new file mode 100644 index 0000000..5028874 --- /dev/null +++ b/plugin-utils/src/main/java/org/axolotsh/pluginutils/dependency_injection/PluginModule.java @@ -0,0 +1,27 @@ +package org.axolotsh.pluginutils.dependency_injection; + +import org.axolotsh.pluginutils.dependency_injection.entities.ICommand; +import org.axolotsh.pluginutils.dependency_injection.entities.IConfiguration; +import org.axolotsh.pluginutils.dependency_injection.entities.ITask; +import org.bukkit.event.Listener; + +import com.google.inject.AbstractModule; +import com.google.inject.multibindings.Multibinder; + +public abstract class PluginModule extends AbstractModule { + protected Multibinder createListenersMultibinder() { + return Multibinder.newSetBinder(binder(), Listener.class); + } + + protected Multibinder createCommandsMultibinder() { + return Multibinder.newSetBinder(binder(), ICommand.class); + } + + protected Multibinder createConfigurationMultibinder() { + return Multibinder.newSetBinder(binder(), IConfiguration.class); + } + + protected Multibinder createTasksMultibinder() { + return Multibinder.newSetBinder(binder(), ITask.class); + } +} diff --git a/plugin-utils/src/main/java/org/axolotsh/pluginutils/dependency_injection/entities/ICommand.java b/plugin-utils/src/main/java/org/axolotsh/pluginutils/dependency_injection/entities/ICommand.java new file mode 100644 index 0000000..0ce88c7 --- /dev/null +++ b/plugin-utils/src/main/java/org/axolotsh/pluginutils/dependency_injection/entities/ICommand.java @@ -0,0 +1,16 @@ +package org.axolotsh.pluginutils.dependency_injection.entities; + +import java.util.Collection; +import java.util.Optional; + +import org.bukkit.permissions.Permission; + +import dev.jorel.commandapi.CommandAPICommand; + +public interface ICommand { + public Collection permissions(); + + public CommandAPICommand command(); + + public Optional> parentCommand(); +} diff --git a/plugin-utils/src/main/java/org/axolotsh/pluginutils/dependency_injection/entities/IConfiguration.java b/plugin-utils/src/main/java/org/axolotsh/pluginutils/dependency_injection/entities/IConfiguration.java new file mode 100644 index 0000000..2cf47b1 --- /dev/null +++ b/plugin-utils/src/main/java/org/axolotsh/pluginutils/dependency_injection/entities/IConfiguration.java @@ -0,0 +1,6 @@ +package org.axolotsh.pluginutils.dependency_injection.entities; + +import org.bukkit.configuration.serialization.ConfigurationSerializable; + +public interface IConfiguration extends ConfigurationSerializable { +} diff --git a/plugin-utils/src/main/java/org/axolotsh/pluginutils/dependency_injection/entities/ITask.java b/plugin-utils/src/main/java/org/axolotsh/pluginutils/dependency_injection/entities/ITask.java new file mode 100644 index 0000000..5409c08 --- /dev/null +++ b/plugin-utils/src/main/java/org/axolotsh/pluginutils/dependency_injection/entities/ITask.java @@ -0,0 +1,9 @@ +package org.axolotsh.pluginutils.dependency_injection.entities; + +public interface ITask { + public long delay(); + + public long period(); + + public void run(); +} \ No newline at end of file diff --git a/plugin-utils/src/main/java/org/axolotsh/pluginutils/persistent_data_container/ContainerUtils.java b/plugin-utils/src/main/java/org/axolotsh/pluginutils/persistent_data_container/ContainerUtils.java new file mode 100644 index 0000000..376c22e --- /dev/null +++ b/plugin-utils/src/main/java/org/axolotsh/pluginutils/persistent_data_container/ContainerUtils.java @@ -0,0 +1,257 @@ +package org.axolotsh.pluginutils.persistent_data_container; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Optional; +import java.util.function.Function; +import java.util.function.Supplier; + +import org.axolotsh.pluginutils.persistent_data_container.exception.ContainerDataModificationUnsupportedException; +import org.bukkit.NamespacedKey; +import org.bukkit.inventory.ItemStack; +import org.bukkit.persistence.ListPersistentDataType; +import org.bukkit.persistence.PersistentDataContainer; +import org.bukkit.persistence.PersistentDataHolder; +import org.bukkit.persistence.PersistentDataType; + +import io.papermc.paper.persistence.PersistentDataContainerView; +import io.papermc.paper.persistence.PersistentDataViewHolder; + +public class ContainerUtils { + // #region Get + public static Optional get( + PersistentDataViewHolder holder, + NamespacedKey key, PersistentDataType dataType) { + return get(holder.getPersistentDataContainer(), key, dataType); + } + + public static Optional get( + PersistentDataContainerView pdc, + NamespacedKey key, PersistentDataType dataType) { + if (!pdc.has(key)) + return Optional.empty(); + + var result = pdc.get(key, dataType); + return Optional.ofNullable(result); + } + + // #region Collection + public static > Collection getCollection( + PersistentDataViewHolder holder, + NamespacedKey key, PersistentDataType dataType) { + return getCollection(holder.getPersistentDataContainer(), key, dataType); + } + + public static > Collection getCollection( + PersistentDataViewHolder holder, + NamespacedKey key, PersistentDataType dataType, + Supplier collectionFactory) { + return getCollection(holder.getPersistentDataContainer(), key, dataType, collectionFactory); + } + + public static > Collection getCollection( + PersistentDataContainerView pdc, + NamespacedKey key, PersistentDataType dataType) { + return getCollection(pdc, key, dataType, ArrayList::new); + } + + public static > Collection getCollection( + PersistentDataContainerView pdc, + NamespacedKey key, PersistentDataType dataType, + Supplier collectionFactory) { + var result = collectionFactory.get(); + if (!pdc.has(key)) + return result; + + Collection list = pdc.get(key, listType(dataType)); + if (list != null) + result.addAll(list); + + return result; + } + // #endregion + + // #region Map + public static Map getMap( + PersistentDataViewHolder holder, + NamespacedKey key, PersistentDataType dataType, + Function> entryMapper) { + return getMap(holder.getPersistentDataContainer(), key, dataType, entryMapper); + } + + public static > Map getMap( + PersistentDataViewHolder holder, + NamespacedKey key, PersistentDataType dataType, + Function> entryMapper, Supplier mapFactory) { + return getMap(holder.getPersistentDataContainer(), key, dataType, entryMapper, mapFactory); + } + + public static Map getMap( + PersistentDataContainerView pdc, + NamespacedKey key, PersistentDataType dataType, + Function> entryMapper) { + return getMap(pdc, key, dataType, entryMapper, HashMap::new); + } + + public static > Map getMap( + PersistentDataContainerView pdc, + NamespacedKey key, PersistentDataType dataType, + Function> entryMapper, Supplier mapFactory) { + var list = getCollection(pdc, key, dataType); + + Map result = mapFactory.get(); + list.forEach(entry -> { + var mapEntry = entryMapper.apply(entry); + result.put(mapEntry.getKey(), + mapEntry.getValue()); + }); + + return result; + } + // #endregion + + // #endregion + + // #region Set + public static void set( + PersistentDataViewHolder viewHolder, + NamespacedKey key, PersistentDataType dataType, + T value) { + if (viewHolder instanceof PersistentDataHolder holder) + set(holder, key, dataType, value); + else if (viewHolder instanceof ItemStack item) + set(item, key, dataType, value); + else + throw new ContainerDataModificationUnsupportedException(); + } + + public static void set( + PersistentDataHolder holder, + NamespacedKey key, PersistentDataType dataType, + T value) { + set(holder.getPersistentDataContainer(), key, dataType, value); + } + + public static void set( + ItemStack item, + NamespacedKey key, PersistentDataType dataType, + T value) { + item.editPersistentDataContainer(pdc -> set(pdc, key, dataType, value)); + } + + public static void set( + PersistentDataContainer pdc, + NamespacedKey key, PersistentDataType dataType, + T value) { + if (value == null) + pdc.remove(key); + else + pdc.set(key, dataType, value); + } + + // #region Collection + public static void setCollection( + PersistentDataViewHolder viewHolder, + NamespacedKey key, PersistentDataType dataType, + Collection collection) { + if (viewHolder instanceof PersistentDataHolder holder) + setCollection(holder, key, dataType, collection); + else if (viewHolder instanceof ItemStack item) + setCollection(item, key, dataType, collection); + else + throw new ContainerDataModificationUnsupportedException(); + } + + public static void setCollection( + PersistentDataHolder holder, + NamespacedKey key, PersistentDataType dataType, + Collection collection) { + setCollection(holder.getPersistentDataContainer(), key, dataType, collection); + } + + public static void setCollection( + ItemStack item, + NamespacedKey key, PersistentDataType dataType, + Collection collection) { + item.editPersistentDataContainer(pdc -> setCollection(pdc, key, dataType, collection)); + } + + public static void setCollection( + PersistentDataContainer pdc, + NamespacedKey key, PersistentDataType dataType, + Collection collection) { + if (collection == null || collection.isEmpty()) + pdc.remove(key); + else + pdc.set(key, listType(dataType), List.copyOf(collection)); + } + // #endregion + + // #region Map + public static void setMap( + PersistentDataViewHolder viewHolder, + NamespacedKey key, PersistentDataType dataType, + Map map) { + if (viewHolder instanceof PersistentDataHolder holder) + setMap(holder, key, dataType, map); + else if (viewHolder instanceof ItemStack item) + setMap(item, key, dataType, map); + else + throw new ContainerDataModificationUnsupportedException(); + } + + public static void setMap( + PersistentDataHolder holder, + NamespacedKey key, PersistentDataType dataType, + Map map) { + setMap(holder.getPersistentDataContainer(), key, dataType, map); + } + + public static void setMap( + ItemStack item, + NamespacedKey key, PersistentDataType dataType, + Map map) { + item.editPersistentDataContainer(pdc -> setMap(pdc, key, dataType, map)); + } + + public static void setMap( + PersistentDataContainer pdc, + NamespacedKey key, PersistentDataType dataType, + Map map) { + setCollection(pdc, key, dataType, map.values()); + } + // #endregion + + // #endregion + + // #region Remove + public static void remove(PersistentDataViewHolder viewHolder, NamespacedKey key) { + if (viewHolder instanceof PersistentDataHolder holder) + remove(holder, key); + else if (viewHolder instanceof ItemStack item) + remove(item, key); + else + throw new ContainerDataModificationUnsupportedException(); + } + + public static void remove(PersistentDataHolder holder, NamespacedKey key) { + remove(holder.getPersistentDataContainer(), key); + } + + public static void remove(ItemStack item, NamespacedKey key) { + item.editPersistentDataContainer(pdc -> remove(pdc, key)); + } + + public static void remove(PersistentDataContainer pdc, NamespacedKey key) { + pdc.remove(key); + } + // #endregion + + public static ListPersistentDataType listType(PersistentDataType dataType) { + return PersistentDataType.LIST.listTypeFrom(dataType); + } +} diff --git a/plugin-utils/src/main/java/org/axolotsh/pluginutils/persistent_data_container/PersistentCollection.java b/plugin-utils/src/main/java/org/axolotsh/pluginutils/persistent_data_container/PersistentCollection.java new file mode 100644 index 0000000..ec8b251 --- /dev/null +++ b/plugin-utils/src/main/java/org/axolotsh/pluginutils/persistent_data_container/PersistentCollection.java @@ -0,0 +1,53 @@ +package org.axolotsh.pluginutils.persistent_data_container; + +import java.util.Collection; +import java.util.function.Consumer; +import java.util.function.Supplier; + +import org.axolotsh.pluginutils.wrappers.CollectionWrapper; +import org.bukkit.NamespacedKey; +import org.bukkit.persistence.PersistentDataType; + +import io.papermc.paper.persistence.PersistentDataViewHolder; +import lombok.AllArgsConstructor; + +@AllArgsConstructor +public class PersistentCollection { + protected final NamespacedKey key; + protected final PersistentDataType dataType; + protected final PersistentDataViewHolder holder; + protected final Supplier> collectionFactory; + + public Collection get() { + return ContainerUtils.getCollection(holder, key, dataType, collectionFactory); + } + + public PersistentCollection set(Collection collection) { + ContainerUtils.setCollection(holder, key, dataType, collection); + + return this; + } + + public PersistentCollection edit(Consumer action) { + try (var transaction = edit()) { + action.accept(transaction); + } + + return this; + } + + public Transaction edit() { + return new Transaction(get()); + } + + public class Transaction extends CollectionWrapper implements AutoCloseable { + protected Transaction(Collection collection) { + super(collection); + } + + @Override + public void close() { + set(innerCollection); + } + } +} \ No newline at end of file diff --git a/plugin-utils/src/main/java/org/axolotsh/pluginutils/persistent_data_container/PersistentEntry.java b/plugin-utils/src/main/java/org/axolotsh/pluginutils/persistent_data_container/PersistentEntry.java new file mode 100644 index 0000000..d9c3901 --- /dev/null +++ b/plugin-utils/src/main/java/org/axolotsh/pluginutils/persistent_data_container/PersistentEntry.java @@ -0,0 +1,34 @@ +package org.axolotsh.pluginutils.persistent_data_container; + +import java.util.Optional; +import java.util.function.Function; + +import org.bukkit.NamespacedKey; +import org.bukkit.persistence.PersistentDataType; + +import io.papermc.paper.persistence.PersistentDataViewHolder; +import lombok.AllArgsConstructor; + +@AllArgsConstructor +public class PersistentEntry { + protected NamespacedKey key; + protected PersistentDataType dataType; + + protected PersistentDataViewHolder holder; + + public Optional get() { + return ContainerUtils.get(holder, key, dataType); + } + + public PersistentEntry set(T value) { + ContainerUtils.set(holder, key, dataType, value); + + return this; + } + + public PersistentEntry edit(Function, T> action) { + var result = action.apply(get()); + set(result); + return this; + } +} diff --git a/plugin-utils/src/main/java/org/axolotsh/pluginutils/persistent_data_container/PersistentMap.java b/plugin-utils/src/main/java/org/axolotsh/pluginutils/persistent_data_container/PersistentMap.java new file mode 100644 index 0000000..69cdbd3 --- /dev/null +++ b/plugin-utils/src/main/java/org/axolotsh/pluginutils/persistent_data_container/PersistentMap.java @@ -0,0 +1,60 @@ +package org.axolotsh.pluginutils.persistent_data_container; + +import java.util.HashMap; +import java.util.Map; +import java.util.Map.Entry; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.function.Supplier; + +import org.axolotsh.pluginutils.wrappers.MapWrapper; +import org.bukkit.NamespacedKey; +import org.bukkit.persistence.PersistentDataType; + +import io.papermc.paper.persistence.PersistentDataViewHolder; +import lombok.AllArgsConstructor; + +@AllArgsConstructor +public class PersistentMap { + protected NamespacedKey key; + protected PersistentDataType dataType; + + protected PersistentDataViewHolder holder; + + protected Function> entryMapper; + + protected Supplier> mapFactory = HashMap::new; + + public Map get() { + return ContainerUtils.getMap(holder, key, dataType, entryMapper, mapFactory); + } + + public PersistentMap set(Map map) { + ContainerUtils.setMap(holder, key, dataType, map); + + return this; + } + + public PersistentMap edit(Consumer action) { + try (var transaction = edit()) { + action.accept(transaction); + } + + return this; + } + + public Transaction edit() { + return new Transaction(get()); + } + + private class Transaction extends MapWrapper implements AutoCloseable { + protected Transaction(Map map) { + super(map); + } + + @Override + public void close() { + set(innerMap); + } + } +} diff --git a/plugin-utils/src/main/java/org/axolotsh/pluginutils/persistent_data_container/exception/ContainerDataModificationUnsupportedException.java b/plugin-utils/src/main/java/org/axolotsh/pluginutils/persistent_data_container/exception/ContainerDataModificationUnsupportedException.java new file mode 100644 index 0000000..9916fde --- /dev/null +++ b/plugin-utils/src/main/java/org/axolotsh/pluginutils/persistent_data_container/exception/ContainerDataModificationUnsupportedException.java @@ -0,0 +1,7 @@ +package org.axolotsh.pluginutils.persistent_data_container.exception; + +public class ContainerDataModificationUnsupportedException extends UnsupportedOperationException { + public ContainerDataModificationUnsupportedException() { + super("This holder does not support data modification."); + } +} diff --git a/plugin-utils/src/main/java/org/axolotsh/pluginutils/wrappers/CollectionWrapper.java b/plugin-utils/src/main/java/org/axolotsh/pluginutils/wrappers/CollectionWrapper.java new file mode 100644 index 0000000..dfa9d39 --- /dev/null +++ b/plugin-utils/src/main/java/org/axolotsh/pluginutils/wrappers/CollectionWrapper.java @@ -0,0 +1,87 @@ +package org.axolotsh.pluginutils.wrappers; + +import java.util.Collection; +import java.util.Collections; +import java.util.Iterator; + +public abstract class CollectionWrapper implements Collection { + protected final Collection innerCollection; + + public Collection innerCollection() { + return Collections.unmodifiableCollection(innerCollection); + } + + protected CollectionWrapper(Collection innerCollection) { + this.innerCollection = innerCollection; + } + + @Override + public boolean add(C arg0) { + return innerCollection.add(arg0); + } + + @Override + public boolean addAll(Collection c) { + return innerCollection.addAll(c); + } + + @Override + public void clear() { + innerCollection.clear(); + } + + @Override + public boolean contains(Object o) { + return innerCollection.contains(o); + } + + @Override + public boolean containsAll(Collection c) { + return innerCollection.containsAll(c); + } + + @Override + public boolean isEmpty() { + return innerCollection.isEmpty(); + } + + @Override + public Iterator iterator() { + return innerCollection.iterator(); + } + + @Override + public boolean remove(Object o) { + return innerCollection.remove(o); + } + + @Override + public boolean removeAll(Collection c) { + return innerCollection.removeAll(c); + } + + @Override + public boolean retainAll(Collection c) { + return innerCollection.retainAll(c); + } + + @Override + public int size() { + return innerCollection.size(); + } + + @Override + public Object[] toArray() { + return innerCollection.toArray(); + } + + @Override + public T[] toArray(T[] arg0) { + return innerCollection.toArray(arg0); + } + + @Override + public String toString() { + return innerCollection.toString(); + } +} diff --git a/plugin-utils/src/main/java/org/axolotsh/pluginutils/wrappers/MapWrapper.java b/plugin-utils/src/main/java/org/axolotsh/pluginutils/wrappers/MapWrapper.java new file mode 100644 index 0000000..27bafe1 --- /dev/null +++ b/plugin-utils/src/main/java/org/axolotsh/pluginutils/wrappers/MapWrapper.java @@ -0,0 +1,78 @@ +package org.axolotsh.pluginutils.wrappers; + +import java.util.Collection; +import java.util.Collections; +import java.util.Map; +import java.util.Set; + +public class MapWrapper implements Map { + protected final Map innerMap; + + public Map innerMap() { + return Collections.unmodifiableMap(innerMap); + } + + protected MapWrapper(Map innerMap) { + this.innerMap = innerMap; + } + + @Override + public void clear() { + innerMap.clear(); + } + + @Override + public boolean containsKey(Object key) { + return innerMap.containsKey(key); + } + + @Override + public boolean containsValue(Object value) { + return innerMap.containsValue(value); + } + + @Override + public Set> entrySet() { + return innerMap.entrySet(); + } + + @Override + public V get(Object key) { + return innerMap.get(key); + } + + @Override + public boolean isEmpty() { + return innerMap.isEmpty(); + } + + @Override + public Set keySet() { + return innerMap.keySet(); + } + + @Override + public V put(K arg0, V arg1) { + return innerMap.put(arg0, arg1); + } + + @Override + public void putAll(Map m) { + innerMap.putAll(m); + } + + @Override + public V remove(Object key) { + return innerMap.remove(key); + } + + @Override + public int size() { + return innerMap.size(); + } + + @Override + public Collection values() { + return innerMap.values(); + } +} diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 0000000..f30d6a8 --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1,2 @@ +rootProject.name = "PluginUtils" +include("plugin-utils")