Compare commits

..

29 commits

Author SHA1 Message Date
daca492c5e Bump to 2.1 on plugin.yml. 2026-05-30 11:06:58 -03:00
e19d169425 Bump to 2.1, deprecated LoggerProvider#error, change version mathcing to return 1.21 on any version that is not b1.7.3, remove leftover classes. 2026-05-30 11:06:14 -03:00
b227ef18e2 Merge remote-tracking branch 'origin/main' 2026-05-26 20:01:51 -03:00
f0e9682a9f Bump to 2.1 2026-05-26 20:01:40 -03:00
7a03172d57 Bump to 2.1 2026-05-26 19:56:47 -03:00
6ef06b1c4d Fix bug in Configuration inialization and Configuration#load(String content) that was passing content as file path on 1.21 implementation. 2026-05-26 19:55:58 -03:00
632993678e Make file provider accept plugin to get correct resource file 2026-05-25 21:45:33 -03:00
26d18e2552 Add file provider with support for saving resource to disk 2026-05-25 19:15:30 -03:00
df450e1f9b Fix versioning not working on b1.7.3 2026-05-25 18:27:54 -03:00
5b3f7a4e56 Merge remote-tracking branch 'origin/main' 2026-05-24 14:24:56 -03:00
2956f2c04b Merge remote-tracking branch 'origin/main' 2026-05-24 14:24:50 -03:00
8db4c560db Merge remote-tracking branch 'origin/main' 2026-05-24 14:22:43 -03:00
b368118c3b Merge remote-tracking branch 'origin/main' 2026-05-24 14:02:19 -03:00
467524bf5d Merge remote-tracking branch 'origin/main' 2026-05-24 13:30:29 -03:00
a476c790de Merge remote-tracking branch 'origin/main' 2026-05-24 13:30:21 -03:00
27a93cdb46 Merge remote-tracking branch 'origin/main' 2026-05-23 22:39:53 -03:00
8272a98e9c Merge remote-tracking branch 'origin/main' 2026-05-23 22:39:46 -03:00
0484769372 Merge remote-tracking branch 'origin/main' 2026-05-23 22:02:33 -03:00
425599ff62 Fix VersionMatcher not parsing version string correctly 2026-05-23 22:02:20 -03:00
2ef8b2d1be Fix VersionMatcher not parsing version string correctly 2026-05-23 21:49:38 -03:00
0b753d6a4e Finish factory implementation 2026-05-23 21:41:17 -03:00
eec7b2fcbb Remove reflection and add VersionedService to provide multiple versions support 2026-05-23 17:59:40 -03:00
811b54517a Safer classpath building in ImplementationRegistry 2026-05-23 15:12:13 -03:00
623e581623 Fix ImplementationRegistry 2026-05-23 15:09:19 -03:00
c36d001954 Convert to an actual library 2026-05-23 14:36:04 -03:00
2e0745d505 Add duplicatesStrategy to ProcessResources 2026-05-23 13:25:11 -03:00
dbd8c6a83e Overall refactor and add reflection. 2026-05-23 12:23:40 -03:00
134eb44f74 Converted project to Gradle. 2025-12-15 23:53:37 -03:00
b317749ed0 Reworked classe. 2025-03-19 06:35:42 -03:00
45 changed files with 1710 additions and 191 deletions

12
.gitattributes vendored Normal file
View file

@ -0,0 +1,12 @@
#
# https://help.github.com/articles/dealing-with-line-endings/
#
# Linux start script should use lf
/gradlew text eol=lf
# These are Windows script files and should use crlf
*.bat text eol=crlf
# Binary files should be left untouched
*.jar binary

16
.gitignore vendored Normal file
View file

@ -0,0 +1,16 @@
bin/
libs/
.idea/
.gradle/
build/
out/
# Ignore Gradle project-specific cache directory
.gradle
# Ignore Gradle build output directory
build
run/
*.log

43
app/build.gradle.kts Normal file
View file

@ -0,0 +1,43 @@
/*
* This file was generated by the Gradle 'init' task.
*
* This generated file contains a sample Java application project to get you started.
* For more details on building Java & JVM projects, please refer to https://docs.gradle.org/9.2.1/userguide/building_java_projects.html in the Gradle documentation.
*/
plugins {
// Apply the application plugin to add support for building a CLI application in Java.
application
}
repositories {
// Use Maven Central for resolving dependencies.
mavenCentral()
}
dependencies {
// Use JUnit Jupiter for testing.
testImplementation(libs.junit.jupiter)
testRuntimeOnly("org.junit.platform:junit-platform-launcher")
// This dependency is used by the application.
implementation(libs.guava)
}
// Apply a specific Java toolchain to ease working on different environments.
java {
toolchain {
languageVersion = JavaLanguageVersion.of(21)
}
}
application {
// Define the main class for the application.
mainClass = "org.example.App"
}
tasks.named<Test>("test") {
// Use JUnit Platform for unit tests.
useJUnitPlatform()
}

View file

@ -0,0 +1,14 @@
/*
* This source file was generated by the Gradle 'init' task
*/
package org.example;
public class App {
public String getGreeting() {
return "Hello World!";
}
public static void main(String[] args) {
System.out.println(new App().getGreeting());
}
}

View file

