Compare commits

...

48 commits
1.0 ... main

Author SHA1 Message Date
5536183a99 Events Bus deps update for JarInJar in downstream 2024-09-14 18:04:15 -07:00
eed3904d96 Add a jenkinsfile with build instructions 2024-09-12 15:03:36 -07:00
9c3fc3feb9 Adjust publishing URL 2024-09-12 15:01:25 -07:00
0b79531751 Place a static method check to prevent errors. 2024-02-13 21:48:02 -07:00
e0bbf63fc1 Fix a minor bug with posting to wrong priority levels. 2024-02-13 21:33:40 -07:00
7e25ece9b0 Mark the class scanner for removal 2024-02-13 21:25:45 -07:00
799f32bca7 Replace a function in the API 2024-02-13 21:16:49 -07:00
702b68a7ac Replace reflections 2024-02-13 02:16:58 -07:00
ccddf83a7c Oops, shadow jar did not take effect 2024-02-13 02:02:45 -07:00
32786be1e3 Test another fix 2024-02-13 01:55:57 -07:00
0fd90a8ff4 Test another fix 2024-02-13 01:26:17 -07:00
2052afaee0 Test another fix 2024-02-13 01:19:22 -07:00
08058af758 Attempt to fix the field not being found 2024-02-12 21:27:29 -07:00
ee629e2bc8 Update to using a newer method. 2024-02-12 18:54:40 -07:00
fc125dfd32 Patch the EventsBus as it was non-functional 2024-02-12 14:13:29 -07:00
80148106a2 Update project JDK Version to 17 2024-02-06 20:58:01 -07:00
acd5f1c02c Update publish instructions 2024-02-06 18:51:23 -07:00
5ec55d786a Update repository info 2024-01-07 14:44:14 -07:00
901c76a937 Retarget java 8 2023-12-04 23:20:21 -07:00
eab6877c9e Fix publish errors 2023-11-19 05:04:44 -07:00
b15a607f9d Update publish section 2023-11-19 04:20:16 -07:00
baa0f14c17 Update publish section 2023-11-19 04:16:18 -07:00
5a20237230 Adds a classifier to jar task 2023-11-19 04:13:55 -07:00
7443d0e10b Adds a classifier to jar task 2023-11-19 04:11:42 -07:00
99630b7470 Adds a classifier to jar task 2023-11-19 03:54:19 -07:00
434349aca6 Add a debug line 2023-11-19 03:48:08 -07:00
1d5b113308 Update bus API to fix an error 2023-11-19 03:14:38 -07:00
803370c35c Test changes to publication 2023-10-15 06:41:57 -07:00
18619334bd Test changes to publication 2023-10-15 06:38:51 -07:00
73e0dc4f11 Fix compile error 2023-10-15 06:29:16 -07:00
65416ae18d Update method for generating pom 2023-10-15 06:27:27 -07:00
6c65aa1cb0 Adds any dependencies to pom output 2023-10-15 06:23:03 -07:00
0146cb6473 Fixes the static modifier check 2023-10-14 14:23:27 -07:00
00ce1750c5 Adds a runtime property to allow programs to dynamically set debug 2023-10-13 07:59:19 -07:00
7aaed4b8f4 Fix version information 2023-10-12 19:10:31 -07:00
87980865f8 Update root project name 2023-10-12 19:09:17 -07:00
569db6e849 Update root project name 2023-10-12 18:58:03 -07:00
c9d44b6527 Adds the definition for a basic tick event. 2023-10-12 18:26:22 -07:00
fca7a9ce61 Adds a reset event 2023-10-12 18:25:43 -07:00
96b096478c Implement post method in bus 2023-10-12 18:15:05 -07:00
d1c79aac63 Finish implementing EventBus register function 2023-10-12 18:00:52 -07:00
e8646ee518 More feature parity with C# EventBus 2023-10-12 17:32:20 -07:00
783de1e9c0 Start implementing bus. 2023-10-12 15:18:06 -07:00
4d005e1704 Make some more changes 2023-10-12 14:54:16 -07:00
e61335609f Add wrapper 2023-10-12 14:52:40 -07:00
e0adea7a16 Make gradlew executable 2023-10-12 14:23:44 -07:00
b7c272ca09 Start adding implementation 2023-10-12 13:31:27 -07:00
5872c2f913 initial commit 2023-10-12 11:35:12 -07:00
24 changed files with 1095 additions and 0 deletions

8
.gitignore vendored
View file

