Skip to content

Commit

Permalink
Add API events system
Browse files Browse the repository at this point in the history
  • Loading branch information
ajgeiss0702 committed Jun 9, 2023
1 parent 2414c69 commit 0899bf8
Show file tree
Hide file tree
Showing 17 changed files with 306 additions and 6 deletions.
46 changes: 46 additions & 0 deletions .github/workflows/javadocs.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
name: JavaDocs Generation

on:
push:
branches: ["master"]

# Allows you to run this workflow manually from the Actions tab
workflow_dispatch:

permissions:
contents: read
pages: write
id-token: write

jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v3
- name: Setup Pages
uses: actions/configure-pages@v3
- name: Set up JDK 11
uses: actions/setup-java@v2
with:
java-version: '11'
distribution: 'temurin'
- name: Build with Gradle
uses: gradle/gradle-build-action@937999e9cc2425eddc7fd62d1053baf041147db7
with:
arguments: :api:javadoc
- name: Upload artifact
uses: actions/upload-pages-artifact@v1
with:
path: 'api/build/docs/javadoc'

deploy:
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
runs-on: ubuntu-latest
needs: build
steps:
- name: Deploy to GitHub Pages
id: deployment
uses: actions/deploy-pages@v2
3 changes: 3 additions & 0 deletions api/src/main/java/us/ajg0702/queue/api/AjQueueAPI.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package us.ajg0702.queue.api;

import us.ajg0702.queue.api.events.utils.EventReceiver;
import us.ajg0702.queue.api.premium.Logic;
import us.ajg0702.queue.api.premium.LogicGetter;
import us.ajg0702.queue.api.spigot.AjQueueSpigotAPI;
Expand Down Expand Up @@ -114,5 +115,7 @@ public static AjQueueSpigotAPI getSpigotInstance() {
*/
public abstract void shutdown();

public abstract <E> void listen(Class<E> event, EventReceiver<E> handler);

public abstract ExecutorService getServersUpdateExecutor();
}
15 changes: 15 additions & 0 deletions api/src/main/java/us/ajg0702/queue/api/events/Cancellable.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package us.ajg0702.queue.api.events;

public interface Cancellable {
/**
* Whether this event is canceled.
* @return True if canceled. False if not.
*/
boolean isCancelled();

/**
* Allows you to cancel or un-cancel this event
* @param cancelled True to cancel the event, false to un-cancel
*/
void setCancelled(boolean cancelled);
}
4 changes: 4 additions & 0 deletions api/src/main/java/us/ajg0702/queue/api/events/Event.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
package us.ajg0702.queue.api.events;