@ -0,0 +1,129 @@
package org.adrianvictor.lib;
import org.adrianvictor.lib.versioning.DefaultVersionedServiceFactory;
import org.adrianvictor.lib.versioning.VersionMatcher;
import org.adrianvictor.lib.versioning.VersionedServiceFactory;
import org.adrianvictor.lib.versioning.VersionedServiceRegistrar;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
// Define dummy interfaces for testing
interface TestService {}
class TestServiceB1_7_3 implements TestService {}
class TestServiceR1_21 implements TestService {}
// Dummy registrar for testing
class DummyRegistrarB1_7_3 implements VersionedServiceRegistrar {
@Override
public void register(VersionedServiceFactory factory) {
factory.register(TestService.class, "b1_7_3", TestServiceB1_7_3::new);
}
}
class DummyRegistrarR1_21 implements VersionedServiceRegistrar {
@Override
public void register(VersionedServiceFactory factory) {
factory.register(TestService.class, "r1_1", TestServiceR1_21::new); // Registers for r1_1 compat
factory.register(TestService.class, "r1_16_5", TestServiceR1_21::new); // Registers for r1_16_5 compat
factory.register(TestService.class, "r1_21", TestServiceR1_21::new); // Registers for r1_21
}
}
public class DefaultVersionedServiceFactoryTest {
private VersionMatcher mockVersionMatcher;
private DefaultVersionedServiceFactory factory;
@BeforeEach
void setUp() {
mockVersionMatcher = mock(VersionMatcher.class);
factory = new DefaultVersionedServiceFactory(mockVersionMatcher);
}
@Test
void testServiceRegistrationAndRetrievalForB1_7_3() {
// Mock VersionMatcher to return b1_7_3 suffix
when(mockVersionMatcher.getServerVersion()).thenReturn("1.7.3");
when(mockVersionMatcher.getClassSuffixes(eq("1.7.3"))).thenReturn(List.of("b1_7_3"));
// Register the dummy service for b1_7_3
new DummyRegistrarB1_7_3().register(factory);
// Retrieve the service
TestService service = factory.getService(TestService.class);
// Assert that the correct version is returned
assertNotNull(service);
assertTrue(service instanceof TestServiceB1_7_3);
}
@Test
void testServiceRegistrationAndRetrievalForR1_1() {
// Mock VersionMatcher to return r1_1 suffix for a 1.10.2 server
when(mockVersionMatcher.getServerVersion()).thenReturn("1.10.2");
when(mockVersionMatcher.getClassSuffixes(eq("1.10.2"))).thenReturn(List.of("r1_1"));
// Register the dummy service for R1_21 (which covers r1_1 compat)
new DummyRegistrarR1_21().register(factory);
// Retrieve the service
TestService service = factory.getService(TestService.class);
// Assert that the correct compatible version is returned
assertNotNull(service);
assertTrue(service instanceof TestServiceR1_21);
}
@Test
void testServiceFallbackCompatibility() {
// Mock a 1.21 server which supports r1_21, r1_16_5, and r1_1
when(mockVersionMatcher.getServerVersion()).thenReturn("1.21.0");
when(mockVersionMatcher.getClassSuffixes(eq("1.21.0"))).thenReturn(List.of("r1_21", "r1_16_5", "r1_1"));
// Register ONLY for r1_1
factory.register(TestService.class, "r1_1", TestServiceR1_21::new);
// Retrieve the service - should fall back to r1_1
TestService service = factory.getService(TestService.class);
assertNotNull(service);
assertTrue(service instanceof TestServiceR1_21);
}
@Test
void testServiceRegistrationAndRetrievalForR1_21() {
// Mock VersionMatcher to return r1_21 suffix
when(mockVersionMatcher.getServerVersion()).thenReturn("1.21.0");
when(mockVersionMatcher.getClassSuffixes(eq("1.21.0"))).thenReturn(List.of("r1_21", "r1_16_5", "r1_1"));
// Register the dummy service for r1_21
new DummyRegistrarR1_21().register(factory);
// Retrieve the service
TestService service = factory.getService(TestService.class);
// Assert that the correct version is returned
assertNotNull(service);
assertTrue(service instanceof TestServiceR1_21);
}
@Test
void testNoServiceRegisteredThrowsException() {
// Mock VersionMatcher to return an unknown suffix
when(mockVersionMatcher.getServerVersion()).thenReturn("unknown");
when(mockVersionMatcher.getClassSuffixes(anyString())).thenReturn(List.of("unknown_version"));
// Attempt to retrieve a service without any registration
IllegalStateException exception = assertThrows(IllegalStateException.class, () ->
factory.getService(TestService.class)
);
assertTrue(exception.getMessage().contains("No service registered for type"));
}
}

View file

@ -0,0 +1,14 @@
/*
* This source file was generated by the Gradle 'init' task
*/
package org.example;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class AppTest {
@Test void appHasAGreeting() {
App classUnderTest = new App();
assertNotNull(classUnderTest.getGreeting(), "app should have a greeting");
}
}

185
build.gradle.kts Normal file
View file