@ -22,3 +22,11 @@
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
replay_pid*
.gradle
build
bin
.idea

50
Jenkinsfile vendored Normal file
View file

@ -0,0 +1,50 @@
pipeline {
agent any
options {
buildDiscarder(
logRotator(
numToKeepStr: '5'
)
)
}
stages {
stage("Build on Linux") {
agent {
label 'linux'
}
tools {
jdk "jdk17"
}
steps {
script {
sh '''
#!/bin/bash
git clean -xfd
git reset --hard
git fetch
java -version
chmod +x gradlew
./gradlew -Dorg.gradle.java.home="$JAVA_HOME" build publish
'''
}
}
post {
always {
archiveArtifacts artifacts: "build/libs/*.jar"
deleteDir()
}
}
}
}
}

103
build.gradle Normal file
View file

@ -0,0 +1,103 @@
/*
* This file was generated by the Gradle 'init' task.
*
* This generated file contains a sample Java library project to get you started.
* For more details take a look at the 'Building Java & JVM projects' chapter in the Gradle
* User Manual available at https://docs.gradle.org/8.0.2/userguide/building_java_projects.html
*/
plugins {
// Apply the java-library plugin for API and implementation separation.
id 'java-library'
id 'idea'
id 'eclipse'
id 'maven-publish'
}
group = "dev.zontreck"
archivesBaseName = "EventsBus"
java.toolchain.languageVersion = JavaLanguageVersion.of(17)
java {
withSourcesJar()
withJavadocJar()
}
configurations {
provided
implementation.extendsFrom(provided)
runtime.extendsFrom(provided)
compile.extendsFrom(provided)
}
def determinePatchVersion = {
// get the name of the last tag
def tagInfo = new ByteArrayOutputStream()
exec {
commandLine 'git', 'describe', '--tags'
standardOutput = tagInfo
}
tagInfo = tagInfo.toString()
if (!tagInfo.contains('-')) {
return 0
}
return tagInfo.split("-")[1]
}
version = determinePatchVersion()
version = "${apiVer}.${version}"
println("Compile for version : ${version}")
repositories {
// Use Maven Central for resolving dependencies.
mavenCentral()
}
dependencies {
}
jar {
manifest {
attributes (
'Multi-Release': 'true'
)
}
duplicatesStrategy = "exclude"
from { configurations.provided.collect { it.isDirectory() ? it : zipTree(it) } }
exclude 'META-INF/*'
exclude 'META-INF/*'
exclude 'META-INF/*'
}
jar.dependsOn(sourcesJar, javadocJar)
def MAVEN_PASSWORD = "AriasCreationsMavenPassword"
def MAVEN_USER = "AriasCreationsMavenUser"
publishing {
publications {
mavenJava(MavenPublication) {
artifact jar
artifact sourcesJar
artifact javadocJar
}
}
repositories {
maven {
url = "https://git.zontreck.com/api/packages/AriasCreations/maven"
name = "ariascreations"
credentials {
username = project.findProperty(MAVEN_USER)
password = project.findProperty(MAVEN_PASSWORD)
}
}
}
}

1
gradle.properties Normal file
View file

@ -0,0 +1 @@
apiVer = 1.0

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

Binary file not shown.

View file

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

244
gradlew vendored Executable file
View file

@ -0,0 +1,244 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=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=SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"

92
gradlew.bat vendored Normal file
View file

@ -0,0 +1,92 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@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.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

1
settings.gradle Normal file
View file

@ -0,0 +1 @@
rootProject.name = "EventsBus"

View file