public interface Event {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package us.ajg0702.queue.api.events;

import org.jetbrains.annotations.Nullable;
import us.ajg0702.queue.api.players.AdaptedPlayer;
import us.ajg0702.queue.api.players.QueuePlayer;
import us.ajg0702.queue.api.queues.QueueServer;

/**
* Called when someone is added or removed from a queue that the player is in, causing the player's position to change
*/
public class PositionChangeEvent implements Event {
private final QueuePlayer player;
private final int position;

public PositionChangeEvent(QueuePlayer player) {
this.player = player;
position = player.getPosition();
}

/**
* Gets the QueuePlayer object that represents this player
* @return the QueuePlayer object
*/
public QueuePlayer getQueuePlayer() {
return player;
}

/**
* Gets the AdaptedPlayer that this event is about. May return null!
* @return The AdaptedPlayer that this event is about. Returns null if the player is offline.
*/
public @Nullable AdaptedPlayer getPlayer() {
return player.getPlayer();
}

/**
* Gets the player's new position in the queue
* @return The player's new position. 1 being 1st, 2 being 2nd, etc
*/
public int getPosition() {
return position;
}

/**
* Gets the queue that this event is from
* @return The QueueServer that the player is in that their position changed
*/
public QueueServer getQueue() {
return player.getQueueServer();
}
}
45 changes: 45 additions & 0 deletions api/src/main/java/us/ajg0702/queue/api/events/PreQueueEvent.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package us.ajg0702.queue.api.events;

import us.ajg0702.queue.api.players.AdaptedPlayer;
import us.ajg0702.queue.api.queues.QueueServer;

/**
* Called after all checks are made, right before a player is actually added to the queue.
* If canceled, the player will not be added to the queue.
* If you cancel this event, it is up to you to send a message telling the player why they were not added to the queue.
*/
public class PreQueueEvent implements Event, Cancellable {
private final AdaptedPlayer player;
private final QueueServer target;

private boolean cancelled = false;

public PreQueueEvent(AdaptedPlayer player, QueueServer target) {
this.player = player;
this.target = target;
}

/**
* Gets the player that is joining the queue
* @return
*/
public AdaptedPlayer getPlayer() {
return player;
}

/**
* Gets the target QueueServer that the player is trying to queue for
* @return The QueueServer that the player is trying to queue for
*/
public QueueServer getTarget() {
return target;
}

public boolean isCancelled() {
return cancelled;
}

public void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package us.ajg0702.queue.api.events;

import us.ajg0702.queue.api.players.AdaptedPlayer;
import us.ajg0702.queue.api.players.QueuePlayer;
import us.ajg0702.queue.api.server.AdaptedServer;

/**
* Called after a player is successfully sent to a server.
*/
public class SuccessfulSendEvent implements Event {
private final QueuePlayer player;
private final AdaptedServer server;

public SuccessfulSendEvent(QueuePlayer player, AdaptedServer server) {
this.player = player;
this.server = server;
}

/**
* Gets the player that was sent
* @return the player that was sent
*/
public AdaptedPlayer getPlayer() {
return player.getPlayer();
}

/**
* Gets the server that the player was sent to
* @return The server that the player was sent to
*/
public AdaptedServer getServer() {
return server;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package us.ajg0702.queue.api.events.utils;

@FunctionalInterface
public interface EventReceiver<E> {
void execute(E event);
}
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,12 @@ public interface AdaptedPlayer extends Handle, Audience {
*/
String getServerName();

/**
* Gets the server that the player is currently connected to
* @return The server that the player is currently connected to.
*/
AdaptedServer getCurrentServer();

/**
* Gets the player's unique id (UUID)
* @return The player's uuid
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer;
import org.jetbrains.annotations.NotNull;
import us.ajg0702.queue.api.EventHandler;
import us.ajg0702.queue.api.events.SuccessfulSendEvent;
import us.ajg0702.queue.api.players.AdaptedPlayer;
import us.ajg0702.queue.api.players.QueuePlayer;
import us.ajg0702.queue.api.queues.QueueServer;
Expand Down Expand Up @@ -87,6 +88,9 @@ public void onPlayerJoinServer(AdaptedPlayer player) {
server.removePlayer(player);
server.setLastSentTime(System.currentTimeMillis());
main.getQueueManager().getSendingAttempts().remove(queuePlayer);
main.getTaskManager().runNow(() -> {
main.call(new SuccessfulSendEvent(queuePlayer, player.getCurrentServer()));
});
}
}

Expand Down
30 changes: 29 additions & 1 deletion common/src/main/java/us/ajg0702/queue/common/QueueMain.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

import org.spongepowered.configurate.ConfigurateException;
import us.ajg0702.queue.api.*;
import us.ajg0702.queue.api.events.Event;
import us.ajg0702.queue.api.events.utils.EventReceiver;
import us.ajg0702.queue.api.premium.Logic;
import us.ajg0702.queue.api.premium.LogicGetter;
import us.ajg0702.queue.api.util.QueueLogger;
Expand All @@ -12,7 +14,8 @@
import us.ajg0702.utils.common.Updater;

import java.io.File;
import java.util.LinkedHashMap;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.regex.Pattern;

Expand Down Expand Up @@ -124,6 +127,31 @@ public void shutdown() {
updater.shutdown();
}


private final Map<Class<?>, ArrayList<EventReceiver<Event>>> listeners = new ConcurrentHashMap<>();

@SuppressWarnings("unchecked")
@Override
public <E> void listen(Class<E> event, EventReceiver<E> handler) {
if(!Arrays.asList(event.getInterfaces()).contains(Event.class)) {
throw new IllegalArgumentException("You can only listen to ajQueue events!");
}
List<EventReceiver<Event>> existingList = listeners.computeIfAbsent(event, (k) -> new ArrayList<>());
existingList.add((e) -> handler.execute((E) e));
}

public void call(Event event) {
List<EventReceiver<Event>> list = listeners.computeIfAbsent(event.getClass(), (k) -> new ArrayList<>());
list.forEach(eventReceiver -> {
try {
eventReceiver.execute(event);
} catch(Exception e) {
logger.severe("An external plugin threw an error while handling an event (this is probably not the fault of ajQueue!)", e);
}
});

}

@Override
public ExecutorService getServersUpdateExecutor() {
return taskManager.getServersUpdateExecutor();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import net.kyori.adventure.text.Component;
import net.kyori.adventure.title.Title;
import us.ajg0702.queue.api.QueueManager;
import us.ajg0702.queue.api.events.PreQueueEvent;
import us.ajg0702.queue.api.players.AdaptedPlayer;
import us.ajg0702.queue.api.players.QueuePlayer;
import us.ajg0702.queue.api.premium.Logic;
Expand Down Expand Up @@ -208,6 +209,14 @@ public boolean addToQueue(AdaptedPlayer player, QueueServer server) {
}
}


PreQueueEvent preQueueEvent = new PreQueueEvent(player, server);
main.call(preQueueEvent);
if(preQueueEvent.isCancelled()) return false;


// Player should be added!

ImmutableList<QueuePlayer> list = server.getQueue();
QueuePlayer queuePlayer;
AdaptedServer ideal = server.getIdealServer(player);
Expand Down
13 changes: 9 additions & 4 deletions common/src/main/java/us/ajg0702/queue/common/TaskManager.java
Original file line number Diff line number Diff line change
@@ -1,16 +1,17 @@
package us.ajg0702.queue.common;

import us.ajg0702.queue.common.utils.QueueThreadFactory;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.*;

public class TaskManager {


final ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
final ScheduledExecutorService updateExecutor = Executors.newScheduledThreadPool(1);

final ExecutorService serversUpdateExecutor = Executors.newCachedThreadPool();
final ScheduledExecutorService executor = Executors.newScheduledThreadPool(1, new QueueThreadFactory("GENERIC"));
final ScheduledExecutorService updateExecutor = Executors.newScheduledThreadPool(1, new QueueThreadFactory("UPDATE-EXECUTOR"));
final ExecutorService serversUpdateExecutor = Executors.newCachedThreadPool(new QueueThreadFactory("SERVER-UPDATE"));

final QueueMain main;
public TaskManager(QueueMain main) {
Expand Down Expand Up @@ -128,6 +129,10 @@ public ScheduledFuture<?> runLater(Runnable runnable, long delay, TimeUnit unit)
return executor.schedule(runnable, delay, unit);
}

public Future<?> runNow(Runnable runnable) {
return executor.submit(runnable);
}


private ScheduledFuture<?> scheduleAtFixedRate(ScheduledExecutorService executor, Runnable command, long initialDelay, long period, TimeUnit unit) {
return executor.scheduleAtFixedRate(() -> {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package us.ajg0702.queue.common.queues;

import com.google.common.collect.ImmutableList;
import us.ajg0702.queue.api.events.PositionChangeEvent;
import us.ajg0702.queue.api.players.AdaptedPlayer;
import us.ajg0702.queue.api.players.QueuePlayer;
import us.ajg0702.queue.api.queues.Balancer;
Expand Down Expand Up @@ -203,6 +204,7 @@ public boolean isPaused() {
public synchronized void removePlayer(QueuePlayer player) {
main.getQueueManager().getSendingAttempts().remove(player);
queue.remove(player);
positionChange();
}

@Override
Expand All @@ -226,6 +228,7 @@ public synchronized void addPlayer(QueuePlayer player, int position) {
} else {
queue.add(player);
}
positionChange();
}

@Override
Expand Down Expand Up @@ -316,4 +319,10 @@ public Balancer getBalancer() {
return balancer;
}

private void positionChange() {
main.getTaskManager().runNow(
() -> queue.forEach(queuePlayer -> main.call(new PositionChangeEvent(queuePlayer)))
);
}

}
Loading

0 comments on commit 0899bf8

Please sign in to comment.