@ -0,0 +1,185 @@
plugins {
java
id("xyz.jpenilla.run-paper") version "3.0.1"
}
group = "org.adrianvictor"
version = "2.1.1"
val buildEnv = System.getenv("BUILD_CHANNEL")
?: if (System.getenv("JITPACK") != null) "jitpack" else "local"
repositories {
mavenCentral()
maven("https://repo.papermc.io/repository/maven-public/")
}
/* ----------------------------------------- */
/* SUPPORTED VERSIONS */
/* ----------------------------------------- */
val mcVersions = listOf(
"b1_7_3",
"r1_21"
)
/* ----------------------------------------- */
/* CREATE SOURCE SET PER VERSION */
/* ----------------------------------------- */
//tasks.withType<ProcessResources> {
// inputs.property("version", project.version)
//
// filesMatching("plugin.yml") {
// expand("version" to project.version)
// }
//}
mcVersions.forEach { ver ->
val ss = sourceSets.create(ver) {
java.srcDir("src/$ver/java")
resources.setSrcDirs(
listOf(
"src/$ver/resources",
"src/main/resources"
)
)
compileClasspath += sourceSets["main"].output
runtimeClasspath += output + compileClasspath
}
if (ver == "r1_21") {
configurations[ss.compileOnlyConfigurationName]
.extendsFrom(configurations["compileOnly"])
}
}
/* ----------------------------------------- */
/* DEPENDENCIES */
/* ----------------------------------------- */
dependencies {
add("compileOnly", "io.papermc.paper:paper-api:1.21.1-R0.1-SNAPSHOT")
add("r1_21CompileOnly", "io.papermc.paper:paper-api:1.21.1-R0.1-SNAPSHOT")
add("b1_7_3CompileOnly", files("libs/craftbukkit-1060.jar"))
}
/* ----------------------------------------- */
/* BUILD TASKS */
/* ----------------------------------------- */
mcVersions.forEach { ver ->
tasks.register<Jar>("jar${ver.replace(".", "_").replace("-", "_").replace("/", "_").replaceFirstChar { it.uppercase() }}") {
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
from(sourceSets["main"].output)
from(sourceSets[ver].output)
archiveClassifier.set(ver)
manifest {
attributes(
"TLib-Impl-Version" to ver,
"TLib-Environment" to buildEnv
)
}
}
}
val prepareServiceFiles = tasks.register("prepareServiceFiles") {
val outputDir = layout.buildDirectory.dir("generated/service-files")
val serviceFile = "META-INF/services/org.adrianvictor.lib.versioning.VersionedServiceRegistrar"
val inputFiles = mcVersions.map { ver -> file("src/$ver/resources/$serviceFile") }.filter { it.exists() }
inputs.files(inputFiles)
outputs.dir(outputDir)
doLast {
val registrars = mutableSetOf<String>()
inputFiles.forEach { file ->
if (file.exists()) {
file.readLines().forEach { line ->
val trimmed = line.trim()
if (trimmed.isNotEmpty()) {
registrars.add(trimmed)
}
}
}
}
val mergedFile = outputDir.get().file(serviceFile).asFile
mergedFile.parentFile.mkdirs()
mergedFile.writeText(registrars.joinToString("\n") + "\n")
println("Merged service file content: \n${registrars.joinToString("\n")}")
}
}
tasks.named<Jar>("jar") {
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
from(sourceSets["main"].output)
mcVersions.forEach { ver ->
from(sourceSets[ver].output) {
exclude("META-INF/services/org.adrianvictor.lib.versioning.VersionedServiceRegistrar")
}
}
from(prepareServiceFiles)
manifest {
attributes(
"Implemented-Versions" to mcVersions.joinToString(",")
)
}
}
tasks.register<Jar>("bundleAll") {
dependsOn("jar")
from(sourceSets["main"].output)
mcVersions.forEach { ver ->
from(sourceSets[ver].output) {
exclude("META-INF/services/org.adrianvictor.lib.versioning.VersionedServiceRegistrar")
}
}
from(prepareServiceFiles)
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
archiveClassifier.set("all-implementations")
archiveVersion.set(project.version.toString())
manifest {
attributes(
"Implemented-Versions" to mcVersions.joinToString(",")
)
}
}
tasks.withType<ProcessResources>().configureEach {
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
}
tasks.withType<JavaCompile>().configureEach {
options.encoding = "UTF-8"
}
/* ----------------------------------------- */
/* JAVA SETTINGS */
/* ----------------------------------------- */
java {
toolchain.languageVersion.set(JavaLanguageVersion.of(21))
}
tasks.withType<JavaCompile> {
options.encoding = "UTF-8"
}
/* ----------------------------------------- */
/* RUN SETTINGS */
/* ----------------------------------------- */
tasks.runServer {
minecraftVersion("1.21.11")
pluginJars.setFrom(tasks.named("bundleAll"))
}

5
gradle.properties Normal file
View file

@ -0,0 +1,5 @@
# This file was generated by the Gradle 'init' task.
# https://docs.gradle.org/current/userguide/build_environment.html#sec:gradle_configuration_properties
org.gradle.configuration-cache=true

10
gradle/libs.versions.toml Normal file
View file

@ -0,0 +1,10 @@
# This file was generated by the Gradle 'init' task.
# https://docs.gradle.org/current/userguide/platforms.html#sub::toml-dependencies-format
[versions]
guava = "33.4.6-jre"
junit-jupiter = "5.12.1"
[libraries]
guava = { module = "com.google.guava:guava", version.ref = "guava" }
junit-jupiter = { module = "org.junit.jupiter:junit-jupiter", version.ref = "junit-jupiter" }

BIN
gradle/wrapper/gradle-wrapper.jar vendored Normal file

Binary file not shown.

View file

@ -0,0 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-9.2.1-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

248
gradlew vendored Executable file
View file

@ -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/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\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" "$@"

93
gradlew.bat vendored Normal file
View file

@ -0,0 +1,93 @@
@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
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
: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

View file

@ -1,7 +0,0 @@
author: tenkuma
database: false
main: gd.rf.adrianvictor.lib.Main
name: tenkumaLib
startup: startup
url: https://adrianvictor.rf.gd
version: '1.0'

13
settings.gradle.kts Normal file
View file

@ -0,0 +1,13 @@
/*
* This file was generated by the Gradle 'init' task.
*
* The settings file is used to specify which projects to include in your build.
* For more detailed information on multi-project builds, please refer to https://docs.gradle.org/9.2.1/userguide/multi_project_builds.html in the Gradle documentation.
*/
plugins {
id("org.gradle.toolchains.foojay-resolver-convention") version "1.0.0"
}
rootProject.name = "tenkumaLib"

View file

@ -0,0 +1,36 @@
package org.adrianvictor.lib.impl.b1_7_3;
import org.adrianvictor.lib.file.provider.FileProvider;
import org.adrianvictor.lib.impl.b1_7_3.file.File;
import org.adrianvictor.lib.impl.b1_7_3.logging.Logger;
import org.adrianvictor.lib.versioning.VersionedServiceFactory;
import org.adrianvictor.lib.versioning.VersionedServiceRegistrar;
import org.adrianvictor.lib.configuration.provider.ConfigurationProvider;
import org.adrianvictor.lib.impl.b1_7_3.configuration.Configuration;
import org.adrianvictor.lib.text.provider.TextColorProvider;
import org.adrianvictor.lib.impl.b1_7_3.text.TextColor;
import org.adrianvictor.lib.logging.provider.LoggerProvider;
import org.bukkit.plugin.java.JavaPlugin;
public class B1_7_3Registrar implements VersionedServiceRegistrar {
private JavaPlugin plugin;
@Override
public void setPlugin(JavaPlugin plugin) {
this.plugin = plugin;
}
@Override
public JavaPlugin getPlugin() {
return plugin;
}
@Override
public void register(VersionedServiceFactory factory) {
Logger.setPlugin(this.plugin);
factory.register(ConfigurationProvider.class, "b1_7_3", Configuration::new);
factory.register(TextColorProvider.class, "b1_7_3", TextColor::new);
factory.register(LoggerProvider.class, "b1_7_3", Logger::new);
factory.register(FileProvider.class, "b1_7_3", File::new);
}
}