@ -0,0 +1,166 @@
package dev.zontreck.eventsbus;
import dev.zontreck.eventsbus.annotations.Priority;
import dev.zontreck.eventsbus.annotations.SingleshotEvent;
import dev.zontreck.eventsbus.annotations.Subscribe;
import dev.zontreck.eventsbus.events.EventBusReadyEvent;
import dev.zontreck.eventsbus.events.ResetEventBusEvent;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.*;
import java.util.stream.Collectors;
/**
* To be removed
* <br/>
* Use {EventDispatcher} instead
*/
@Deprecated()
public class Bus {
/**
* The main event bus!
*/
private static Bus Main;
static {
if(Main == null)
{
Main = new Bus("Main Event Bus", false);
}
}
public static boolean debug = false;
public final String BusName;
public final boolean UsesInstances;
public Bus(String name, boolean useInstances) {
BusName = name;
UsesInstances = useInstances;
Post(new EventBusReadyEvent());
}
public Map<Class<?>, List<EventContainer>> static_events = new HashMap<Class<?>, List<EventContainer>>();
public Map<Class<?>, List<EventContainer>> instanced_events = new HashMap<Class<?>, List<EventContainer>>();
public static <T> void Register(Class<T> clazz, T instance) {
List<Method> nonStaticMethods = Arrays.stream(clazz.getMethods())
.filter(x -> x.isAnnotationPresent(Subscribe.class))
.filter(x -> (x.getModifiers() & Modifier.STATIC) != Modifier.STATIC)
.collect(Collectors.toList());
List<Method> staticMethods = Arrays.stream(clazz.getMethods())
.filter(x -> x.isAnnotationPresent(Subscribe.class))
.filter(x -> (x.getModifiers() & Modifier.STATIC) == Modifier.STATIC)
.collect(Collectors.toList());
// Register the non-static methods if applicable
if (instance != null) {
for (Method m :
nonStaticMethods) {
EventContainer container = new EventContainer();
container.instance = instance;
container.method = m;
container.clazz = clazz;
if (m.isAnnotationPresent(Priority.class))
container.Level = m.getAnnotation(Priority.class).Level();
else container.Level = PriorityLevel.LOWEST;
Class<?> clz = m.getParameters()[0].getType();
container.IsSingleshot = m.isAnnotationPresent(SingleshotEvent.class);
if (Main.instanced_events.containsKey(clz))
Main.instanced_events.get(clz).add(container);
else {
Main.instanced_events.put(clz, new ArrayList<>());
Main.instanced_events.get(clz).add(container);
}
}
}
for (Method m : staticMethods) {
EventContainer container = new EventContainer();
container.instance = null;
container.method = m;
container.clazz = clazz;
if (m.isAnnotationPresent((Priority.class)))
container.Level = m.getAnnotation(Priority.class).Level();
else container.Level = PriorityLevel.LOWEST;
Class<?> clz = m.getParameters()[0].getType();
container.IsSingleshot = m.isAnnotationPresent(SingleshotEvent.class);
if (Main.static_events.containsKey(clz))
Main.static_events.get(clz).add(container);
else {
Main.static_events.put(clz, new ArrayList<>());
Main.static_events.get(clz).add(container);
}
}
}
/**
* Posts an event to the bus.
*
* @param event The event you wish to post
* @return True if the event was cancelled.
*/
public static boolean Post(Event event) {
for (PriorityLevel level :
PriorityLevel.values()) {
// Call each priority level in order of declaration
// Static first, then instanced
// At the end, this method will return the cancellation result.
try {
if (Main.static_events.containsKey(event.getClass())) {
EventContainer[] tempArray = (EventContainer[]) Main.static_events.get(event.getClass()).toArray();
for (EventContainer container : tempArray) {
if (container.invoke(event, level)) {
Main.static_events.get(event.getClass()).remove(container);
}
}
}
if (Main.instanced_events.containsKey(event.getClass())) {
EventContainer[] tempArray = (EventContainer[]) Main.instanced_events.get(event.getClass()).toArray();
for (EventContainer container : tempArray) {
if (container.invoke(event, level)) {
Main.instanced_events.get(event.getClass()).remove(container);
}
}
}
} catch (Exception e) {
}
}
return event.isCancelled();
}
/**
* Attempts to reset the Event Bus
*
* @return True if the bus was successfully reset (If not interrupts!)
* @see dev.zontreck.eventsbus.events.ResetEventBusEvent
*/
public static boolean Reset() {
if (!Post(new ResetEventBusEvent())) {
Main.static_events = new HashMap<>();
Main.instanced_events = new HashMap<>();
Post(new EventBusReadyEvent());
return true;
}
return false;
}
}

View file