View file

@ -0,0 +1,136 @@
package org.adrianvictor.lib.impl.b1_7_3.configuration;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
public class Configuration implements org.adrianvictor.lib.configuration.provider.ConfigurationProvider {
org.bukkit.util.config.Configuration config;
@Override
public void load(File file) {
config = new org.bukkit.util.config.Configuration(file);
config.load();
}
@Override
public void load(String contents) throws IOException {
String timestamp = LocalDateTime.now()
.format(DateTimeFormatter.ofPattern("HH-mm-dd-MM-yyyy"));
Path temp = Files.createTempFile("tlib-configprovider-tmp-%s".formatted(timestamp), ".yml");
Files.writeString(temp, contents);
File file = temp.toFile();
load(file);
}
@Override
public void load(Reader reader) throws IOException {
String timestamp = LocalDateTime.now()
.format(DateTimeFormatter.ofPattern("HH-mm-dd-MM-yyyy"));
Path temp = Files.createTempFile("tlib-configprovider-tmp-%s".formatted(timestamp), ".yml");
try (BufferedWriter writer = Files.newBufferedWriter(temp)) {
reader.transferTo(writer);
}
File file = temp.toFile();
load(file);
}
@Override
public boolean save(File file) {
return config.save();
}
@Override
public boolean save() {
return config.save();
}
@Override
public String saveToString() {
return config.toString();
}
@Override
public Object getProperty(String path) {
return config.getProperty(path);
}
@Override
public void setProperty(String path, Object value) {
config.setProperty(path, value);
}
@Override
public Map<String, Object> getAll() {
return config.getAll();
}
@Override
public boolean getBoolean(String path, boolean def) {
return config.getBoolean(path, def);
}
@Override
public List<Boolean> getBooleanList(String path, List<Boolean> def) {
return config.getBooleanList(path, def);
}
@Override
public double getDouble(String path, double def) {
return config.getDouble(path, def);
}
@Override
public List<Double> getDoubleList(String path, List<Double> def) {
return config.getDoubleList(path, def);
}
@Override
public int getInt(String path, int def) {
return config.getInt(path, def);
}
@Override
public String getString(String path) {
return config.getString(path);
}
@Override
public String getString(String path, String def) {
return config.getString(path, def);
}
@Override
public List<String> getStringList(String path, List<String> def) {
return config.getStringList(path, def);
}
@Override
public List<Integer> getIntList(String path, List<Integer> def) {
return config.getIntList(path, def);
}
@Override
public List<String> getKeys(String path) {
return config.getKeys(path);
}
@Override
public List<String> getKeys() {
return config.getKeys();
}
@Override
public List<Object> getList(String path) {
return config.getList(path);
}
}

View file

@ -0,0 +1,37 @@
package org.adrianvictor.lib.impl.b1_7_3.file;
import org.adrianvictor.lib.file.provider.FileProvider;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class File implements FileProvider {
@Override
public void saveResource(String resourcePath, boolean replace, JavaPlugin plugin) throws IOException {
java.io.File file = new java.io.File(plugin.getDataFolder(), resourcePath);
if (!file.exists() || replace) {
file.getParentFile().mkdirs();
InputStream in = plugin.getClass().getResourceAsStream("/" + resourcePath);
if (in == null) {
throw new IllegalArgumentException("Resource not found: " + resourcePath);
}
FileOutputStream out = new FileOutputStream(file);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) != -1) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
}
}

View file

@ -0,0 +1,38 @@
package org.adrianvictor.lib.impl.b1_7_3.logging;
import org.adrianvictor.lib.logging.provider.LoggerProvider;
import org.bukkit.plugin.java.JavaPlugin;
public class Logger implements LoggerProvider {
private static JavaPlugin plugin;
private java.util.logging.Logger logger;
private String prefix = "[tenkumaLib] ";
public static void setPlugin(JavaPlugin p) {
plugin = p;
}
public Logger() {
if (plugin != null) {
logger = plugin.getServer().getLogger();
prefix = "[" + plugin.getDescription().getName() + "] ";
} else {
logger = java.util.logging.Logger.getLogger("Minecraft");
}
}
@Override
public void info(String text) {
logger.info(prefix + text);
}
@Override
public void warning(String text) {
logger.warning(prefix + text);
}
@Override
public void severe(String text) {
logger.severe(prefix + text);
}
}

View file

@ -0,0 +1,10 @@
package org.adrianvictor.lib.impl.b1_7_3.text;
import org.bukkit.ChatColor;
public class TextColor implements org.adrianvictor.lib.text.provider.TextColorProvider {
@Override
public String colorize(String colorCode) {
return ChatColor.valueOf(colorCode).toString();
}
}

View file

@ -0,0 +1 @@
org.adrianvictor.lib.impl.b1_7_3.B1_7_3Registrar

View file

@ -1,13 +0,0 @@
package gd.rf.adrianvictor.lib;
public class Color {
public String formatColors(String message) {
return message.replaceAll("&([0-9a-fk-or])", "§$1");
}
public Object[] ignoreColors(String message) {
String parsed = message.replaceAll("&([0-9a-fk-or])", "");
Boolean changed = parsed == message;
return new Object[] {parsed, changed};
}
}

View file

@ -1,135 +0,0 @@
package gd.rf.adrianvictor.lib;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.util.config.Configuration;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
/**
* Utility class for managing plugin configuration files.
* <p>
* This class extends {@link Configuration} to provide custom methods for loading, saving, and managing
* configuration files. It automatically handles the creation of parent directories and copies default configuration
* files from the plugin's resources if they do not exist.
* <p>
* <b>Note:</b> This class allows for flexible management of multiple configuration files, specified by their file name.
*/
public class Configuration extends Configuration {
private final File configFile;
private final String pluginName;
/**
* Constructs a new instance of {@code ConfigUtil}.
*
* @param plugin the plugin instance using this configuration utility
* @param fileName the name of the configuration file to manage (e.g., "config.yml", "settings.yml")
*/
public Configuration(JavaPlugin plugin, String fileName) {
super(new File(plugin.getDataFolder(), fileName));
this.configFile = new File(plugin.getDataFolder(), fileName);
this.pluginName = plugin.getDescription().getName();
}
/**
* Loads the configuration file.
* <ul>
* <li>Creates parent directories if they do not exist.</li>
* <li>Copies the default configuration file from the plugin's resources if the configuration file does not exist.</li>
* <li>Attempts to load the configuration by calling the superclass' {@code load()} method.</li>
* <li>Logs errors if the configuration file cannot be loaded.</li>
* </ul>
*/
@Override
public void load() {
createParentDirectories();
if (!configFile.exists()) {
copyDefaultConfig();
}
try {
super.load();
} catch (Exception e) {
Logger.severe(String.format("[%s] Failed to load config '%s': %s", pluginName, configFile.getName(), e.getMessage()));
}
}
/**
* Creates the parent directories for the configuration file if they do not exist.
* <p>
* Logs an error if the directories cannot be created.
*/
private void createParentDirectories() {
try {
Files.createDirectories(configFile.getParentFile().toPath());
} catch (IOException e) {
Logger.severe(String.format("[%s] Failed to generate default config directory: %s", pluginName, e.getMessage()));
}
}
/**
* Copies the default configuration file from the plugin's resources to the target location.
* <p>
* This method looks for a file in the plugin's resources with the same name as the configuration file being managed.
* If found, it copies this file to the plugin's data folder.
* <p>
* Logs an error if the default configuration file cannot be found or copied.
*/
private void copyDefaultConfig() {
// Adjust the path to ensure it's correct for your JAR structure
String resourcePath = "/" + configFile.getName();
try (InputStream input = getClass().getResourceAsStream(resourcePath)) {
if (input == null) {
Logger.severe(String.format("[%s] Default config '%s' wasn't found.", pluginName, configFile.getName()));
return;
}
Files.copy(input, configFile.toPath());
Logger.info(String.format("[%s] Default config '%s' generated successfully.", pluginName, configFile.getName()));
} catch (IOException e) {
Logger.severe(String.format("[%s] Failed to generate default config '%s': %s", pluginName, configFile.getName(), e.getMessage()));
}
}
/**
* Loads the configuration file and logs the result.
* <p>
* Logs a message indicating whether the configuration was loaded successfully.
*/
public void loadConfig() {
try {
this.load();
Logger.info(String.format("[%s] Config '%s' loaded successfully.", pluginName, configFile.getName()));
} catch (Exception e) {
Logger.severe(String.format("[%s] Failed to load config '%s': %s", pluginName, configFile.getName(), e.getMessage()));
}
}
/**
* Saves the configuration file and logs the result.
* <p>
* Logs a message indicating whether the configuration was saved successfully.
*/
public void saveConfig() {
try {
this.save();
Logger.info(String.format("[%s] Config '%s' saved successfully.", pluginName, configFile.getName()));
} catch (Exception e) {
Logger.severe(String.format("[%s] Failed to save config '%s': %s", pluginName, configFile.getName(), e.getMessage()));
}
}
/**
* Returns the configuration file managed by this utility.
*
* @return the configuration file
*/
public File getConfig() {
return configFile;
}
}

View file

@ -1,28 +0,0 @@
package gd.rf.adrianvictor.lib;
import static org.bukkit.Bukkit.getServer;
public class Log {
public static void info(String message) {
getServer().getLogger().info(message);
}
public static void infoc(String message) {
getServer().getLogger().info(message);
}
public static void warning(String message) {
getServer().getLogger().warning(message);
}
public static void warningc(String message) {
getServer().getLogger().warning(message);
}
public static void severe(String message) {
getServer().getLogger().severe(message);
}
public static void severec(String message) {
getServer().getLogger().severe(message);
}
}

View file

@ -1,8 +0,0 @@
package gd.rf.adrianvictor.lib;
import org.bukkit.plugin.java.JavaPlugin;
public class Main extends JavaPlugin {
public void onLoad() {
Log.info(this + " is loading.");
}
}

View file