@ -0,0 +1,95 @@
package dev.zontreck.eventsbus;
import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
@Deprecated
/**
* Used internally. Do not directly invoke
* <br/>
* Accessor is set Protected intentionally!!!!!!!!!
*/
class ClassScanner {
/**
* Start the process of scanning the classes and forcing them to load in
* <br/>
* This is used by the event dispatcher
*/
protected static void DoScan() {
// Scan all classes in the classpath
Set<Class<?>> scannedClasses = scanClasses();
// Force loading of all scanned classes
for (Class<?> clazz : scannedClasses) {
try {
// Load the class
Class.forName(clazz.getName());
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
private static Set<Class<?>> scanClasses() {
String classpath = System.getProperty("java.class.path");
String[] classpathEntries = classpath.split(File.pathSeparator);
Set<Class<?>> scannedClasses = new HashSet<>();
for (String classpathEntry : classpathEntries) {
File file = new File(classpathEntry);
if (file.isDirectory()) {
scanClassesInDirectory(file, "", scannedClasses);
} else if (file.isFile() && classpathEntry.endsWith(".jar")) {
scanClassesInJar(file, scannedClasses);
}
}
return scannedClasses;
}
private static void scanClassesInDirectory(File directory, String packageName, Set<Class<?>> scannedClasses) {
File[] files = directory.listFiles();
if (files == null) {
return;
}
for (File file : files) {
if (file.isDirectory()) {
scanClassesInDirectory(file, packageName + "." + file.getName(), scannedClasses);
} else if (file.getName().endsWith(".class")) {
String className = packageName + "." + file.getName().substring(0, file.getName().length() - 6);
try {
Class<?> clazz = Class.forName(className);
scannedClasses.add(clazz);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
}
private static void scanClassesInJar(File jarFile, Set<Class<?>> scannedClasses) {
try (JarFile jf = new JarFile(jarFile)) {
for (JarEntry entry : Collections.list(jf.entries())) {
if (entry.getName().endsWith(".class")) {
String className = entry.getName().replace("/", ".").substring(0, entry.getName().length() - 6);
try {
Class<?> clazz = Class.forName(className);
scannedClasses.add(clazz);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

View file

@ -0,0 +1,46 @@
package dev.zontreck.eventsbus;
import dev.zontreck.eventsbus.annotations.Cancellable;
import dev.zontreck.eventsbus.annotations.Priority;
public class Event {
private boolean cancelled = false;
/**
* Checks if the event can be cancelled.
*
* @return True if the cancellation annotation is present.
* @see Cancellable
*/
public boolean IsCancellable() {
Class<?> Current = this.getClass();
return Current.isAnnotationPresent(Cancellable.class);
}
/**
* Checks if the event is cancelled.
*
* @return False if the event cannot be cancelled; or
* The current cancellation status for the event
*/
public boolean isCancelled() {
if (!IsCancellable())
return false;
return cancelled;
}
/**
* Sets the cancelled status for the event
*
* @param cancel Whether the event should be marked as cancelled or not.
*/
public void setCancelled(boolean cancel) {
cancelled = cancel;
}
public PriorityLevel getPriorityLevel() {
Class<?> Current = this.getClass();
return Current.getAnnotation(Priority.class).Level();
}
}

View file

@ -0,0 +1,45 @@
package dev.zontreck.eventsbus;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class EventContainer {
public Class<?> clazz;
public Object instance;
/**
* The method that gets invoked, either statically, or via the instance.
*/
public Method method;
/**
* Indicates whether an event gets removed from the register after being invoked once.
*/
public boolean IsSingleshot;
/**
* The current method's priority level
*/
public PriorityLevel Level;
/**
* Invokes the event
*
* @param EventArg The event instance to pass to the subscribed function
* @param level Current priority level on the call loop. Will refuse to invoke if the priority level mismatches.
* @return True if the event was single shot and should be deregistered
* @throws InvocationTargetException
* @throws IllegalAccessException
*/
public boolean invoke(Event EventArg, PriorityLevel level) throws InvocationTargetException, IllegalAccessException {
if (Level != level) return false;
if (instance == null) {
method.invoke(null, EventArg);
} else {
method.invoke(instance, EventArg);
}
return IsSingleshot;
}
}

View file

@ -0,0 +1,124 @@
package dev.zontreck.eventsbus;
import dev.zontreck.eventsbus.annotations.EventSubscriber;
import dev.zontreck.eventsbus.annotations.Priority;
import dev.zontreck.eventsbus.annotations.SingleshotEvent;
import dev.zontreck.eventsbus.annotations.Subscribe;
import dev.zontreck.eventsbus.events.EventBusReadyEvent;
import dev.zontreck.eventsbus.events.ResetEventBusEvent;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class EventDispatcher
{
private static List<Method> singleshot = new ArrayList<>();
private static List<Class<?>> subscribers = new ArrayList<>();
/**
* Scans every Java class that is currently loaded. It then checks for Subscribe, and a proper parameter before posting the Event.
* The Event will only be posted if not cancelled using {@link Event#setCancelled(boolean)} and that {@link Subscribe#allowCancelled()} allows.
* @param event The event to post
* @return True if cancelled.
*/
public static boolean Post(Event event)
{
for(PriorityLevel level : PriorityLevel.values())
{
for(Class<?> clazz : subscribers)
{
for(Method M :clazz.getMethods())
{
if(!M.isAnnotationPresent(Subscribe.class)) continue;
Subscribe subscriber = M.getAnnotation(Subscribe.class);
boolean canPost=true;
Class<?> param = M.getParameterTypes()[0];
if(param == event.getClass())
{
if(M.isAnnotationPresent(SingleshotEvent.class))
{
if(singleshot.contains(M))
{
canPost=false;
}
}
} else canPost=false;
PriorityLevel eventPriotityLevel= PriorityLevel.HIGH; // Default
if(M.isAnnotationPresent(Priority.class))
{
Priority prio = M.getAnnotation(Priority.class);
eventPriotityLevel=prio.Level();
}
if(level != eventPriotityLevel)
{
canPost=false;
}
// Dispatch the event now
if(!canPost) continue;
if(!M.canAccess(null))
{
canPost=false;
System.out.println("ERROR: Even subscriber methods must be static and public");
}
try {
if(event.isCancelled() && !subscriber.allowCancelled())
continue;
else
M.invoke(null, event);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
}
}
}
return event.isCancelled();
}
/**
* Register a class
*/
public static void Register(Class<?> clazz)
{
if(clazz.isAnnotationPresent(EventSubscriber.class))
subscribers.add(clazz);
}
/**
* Resets the events system.
* <br/>
* This action clears the Singleshot list for the events that should only be invoked once. And rescans all classes incase new classes were dynamically loaded.
*/
public static void Reset()
{
Post(new ResetEventBusEvent());
subscribers.clear();
singleshot.clear();
Post(new EventBusReadyEvent());
}
}

View file

@ -0,0 +1,15 @@
package dev.zontreck.eventsbus;
/**
* Event priority level.
* <p>
* The higher the priority, the sooner it gets executed. High is executed after
* Highest.
*/
public enum PriorityLevel {
HIGHEST,
HIGH,
MEDIUM,
LOW,
LOWEST
}

View file

@ -0,0 +1,11 @@
package dev.zontreck.eventsbus.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(value = RetentionPolicy.RUNTIME)
@Target(value = ElementType.TYPE)
public @interface Cancellable {
}

View file

@ -0,0 +1,11 @@
package dev.zontreck.eventsbus.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(value = RetentionPolicy.RUNTIME)
@Target(value = ElementType.TYPE)
public @interface EventSubscriber {
}

View file

@ -0,0 +1,14 @@
package dev.zontreck.eventsbus.annotations;
import dev.zontreck.eventsbus.PriorityLevel;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(value = RetentionPolicy.RUNTIME)
@Target(value = ElementType.METHOD)
public @interface Priority {
PriorityLevel Level();
}

View file

@ -0,0 +1,11 @@
package dev.zontreck.eventsbus.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(value = RetentionPolicy.RUNTIME)
@Target(value = ElementType.METHOD)
public @interface SingleshotEvent {
}

View file

@ -0,0 +1,18 @@
package dev.zontreck.eventsbus.annotations;
import dev.zontreck.eventsbus.Event;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(value = RetentionPolicy.RUNTIME)
@Target(value = ElementType.METHOD)
public @interface Subscribe {
/**
* Marks that the subscribed method will not receive the signal if the event was cancelled with {@link Event#setCancelled(boolean)}
*/
boolean allowCancelled();
}

View file

@ -0,0 +1,11 @@
package dev.zontreck.eventsbus.events;
import dev.zontreck.eventsbus.Event;
/**
* This event is sent out when the Event Bus is ready.
* <p>
* This is also dispatched when a reset occurs, prior to clearing the lists.
*/
public class EventBusReadyEvent extends Event {
}

View file

@ -0,0 +1,17 @@
package dev.zontreck.eventsbus.events;
import dev.zontreck.eventsbus.annotations.Cancellable;
import dev.zontreck.eventsbus.Event;
/**
* Posted when the event bus is about to be reset.
* <p>
* This event can be cancelled to prevent the reset.
* <p>
* The default behavior is: Allow Reset.
* <p>
* Recommended that handlers be implemented to re-register instances, and classes when a reset occurs.
*/
@Cancellable
public class ResetEventBusEvent extends Event {
}

View file

@ -0,0 +1,6 @@
package dev.zontreck.eventsbus.events;
import dev.zontreck.eventsbus.Event;
public class TickEvent extends Event {
}

View file