@ -0,0 +1,107 @@
package org.adrianvictor.lib;
import org.adrianvictor.lib.logging.provider.LoggerProvider;
import org.adrianvictor.lib.versioning.DefaultVersionedServiceFactory;
import org.adrianvictor.lib.versioning.MinecraftVersion;
import org.adrianvictor.lib.versioning.VersionMatcher;
import org.adrianvictor.lib.versioning.VersionedServiceFactory;
import org.adrianvictor.lib.versioning.VersionedServiceRegistrar;
import org.bukkit.Bukkit;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.logging.Logger;
public class Main extends JavaPlugin {
private static Logger globalLogger;
private static LoggerProvider pluginLogger;
private static DefaultVersionedServiceFactory versionedServiceFactory;
public static VersionedServiceFactory getServiceFactory() {
return versionedServiceFactory;
}
@Override
public void onEnable() {
globalLogger = Bukkit.getServer().getLogger();
globalLogger.info("[tenkumaLib] Enabling tenkumaLib v2.0...");
VersionMatcher versionMatcher = new VersionMatcher();
versionedServiceFactory = new DefaultVersionedServiceFactory(versionMatcher);
MinecraftVersion version = MinecraftVersion.detect();
globalLogger.info("[tenkumaLib] Detected Minecraft Version: " + version);
boolean registered = false;
String coreRegistrar = version.getRegistrarClass();
if (coreRegistrar != null) {
if (loadRegistrar(coreRegistrar)) {
registered = true;
}
}
try {
java.util.ServiceLoader<VersionedServiceRegistrar> loader = java.util.ServiceLoader.load(VersionedServiceRegistrar.class, getClassLoader());
for (VersionedServiceRegistrar registrar : loader) {
String registrarName = registrar.getClass().getName();
if (registrarName.equals(coreRegistrar)) continue;
if (registerRegistrar(registrar)) {
registered = true;
}
}
} catch (Throwable t) {
// ServiceLoader failure is expected on some legacy platforms
}
if (!registered) {
globalLogger.warning("[tenkumaLib] No registrars were loaded! Services might not be available.");
}
try {
pluginLogger = LoggerProvider.get();
pluginLogger.info("tenkumaLib has been successfully enabled!");
} catch (Exception e) {
globalLogger.severe("[tenkumaLib] Failed to initialize plugin logger: " + e.getMessage());
e.printStackTrace();
}
}
private boolean loadRegistrar(String className) {
try {
Class<?> clazz = Class.forName(className, true, getClassLoader());
VersionedServiceRegistrar registrar = (VersionedServiceRegistrar) clazz.getDeclaredConstructor().newInstance();
return registerRegistrar(registrar);
} catch (NoClassDefFoundError e) {
globalLogger.info("[tenkumaLib] Skipping registrar " + className + " (incompatible server version)");
} catch (Throwable t) {
globalLogger.warning("[tenkumaLib] Failed to load registrar " + className + ": " + t.toString());
}
return false;
}
private boolean registerRegistrar(VersionedServiceRegistrar registrar) {
String registrarName = registrar.getClass().getName();
try {
registrar.setPlugin(this);
registrar.register(versionedServiceFactory);
globalLogger.info("[tenkumaLib] Registered " + registrarName);
return true;
} catch (NoClassDefFoundError e) {
globalLogger.info("[tenkumaLib] Skipping registrar " + registrarName + " (incompatible server version)");
} catch (Throwable t) {
globalLogger.warning("[tenkumaLib] Failed to register " + registrarName + ": " + t.toString());
}
return false;
}
@Override
public void onDisable() {
if (pluginLogger != null) {
pluginLogger.info("tenkumaLib has been disabled!");
}
}
}

View file

@ -0,0 +1,11 @@
package org.adrianvictor.lib.configuration.exception;
public class InvalidConfigurationException extends Exception {
public InvalidConfigurationException(String message) {
super(message);
}
public InvalidConfigurationException(String message, Throwable cause) {
super(message, cause);
}
}

View file

@ -0,0 +1,38 @@
package org.adrianvictor.lib.configuration.provider;
import org.adrianvictor.lib.Main;
import org.adrianvictor.lib.configuration.exception.InvalidConfigurationException;
import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.util.List;
import java.util.Map;
public interface ConfigurationProvider {
static ConfigurationProvider get() {
return Main.getServiceFactory().getService(ConfigurationProvider.class);
}
void load(File file) throws IOException, InvalidConfigurationException;
void load(String contents) throws IOException, InvalidConfigurationException;
void load(Reader reader) throws IOException, InvalidConfigurationException;
boolean save(File file);
boolean save();
String saveToString();
Object getProperty(String path);
void setProperty(String path, Object value);
Map<String, Object> getAll();
boolean getBoolean(String path, boolean def);
List<Boolean> getBooleanList(String path, List<Boolean> def);
double getDouble(String path, double def);
List<Double> getDoubleList(String path, List<Double> def);
int getInt(String path, int def);
String getString(String path);
String getString(String path, String def);
List<String> getStringList(String path, List<String> def);
List<Integer> getIntList(String path, List<Integer> def);
List<String> getKeys(String path);
List<String> getKeys();
List<Object> getList(String path);
}

View file

@ -0,0 +1,14 @@
package org.adrianvictor.lib.file.provider;
import org.adrianvictor.lib.Main;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.IOException;
public interface FileProvider {
static FileProvider get() {
return Main.getServiceFactory().getService(FileProvider.class);
}
void saveResource(String resourcePath, boolean replace, JavaPlugin plugin) throws IOException;
}

View file

@ -0,0 +1,24 @@
package org.adrianvictor.lib.logging.provider;
import org.adrianvictor.lib.Main;
public interface LoggerProvider {
static LoggerProvider get() {
return Main.getServiceFactory().getService(LoggerProvider.class);
}
void info(String text);
void warning(String text);
/**
* @deprecated
* Does not throw an error.
* <p> Use {@link LoggerProvider#severe(String)} instead.
*/
@Deprecated
default void error(String text) {
severe(text);
}
void severe(String text);
}

View file

@ -0,0 +1,40 @@
package org.adrianvictor.lib.text;
import org.adrianvictor.lib.versioning.VersionedServiceFactory;
import org.adrianvictor.lib.text.provider.TextColorProvider;
public class TextColorUtils {
private final TextColorProvider provider;
public TextColorUtils() {
this.provider = TextColorProvider.get();
}
public TextColorUtils(VersionedServiceFactory factory) {
this.provider = factory.getService(TextColorProvider.class);
}
public String formatColors(String message) {
return message.replace("&", "§");
}
public String ignoreColors(String message) {
return message.replaceAll("&([0-9a-fk-or])", "");
}
public String rainbow(String message) {
String[] colorNames = {"RED", "GOLD", "YELLOW", "GREEN", "AQUA", "BLUE", "LIGHT_PURPLE"};
int colorIndex = 0;
String coloredMessage = "";
for (char c : message.toCharArray()) {
String currentColor = provider.colorize(colorNames[colorIndex]);
coloredMessage += currentColor + c;
colorIndex++;
if (colorIndex >= colorNames.length) {
colorIndex = 0;
}
}
return coloredMessage;
}
}

View file

@ -0,0 +1,18 @@
package org.adrianvictor.lib.text;
import java.util.Random;
public class TextUtils {
public static String generateRandomString(int length) {
String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
Random random = new Random();
StringBuilder randomString = new StringBuilder(length);
for (int i = 0; i < length; i++) {
int randomIndex = random.nextInt(characters.length());
randomString.append(characters.charAt(randomIndex));
}
return randomString.toString();
}
}

View file

@ -0,0 +1,11 @@
package org.adrianvictor.lib.text.provider;
import org.adrianvictor.lib.Main;
public interface TextColorProvider {
static TextColorProvider get() {
return Main.getServiceFactory().getService(TextColorProvider.class);
}
String colorize(String colorCode);
}

View file

@ -0,0 +1,41 @@
package org.adrianvictor.lib.versioning;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Supplier;
public class DefaultVersionedServiceFactory implements VersionedServiceFactory {
private final VersionMatcher versionMatcher;
private final Map<Class<?>, Map<String, Supplier<?>>> serviceRegistrations = new HashMap<>();
public DefaultVersionedServiceFactory(VersionMatcher versionMatcher) {
this.versionMatcher = versionMatcher;
}
@Override
public <T> void register(Class<T> serviceType, String versionSuffix, Supplier<T> supplier) {
serviceRegistrations
.computeIfAbsent(serviceType, k -> new HashMap<>())
.put(versionSuffix, supplier);
}
@Override
@SuppressWarnings("unchecked")
public <T> T getService(Class<T> serviceType) {
String serverVersion = versionMatcher.getServerVersion();
java.util.List<String> versionSuffixes = versionMatcher.getClassSuffixes(serverVersion);
Map<String, Supplier<?>> versionSuppliers = serviceRegistrations.get(serviceType);
if (versionSuppliers == null) {
throw new IllegalStateException("No service registered for type " + serviceType.getName());
}
for (String suffix : versionSuffixes) {
if (versionSuppliers.containsKey(suffix)) {
return (T) versionSuppliers.get(suffix).get();
}
}
throw new IllegalStateException("No service registered for type " + serviceType.getName() + " and versions " + versionSuffixes + ". Current server version: " + serverVersion);
}
}

View file

@ -0,0 +1,50 @@
package org.adrianvictor.lib.versioning;
import org.bukkit.Bukkit;
public enum MinecraftVersion {
B1_7_3(0, "b1_7_3", "org.adrianvictor.lib.impl.b1_7_3.B1_7_3Registrar"),
V1_21(21, "r1_21", "org.adrianvictor.lib.impl.r1_21.R1_21Registrar"),
UNKNOWN(-1, "unknown");
private final int versionId;
private final String suffix;
private final String registrarClass;
MinecraftVersion(int versionId, String suffix) {
this(versionId, suffix, null);
}
MinecraftVersion(int versionId, String suffix, String registrarClass) {
this.versionId = versionId;
this.suffix = suffix;
this.registrarClass = registrarClass;
}
public int getVersionId() {
return versionId;
}
public String getSuffix() {
return suffix;
}
public String getRegistrarClass() {
return registrarClass;
}
public boolean isAtLeast(MinecraftVersion other) {
return this.versionId >= other.versionId;
}
public static MinecraftVersion detect() {
String version = Bukkit.getVersion();
if (version.contains("1.7.3")) return B1_7_3;
String bukkitVersion = Bukkit.getBukkitVersion();
String mcVer = bukkitVersion.split("-")[0];
//if (mcVer.startsWith("1.21")) return V1_21;
return V1_21;
}
}

View file

@ -0,0 +1,32 @@
package org.adrianvictor.lib.versioning;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class VersionMatcher {
public VersionMatcher() {}
public List<String> getClassSuffixes(String serverVersion) {
MinecraftVersion version = MinecraftVersion.detect();
if (version == MinecraftVersion.UNKNOWN) {
return Collections.emptyList();
}
List<String> suffixes = new ArrayList<>();
if (version.isAtLeast(MinecraftVersion.V1_21)) {
suffixes.add("r1_21");
}
if (version == MinecraftVersion.B1_7_3) {
suffixes.add("b1_7_3");
}
return suffixes;
}
public String getServerVersion() {
return MinecraftVersion.detect().name();
}
}

View file

@ -0,0 +1,8 @@
package org.adrianvictor.lib.versioning;
import java.util.function.Supplier;
public interface VersionedServiceFactory {
<T> void register(Class<T> serviceType, String versionSuffix, Supplier<T> supplier);
<T> T getService(Class<T> serviceType);
}

View file

@ -0,0 +1,9 @@
package org.adrianvictor.lib.versioning;
import org.bukkit.plugin.java.JavaPlugin;
public interface VersionedServiceRegistrar {
void setPlugin(JavaPlugin plugin);
JavaPlugin getPlugin();
void register(VersionedServiceFactory factory);
}

View file

@ -0,0 +1,8 @@
name: tenkumaLib
author: tenkuma
database: false
main: org.adrianvictor.lib.Main
startup: startup
url: https://adrianvic.github.io
version: '2.1.1'
api-version: '1.21'

View file

@ -0,0 +1,36 @@
package org.adrianvictor.lib.impl.r1_21;
import org.adrianvictor.lib.file.provider.FileProvider;
import org.adrianvictor.lib.impl.r1_21.file.File;
import org.adrianvictor.lib.impl.r1_21.logging.Logger;
import org.adrianvictor.lib.versioning.VersionedServiceFactory;
import org.adrianvictor.lib.versioning.VersionedServiceRegistrar;
import org.adrianvictor.lib.configuration.provider.ConfigurationProvider;
import org.adrianvictor.lib.impl.r1_21.configuration.Configuration;
import org.adrianvictor.lib.text.provider.TextColorProvider;
import org.adrianvictor.lib.impl.r1_21.text.TextColor;
import org.adrianvictor.lib.logging.provider.LoggerProvider;
import org.bukkit.plugin.java.JavaPlugin;
public class R1_21Registrar implements VersionedServiceRegistrar {
private JavaPlugin plugin;
@Override
public void setPlugin(JavaPlugin plugin) {
this.plugin = plugin;
}
@Override
public JavaPlugin getPlugin() {
return plugin;
}
@Override
public void register(VersionedServiceFactory factory) {
Logger.setPlugin(this.plugin);
factory.register(ConfigurationProvider.class, "r1_21", Configuration::new); // min 1.1
factory.register(TextColorProvider.class, "r1_21", TextColor::new); // min 1.16.5
factory.register(LoggerProvider.class, "r1_21", Logger::new);
factory.register(FileProvider.class, "r1_21", File::new);
}
}

View file

@ -0,0 +1,158 @@
package org.adrianvictor.lib.impl.r1_21.configuration;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.YamlConfiguration;
import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
public class Configuration implements org.adrianvictor.lib.configuration.provider.ConfigurationProvider {
YamlConfiguration config = new YamlConfiguration();
File configFile;
@Override
public void load(File file) throws IOException, org.adrianvictor.lib.configuration.exception.InvalidConfigurationException {
try {
config.load(file);
configFile = file;
} catch (InvalidConfigurationException e) {
throw new org.adrianvictor.lib.configuration.exception.InvalidConfigurationException(e.getMessage());
}
}
@Override
public void load(String contents) throws IOException, org.adrianvictor.lib.configuration.exception.InvalidConfigurationException {
String timestamp = LocalDateTime.now()
.format(DateTimeFormatter.ofPattern("HH-mm-dd-MM-yyyy"));
Path temp = Files.createTempFile("tlib-configprovider-tmp-%s".formatted(timestamp), ".yml");
Files.writeString(temp, contents);
File file = temp.toFile();
load(file);
}
@Override
public void load(Reader reader) throws IOException, org.adrianvictor.lib.configuration.exception.InvalidConfigurationException {
try {
config.load(reader);
} catch (InvalidConfigurationException e) {
throw new org.adrianvictor.lib.configuration.exception.InvalidConfigurationException(e.getMessage());
}
}
@Override
public boolean save(File file) {
try {
config.save(file);
return true;
} catch (IOException e) {
return false;
}
}
@Override
public boolean save() {
try {
config.save(configFile);
return true;
} catch (IOException e) {
return false;
}
}
@Override
public String saveToString() {
return config.saveToString();
}
@Override
public Object getProperty(String path) {
return config.get(path);
}
@Override
public void setProperty(String path, Object value) {
config.set(path, value);
}
@Override
public Map<String, Object> getAll() {
assert config.getRoot() != null;
return config.getRoot().getValues(true);
}
@Override
public boolean getBoolean(String path, boolean def) {
return config.getBoolean(path, def);
}
@Override
public List<Boolean> getBooleanList(String path, List<Boolean> def) {
List<Boolean> result = config.getBooleanList(path);
if (result.isEmpty()) result = def;
return result;
}
@Override
public double getDouble(String path, double def) {
return config.getDouble(path, def);
}
@Override
public List<Double> getDoubleList(String path, List<Double> def) {
List<Double> result = config.getDoubleList(path);
if (result.isEmpty()) result = def;
return result;
}
@Override
public int getInt(String path, int def) {
return config.getInt(path, def);
}
@Override
public String getString(String path) {
return config.getString(path);
}
@Override
public String getString(String path, String def) {
return config.getString(path, def);
}
@Override
public List<String> getStringList(String path, List<String> def) {
List<String> result = config.getStringList(path);
if (result.isEmpty()) result = def;
return result;
}
@Override
public List<Integer> getIntList(String path, List<Integer> def) {
List<Integer> result = config.getIntegerList(path);
if (result.isEmpty()) result = def;
return result;
}
@Override
public List<String> getKeys(String path) {
Set<String> set = Objects.requireNonNull(config.getConfigurationSection(path)).getKeys(true);
return set.stream().toList();
}
@Override
public List<String> getKeys() {
Set<String> set = Objects.requireNonNull(config.getRoot()).getKeys(true);
return set.stream().toList();
}
@Override
public List<Object> getList(String path) {
return Collections.singletonList(config.getList(path));
}
}

View file

@ -0,0 +1,11 @@
package org.adrianvictor.lib.impl.r1_21.file;
import org.adrianvictor.lib.file.provider.FileProvider;
import org.bukkit.plugin.java.JavaPlugin;
public class File implements FileProvider {
@Override
public void saveResource(String resourcePath, boolean replace, JavaPlugin plugin) {
plugin.saveResource(resourcePath, replace);
}
}

View file

@ -0,0 +1,36 @@
package org.adrianvictor.lib.impl.r1_21.logging;
import org.adrianvictor.lib.logging.provider.LoggerProvider;
import org.bukkit.plugin.java.JavaPlugin;
public class Logger implements LoggerProvider {
private static JavaPlugin plugin;
private java.util.logging.Logger logger;
public static void setPlugin(JavaPlugin p) {
plugin = p;
}
public Logger() {
if (plugin != null) {
logger = plugin.getLogger();
} else {
logger = java.util.logging.Logger.getLogger("Minecraft");
}
}
@Override
public void info(String text) {
logger.info(text);
}
@Override
public void warning(String text) {
logger.warning(text);
}
@Override
public void severe(String text) {
logger.severe(text);
}
}

View file

@ -0,0 +1,10 @@
package org.adrianvictor.lib.impl.r1_21.text;
import net.kyori.adventure.text.format.NamedTextColor;
public class TextColor implements org.adrianvictor.lib.text.provider.TextColorProvider {
@Override
public String colorize(String colorCode) {
return NamedTextColor.NAMES.valueOr(colorCode, NamedTextColor.WHITE).toString();
}
}

View file

@ -0,0 +1 @@
org.adrianvictor.lib.impl.r1_21.R1_21Registrar