New task system & improve DB case-insensitive SELECTs, support fabric 1.20.1 (#433)

This commit is contained in:
William authored and GitHub committed 2023-06-16 12:19:31 +01:00
1 parent d4b37e3677
commit fb052340c0
27 files changed
+687 -505

No files matched your search

+2 -2
View File
@@ -71,7 +71,7 @@ jobs:
1.17.1
1.18.2
1.19.4
1.20
1.20.1
java: 16
- name: Upload to Modrinth (Sponge)
uses: WiIIiam278/mc-publish@hangar
@@ -115,7 +115,7 @@ jobs:
loaders: |
fabric
game-versions: |
1.20
1.20.1
java: 17
- name: Upload GitHub Artifact (Spigot)
uses: actions/upload-artifact@v2
+2 -2
View File
@@ -59,7 +59,7 @@ jobs:
1.17.1
1.18.2
1.19.4
1.20
1.20.1
java: 16
- name: Upload to Modrinth (Sponge)
uses: WiIIiam278/mc-publish@hangar
@@ -103,7 +103,7 @@ jobs:
loaders: |
fabric
game-versions: |
1.20
1.20.1
java: 17
- name: Upload GitHub Artifact (Spigot)
uses: actions/upload-artifact@v2
+11 -1
View File
@@ -15,10 +15,16 @@ defaultTasks 'licenseFormat', 'build'
ext {
set 'version', version.toString()
set 'description', description.toString()
set 'jedis_version', jedis_version.toString()
set 'sqlite_driver_version', sqlite_driver_version.toString()
set 'mysql_driver_version', mysql_driver_version.toString()
set 'description', description.toString()
set 'fabric_minecraft_version', fabric_minecraft_version.toString()
set 'fabric_yarn_mappings', fabric_yarn_mappings.toString()
set 'fabric_loader_version', fabric_loader_version.toString()
set 'fabric_api_version', fabric_api_version.toString()
}
allprojects {
@@ -34,6 +40,10 @@ allprojects {
repositories {
mavenLocal()
mavenCentral()
maven {
url 'https://s01.oss.sonatype.org/content/repositories/snapshots/'
mavenContent { snapshotsOnly() }
}
maven { url 'https://maven.fabricmc.net/' }
maven { url 'https://libraries.minecraft.net/' }
maven { url 'https://api.modrinth.com/maven' }
@@ -65,23 +65,21 @@ import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import space.arim.morepaperlib.MorePaperLib;
import space.arim.morepaperlib.scheduling.GracefulScheduling;
import space.arim.morepaperlib.scheduling.ScheduledTask;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.stream.Collectors;
public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTaskRunner, BukkitEventDispatcher, PluginMessageListener, BukkitSafetyResolver {
public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask.Supplier, BukkitEventDispatcher,
PluginMessageListener, BukkitSafetyResolver {
/**
* Metrics ID for <a href="https://bstats.org/plugin/bukkit/HuskHomes/8430">HuskHomes on Bukkit</a>.
*/
private static final int METRICS_ID = 8430;
private ConcurrentHashMap<UUID, ScheduledTask> tasks;
private Set<SavedUser> savedUsers;
private Settings settings;
private Locales locales;
@@ -130,7 +128,6 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask
// Create adventure audience
this.audiences = BukkitAudiences.create(this);
this.paperLib = new MorePaperLib(this);
this.tasks = new ConcurrentHashMap<>();
this.savedUsers = new HashSet<>();
this.globalPlayerList = new HashMap<>();
this.currentlyOnWarmup = new HashSet<>();
@@ -257,7 +254,7 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask
audiences.close();
audiences = null;
}
cancelAllTasks();
cancelTasks();
}
/**
@@ -485,23 +482,16 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask
@Override
public void onPluginMessageReceived(@NotNull String channel, @NotNull Player player, byte[] message) {
if (broker != null && broker instanceof PluginMessageBroker pluginMessenger
&& getSettings().getBrokerType() == Broker.Type.PLUGIN_MESSAGE) {
&& getSettings().getBrokerType() == Broker.Type.PLUGIN_MESSAGE) {
pluginMessenger.onReceive(channel, BukkitUser.adapt(player), message);
}
}
@Override
@NotNull
public GracefulScheduling getScheduler() {
return paperLib.scheduling();
}
@Override
@NotNull
public ConcurrentHashMap<UUID, ScheduledTask> getTasks() {
return tasks;
}
@Override
@NotNull
public HuskHomes getPlugin() {
@@ -35,7 +35,6 @@ import java.util.List;
public interface BukkitEventDispatcher extends EventDispatcher {
@Override
default <T extends Event> boolean fireIsCancelled(@NotNull T event) {
Bukkit.getPluginManager().callEvent((org.bukkit.event.Event) event);
@@ -0,0 +1,141 @@
/*
* This file is part of HuskHomes, licensed under the Apache License 2.0.
*
* Copyright (c) William278 <[email protected]>
* Copyright (c) contributors
*
* 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
*
* http://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.
*/
package net.william278.huskhomes.util;
import net.william278.huskhomes.BukkitHuskHomes;
import net.william278.huskhomes.HuskHomes;
import org.jetbrains.annotations.NotNull;
import space.arim.morepaperlib.scheduling.GracefulScheduling;
import space.arim.morepaperlib.scheduling.ScheduledTask;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
public interface BukkitTask extends Task {
class Sync extends Task.Sync implements BukkitTask {
private ScheduledTask task;
protected Sync(@NotNull HuskHomes plugin, @NotNull Runnable runnable, long delayTicks) {
super(plugin, runnable, delayTicks);
}
@Override
public void cancel() {
if (task != null && !cancelled) {
task.cancel();
}
super.cancel();
}
@Override
public void run() {
if (delayTicks > 0) {
this.task = getScheduler().globalRegionalScheduler().runDelayed(runnable, delayTicks);
} else {
this.task = getScheduler().globalRegionalScheduler().run(runnable);
}
}
}
class Async extends Task.Async implements BukkitTask {
private ScheduledTask task;
protected Async(@NotNull HuskHomes plugin, @NotNull Runnable runnable) {
super(plugin, runnable);
}
@Override
public void cancel() {
if (task != null && !cancelled) {
task.cancel();
}
super.cancel();
}
@Override
public void run() {
if (!cancelled) {
this.task = getScheduler().asyncScheduler().run(runnable);
}
}
}
class Repeating extends Task.Repeating implements BukkitTask {
private ScheduledTask task;
protected Repeating(@NotNull HuskHomes plugin, @NotNull Runnable runnable, long repeatingTicks) {
super(plugin, runnable, repeatingTicks);
}
@Override
public void cancel() {
if (task != null && !cancelled) {
task.cancel();
}
super.cancel();
}
@Override
public void run() {
if (!cancelled) {
this.task = getScheduler().asyncScheduler().runAtFixedRate(runnable, Duration.ZERO, Duration
.of(repeatingTicks * 50L, ChronoUnit.MILLIS)
);
}
}
}
interface Supplier extends Task.Supplier {
@NotNull
@Override
default Task.Sync getSyncTask(@NotNull Runnable runnable, long delayTicks) {
return new Sync(getPlugin(), runnable, delayTicks);
}
@NotNull
@Override
default Task.Async getAsyncTask(@NotNull Runnable runnable) {
return new Async(getPlugin(), runnable);
}
@NotNull
@Override
default Task.Repeating getRepeatingTask(@NotNull Runnable runnable, long repeatingTicks) {
return new Repeating(getPlugin(), runnable, repeatingTicks);
}
@Override
default void cancelTasks() {
((BukkitHuskHomes) getPlugin()).getScheduler().cancelGlobalTasks();
}
}
@NotNull
default GracefulScheduling getScheduler() {
return ((BukkitHuskHomes) getPlugin()).getScheduler();
}
}
@@ -1,95 +0,0 @@
/*
* This file is part of HuskHomes, licensed under the Apache License 2.0.
*
* Copyright (c) William278 <[email protected]>
* Copyright (c) contributors
*
* 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
*
* http://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.
*/
package net.william278.huskhomes.util;
import org.jetbrains.annotations.NotNull;
import space.arim.morepaperlib.scheduling.GracefulScheduling;
import space.arim.morepaperlib.scheduling.ScheduledTask;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Supplier;
public interface BukkitTaskRunner extends TaskRunner {
@Override
default void runAsync(@NotNull Runnable runnable) {
getScheduler().asyncScheduler().run(runnable);
}
@Override
default <T> CompletableFuture<T> supplyAsync(@NotNull Supplier<T> supplier) {
final CompletableFuture<T> future = new CompletableFuture<>();
getScheduler().asyncScheduler().run(() -> future.complete(supplier.get()));
return future;
}
@Override
default void runSync(@NotNull Runnable runnable) {
getScheduler().globalRegionalScheduler().run(runnable);
}
@NotNull
@Override
default UUID runAsyncRepeating(@NotNull Runnable runnable, long period) {
final UUID taskId = UUID.randomUUID();
getTasks().put(taskId, getScheduler().asyncScheduler().runAtFixedRate(
runnable, Duration.ZERO, getDurationTicks(period))
);
return taskId;
}
@Override
default void runLater(@NotNull Runnable runnable, long delay) {
getScheduler().asyncScheduler().runDelayed(runnable, getDurationTicks(delay));
}
@Override
default void cancelTask(@NotNull UUID taskId) {
getTasks().computeIfPresent(taskId, (id, task) -> {
task.cancel();
return null;
});
getTasks().remove(taskId);
}
@Override
default void cancelAllTasks() {
getScheduler().cancelGlobalTasks();
getTasks().values().forEach(ScheduledTask::cancel);
getTasks().clear();
}
@NotNull
GracefulScheduling getScheduler();
@NotNull
@Override
ConcurrentHashMap<UUID, ScheduledTask> getTasks();
@NotNull
default Duration getDurationTicks(long ticks) {
return Duration.of(ticks * 50, ChronoUnit.MILLIS);
}
}
+2 -2
View File
@@ -7,7 +7,7 @@ test {
}
dependencies {
api 'commons-io:commons-io:2.12.0'
api 'commons-io:commons-io:2.13.0'
api 'org.apache.commons:commons-text:1.10.0'
api 'de.themoep:minedown-adventure:1.7.2-SNAPSHOT'
api 'com.google.code.gson:gson:2.10.1'
@@ -25,7 +25,7 @@ dependencies {
compileOnly 'com.mysql:mysql-connector-j:' + mysql_driver_version
compileOnly 'org.jetbrains:annotations:24.0.1'
compileOnly 'com.google.guava:guava:32.0.0-jre'
compileOnly 'com.google.guava:guava:32.0.1-jre'
compileOnly 'com.github.plan-player-analytics:Plan:5.5.2391'
compileOnly 'com.github.BlueMap-Minecraft:BlueMapAPI:2.5.0'
compileOnly 'us.dynmap:DynmapCoreAPI:3.4'
@@ -63,7 +63,7 @@ import java.util.stream.Stream;
/**
* Represents a cross-platform instance of the plugin
*/
public interface HuskHomes extends TaskRunner, EventDispatcher, SafetyResolver, TransactionResolver {
public interface HuskHomes extends Task.Supplier, EventDispatcher, SafetyResolver, TransactionResolver {
int SPIGOT_RESOURCE_ID = 83767;
@@ -428,9 +428,11 @@ public class MySqlDatabase extends Database {
INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id`
INNER JOIN `%players_table%` ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid`
WHERE `owner_uuid`=?
""" + (caseInsensitive ? "AND UPPER(`name`) LIKE UPPER(?);" : "AND `name`=?;")))) {
AND ((? AND UPPER(`name`) LIKE UPPER(?)) OR (`name`=?))"""))) {
statement.setString(1, user.getUuid().toString());
statement.setString(2, homeName);
statement.setBoolean(2, caseInsensitive);
statement.setString(3, homeName);
statement.setString(4, homeName);
final ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
@@ -503,8 +505,10 @@ public class MySqlDatabase extends Database {
FROM `%warps_table%`
INNER JOIN `%saved_positions_table%` ON `%warps_table%`.`saved_position_id`=`%saved_positions_table%`.`id`
INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id`
""" + (caseInsensitive ? "WHERE UPPER(`name`) LIKE UPPER(?);" : "WHERE `name`=?;")))) {
statement.setString(1, warpName);
AND ((? AND UPPER(`name`) LIKE UPPER(?)) OR (`name`=?))"""))) {
statement.setBoolean(1, caseInsensitive);
statement.setString(2, warpName);
statement.setString(3, warpName);
final ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
@@ -433,15 +433,17 @@ public class SqLiteDatabase extends Database {
public Optional<Home> getHome(@NotNull User user, @NotNull String homeName, boolean caseInsensitive) {
try {
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `public`
FROM `%homes_table%`
INNER JOIN `%saved_positions_table%` ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id`
INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id`
INNER JOIN `%players_table%` ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid`
WHERE `owner_uuid`=?
""" + (caseInsensitive ? "AND UPPER(`name`) LIKE UPPER(?);" : "AND `name`=?;")))) {
SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `public`
FROM `%homes_table%`
INNER JOIN `%saved_positions_table%` ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id`
INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id`
INNER JOIN `%players_table%` ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid`
WHERE `owner_uuid`=?
AND ((? AND UPPER(`name`) LIKE UPPER(?)) OR (`name`=?))"""))) {
statement.setString(1, user.getUuid().toString());
statement.setString(2, homeName);
statement.setBoolean(2, caseInsensitive);
statement.setString(3, homeName);
statement.setString(4, homeName);
final ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
@@ -510,12 +512,14 @@ public class SqLiteDatabase extends Database {
public Optional<Warp> getWarp(@NotNull String warpName, boolean caseInsensitive) {
try {
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
SELECT `%warps_table%`.`uuid` AS `warp_uuid`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`
FROM `%warps_table%`
INNER JOIN `%saved_positions_table%` ON `%warps_table%`.`saved_position_id`=`%saved_positions_table%`.`id`
INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id`
""" + (caseInsensitive ? "WHERE UPPER(`name`) LIKE UPPER(?);" : "WHERE `name`=?;")))) {
statement.setString(1, warpName);
SELECT `%warps_table%`.`uuid` AS `warp_uuid`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`
FROM `%warps_table%`
INNER JOIN `%saved_positions_table%` ON `%warps_table%`.`saved_position_id`=`%saved_positions_table%`.`id`
INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id`
AND ((? AND UPPER(`name`) LIKE UPPER(?)) OR (`name`=?))"""))) {
statement.setBoolean(1, caseInsensitive);
statement.setString(2, warpName);
statement.setString(3, warpName);
final ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
@@ -64,7 +64,7 @@ public class EventListener {
this.handleInboundTeleport(onlineUser);
// Synchronize the global player list
plugin.runLater(() -> this.synchronizeGlobalPlayerList(onlineUser, plugin.getLocalPlayerList()), 40L);
plugin.runSyncDelayed(() -> this.synchronizeGlobalPlayerList(onlineUser, plugin.getLocalPlayerList()), 40L);
// Request updated player lists from other servers
if (plugin.getOnlineUsers().size() == 1) {
@@ -122,7 +122,7 @@ public class EventListener {
if (bedPosition.isEmpty()) {
plugin.getSpawn().ifPresent(spawn -> {
if (plugin.getSettings().doCrossServer() && !spawn.getServer().equals(plugin.getServerName())) {
plugin.runLater(() -> {
plugin.runSyncDelayed(() -> {
try {
Teleport.builder(plugin)
.teleporter(teleporter)
@@ -25,11 +25,10 @@ import net.william278.huskhomes.config.Settings;
import net.william278.huskhomes.hook.EconomyHook;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.util.Task;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicReference;
/**
* Represents a {@link Teleport} that has an associated warmup time; the teleport will not be performed until the
@@ -37,12 +36,13 @@ import java.util.concurrent.atomic.AtomicReference;
*
* @see Teleport#builder(HuskHomes)
*/
public class TimedTeleport extends Teleport {
public class TimedTeleport extends Teleport implements Runnable {
public static final String BYPASS_PERMISSION = "huskhomes.bypass_teleport_warmup";
private final OnlineUser teleporter;
private final Position startLocation;
private final double startHealth;
private Task.Repeating task;
private int timeLeft;
protected TimedTeleport(@NotNull OnlineUser executor, @NotNull OnlineUser teleporter, @NotNull Target target,
@@ -88,34 +88,36 @@ public class TimedTeleport extends Teleport {
.ifPresent(teleporter::sendMessage);
// Run the warmup
final AtomicReference<UUID> warmupTaskId = new AtomicReference<>();
final Runnable countdownRunnable = (() -> {
// Display a countdown action bar message
if (timeLeft > 0) {
plugin.getSettings().getSoundEffect(Settings.SoundEffectAction.TELEPORTATION_WARMUP)
.ifPresent(teleporter::playSound);
plugin.getLocales().getLocale("teleporting_action_bar_warmup", Integer.toString(timeLeft))
.ifPresent(this::sendStatusMessage);
} else {
plugin.getLocales().getLocale("teleporting_action_bar_processing")
.ifPresent(this::sendStatusMessage);
try {
super.execute();
} catch (TeleportationException e) {
e.displayMessage(teleporter, plugin);
}
}
// Tick (decrement) the timed teleport timer and end it if done
if (tickAndGetIfDone()) {
plugin.getCurrentlyOnWarmup().remove(teleporter.getUuid());
plugin.cancelTask(warmupTaskId.get());
}
});
warmupTaskId.set(plugin.runAsyncRepeating(countdownRunnable, 20L));
this.task = plugin.getRepeatingTask(this, 20L);
this.task.run();
});
}
@Override
public void run() {
// Display a countdown action bar message
if (timeLeft > 0) {
plugin.getSettings().getSoundEffect(Settings.SoundEffectAction.TELEPORTATION_WARMUP)
.ifPresent(teleporter::playSound);
plugin.getLocales().getLocale("teleporting_action_bar_warmup", Integer.toString(timeLeft))
.ifPresent(this::sendStatusMessage);
} else {
plugin.getLocales().getLocale("teleporting_action_bar_processing")
.ifPresent(this::sendStatusMessage);
try {
super.execute();
} catch (TeleportationException e) {
e.displayMessage(teleporter, plugin);
}
}
// Tick (decrement) the timed teleport timer and end it if done
if (tickAndGetIfDone()) {
task.cancel();
plugin.getCurrentlyOnWarmup().remove(teleporter.getUuid());
}
}
/**
* Ticks a timed teleport, decrementing the time left until the teleport is complete
* <p>
@@ -90,7 +90,7 @@ public abstract class OnlineUser extends User implements Teleportable, CommandUs
* @param mineDown the parsed {@link MineDown} to send
* @param subTitle whether to send the title as a subtitle ({@code true} for a subtitle, {@code false} for a title)
*/
public final void sendTitle(@NotNull MineDown mineDown, boolean subTitle) {
public void sendTitle(@NotNull MineDown mineDown, boolean subTitle) {
getAudience().sendTitlePart(subTitle ? TitlePart.SUBTITLE : TitlePart.TITLE, mineDown
.disable(MineDownParser.Option.SIMPLE_FORMATTING)
.replace().toComponent());
@@ -101,7 +101,7 @@ public abstract class OnlineUser extends User implements Teleportable, CommandUs
*
* @param mineDown the parsed {@link MineDown} to send
*/
public final void sendActionBar(@NotNull MineDown mineDown) {
public void sendActionBar(@NotNull MineDown mineDown) {
getAudience().sendActionBar(mineDown
.disable(MineDownParser.Option.SIMPLE_FORMATTING)
.replace().toComponent());
@@ -113,7 +113,7 @@ public abstract class OnlineUser extends User implements Teleportable, CommandUs
*
* @param mineDown the parsed {@link MineDown} to send
*/
public final void sendMessage(@NotNull MineDown mineDown) {
public void sendMessage(@NotNull MineDown mineDown) {
getAudience().sendMessage(mineDown
.disable(MineDownParser.Option.SIMPLE_FORMATTING)
.replace().toComponent());
@@ -125,7 +125,7 @@ public abstract class OnlineUser extends User implements Teleportable, CommandUs
* @param mineDown the parsed {@link MineDown} to send
* @param slot the {@link Locales.DisplaySlot} to send the message to
*/
public final void sendMessage(@NotNull MineDown mineDown, @NotNull Locales.DisplaySlot slot) {
public void sendMessage(@NotNull MineDown mineDown, @NotNull Locales.DisplaySlot slot) {
if (slot == Locales.DisplaySlot.CHAT) {
sendMessage(mineDown);
} else if (slot == Locales.DisplaySlot.ACTION_BAR) {
@@ -144,7 +144,7 @@ public abstract class OnlineUser extends User implements Teleportable, CommandUs
* @implNote This method is intended for use with Minecraft's built-in translation keys. If the key is invalid,
* it will be substituted with {@code minecraft:block.minecraft.spawn.not_valid}
*/
public final void sendTranslatableMessage(@Subst(Key.MINECRAFT_NAMESPACE + "block.minecraft.spawn.not_valid")
public void sendTranslatableMessage(@Subst(Key.MINECRAFT_NAMESPACE + "block.minecraft.spawn.not_valid")
@NotNull String translationKey) {
getAudience().sendMessage(Component.translatable(translationKey));
}
@@ -155,7 +155,7 @@ public abstract class OnlineUser extends User implements Teleportable, CommandUs
* @param soundEffect the sound effect to play. If the sound name is invalid, the sound will not play
* @implNote If the key is invalid, it will be substituted with {@code minecraft:block.note_block.banjo}
*/
public final void playSound(@Subst(Key.MINECRAFT_NAMESPACE + "block.note_block.banjo")
public void playSound(@Subst(Key.MINECRAFT_NAMESPACE + "block.note_block.banjo")
@NotNull String soundEffect) throws IllegalArgumentException {
try {
getAudience().playSound(
@@ -0,0 +1,135 @@
/*
* This file is part of HuskHomes, licensed under the Apache License 2.0.
*
* Copyright (c) William278 <[email protected]>
* Copyright (c) contributors
*
* 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
*
* http://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.
*/
package net.william278.huskhomes.util;
import net.william278.huskhomes.HuskHomes;
import org.jetbrains.annotations.NotNull;
import java.util.concurrent.CompletableFuture;
public interface Task extends Runnable {
abstract class Base implements Task {
protected final HuskHomes plugin;
protected final Runnable runnable;
protected boolean cancelled = false;
protected Base(@NotNull HuskHomes plugin, @NotNull Runnable runnable) {
this.plugin = plugin;
this.runnable = runnable;
}
public void cancel() {
cancelled = true;
}
@NotNull
@Override
public HuskHomes getPlugin() {
return plugin;
}
}
abstract class Async extends Base {
protected Async(@NotNull HuskHomes plugin, @NotNull Runnable runnable) {
super(plugin, runnable);
}
}
abstract class Sync extends Base {
protected long delayTicks;
protected Sync(@NotNull HuskHomes plugin, @NotNull Runnable runnable, long delayTicks) {
super(plugin, runnable);
this.delayTicks = delayTicks;
}
}
abstract class Repeating extends Base {
protected final long repeatingTicks;
protected Repeating(@NotNull HuskHomes plugin, @NotNull Runnable runnable, long repeatingTicks) {
super(plugin, runnable);
this.repeatingTicks = repeatingTicks;
}
}
@SuppressWarnings("UnusedReturnValue")
interface Supplier {
@NotNull
Task.Sync getSyncTask(@NotNull Runnable runnable, long delayTicks);
@NotNull
Task.Async getAsyncTask(@NotNull Runnable runnable);
@NotNull
Task.Repeating getRepeatingTask(@NotNull Runnable runnable, long repeatingTicks);
@NotNull
default Task.Sync runSyncDelayed(@NotNull Runnable runnable, long delayTicks) {
final Task.Sync task = getSyncTask(runnable, delayTicks);
task.run();
return task;
}
@NotNull
default Task.Sync runSync(@NotNull Runnable runnable) {
return runSyncDelayed(runnable, 0);
}
@NotNull
default Task.Async runAsync(@NotNull Runnable runnable) {
final Task.Async task = getAsyncTask(runnable);
task.run();
return task;
}
default <T> CompletableFuture<T> supplyAsync(@NotNull java.util.function.Supplier<T> supplier) {
final CompletableFuture<T> future = new CompletableFuture<>();
runAsync(() -> {
try {
future.complete(supplier.get());
} catch (Throwable throwable) {
future.completeExceptionally(throwable);
}
});
return future;
}
void cancelTasks();
@NotNull
HuskHomes getPlugin();
}
@NotNull
HuskHomes getPlugin();
}
@@ -1,52 +0,0 @@
/*
* This file is part of HuskHomes, licensed under the Apache License 2.0.
*
* Copyright (c) William278 <[email protected]>
* Copyright (c) contributors
*
* 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
*
* http://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.
*/
package net.william278.huskhomes.util;
import net.william278.huskhomes.HuskHomes;
import org.jetbrains.annotations.NotNull;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Supplier;
public interface TaskRunner {
void runAsync(@NotNull Runnable runnable);
<T> CompletableFuture<T> supplyAsync(@NotNull Supplier<T> supplier);
void runSync(@NotNull Runnable runnable);
@NotNull
UUID runAsyncRepeating(@NotNull Runnable runnable, long delay);
void runLater(@NotNull Runnable runnable, long delay);
void cancelTask(@NotNull UUID taskId);
void cancelAllTasks();
@NotNull
ConcurrentHashMap<UUID, ?> getTasks();
@NotNull
HuskHomes getPlugin();
}
+5 -5
View File
@@ -6,9 +6,9 @@ apply plugin: 'fabric-loom'
loom.serverOnlyMinecraftJar()
dependencies {
minecraft 'com.mojang:minecraft:1.20'
mappings 'net.fabricmc:yarn:1.20+build.1:v2'
modImplementation 'net.fabricmc:fabric-loader:0.14.21'
minecraft "com.mojang:minecraft:${fabric_minecraft_version}"
mappings "net.fabricmc:yarn:${fabric_yarn_mappings}:v2"
modImplementation "net.fabricmc:fabric-loader:${fabric_loader_version}"
// Fabric API modules
Set<String> fabricApiModules = [
@@ -19,9 +19,9 @@ dependencies {
'fabric-networking-api-v1'
]
fabricApiModules.forEach {
modImplementation(fabricApi.module(it, '0.83.0+1.20'))
modImplementation(fabricApi.module(it, fabric_api_version))
}
modImplementation include('net.kyori:adventure-platform-fabric:5.8.0')
modImplementation include('net.kyori:adventure-platform-fabric:5.9.0-SNAPSHOT')
modImplementation include('me.lucko:fabric-permissions-api:0.2-SNAPSHOT')
implementation include('redis.clients:jedis:' + jedis_version)
@@ -62,7 +62,7 @@ import net.william278.huskhomes.user.FabricUser;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.user.SavedUser;
import net.william278.huskhomes.util.FabricSafetyResolver;
import net.william278.huskhomes.util.FabricTaskRunner;
import net.william278.huskhomes.util.FabricTask;
import net.william278.huskhomes.util.UnsafeBlocks;
import net.william278.huskhomes.util.Validator;
import org.jetbrains.annotations.NotNull;
@@ -77,13 +77,11 @@ import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.nio.file.Files;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.stream.Collectors;
public class FabricHuskHomes implements DedicatedServerModInitializer, HuskHomes,
FabricTaskRunner, FabricEventDispatcher, FabricSafetyResolver, ServerPlayNetworking.PlayChannelHandler {
public class FabricHuskHomes implements DedicatedServerModInitializer, HuskHomes, FabricTask.Supplier,
FabricEventDispatcher, FabricSafetyResolver, ServerPlayNetworking.PlayChannelHandler {
public static final Logger LOGGER = LoggerFactory.getLogger("HuskHomes");
private static FabricHuskHomes instance;
@@ -93,10 +91,9 @@ public class FabricHuskHomes implements DedicatedServerModInitializer, HuskHomes
return instance;
}
private final ModContainer modContainer = FabricLoader.getInstance()
.getModContainer("huskhomes").orElseThrow(() -> new RuntimeException("Failed to get Mod Container"));
private final ModContainer modContainer = FabricLoader.getInstance().getModContainer("huskhomes")
.orElseThrow(() -> new RuntimeException("Failed to get Mod Container"));
private MinecraftServer minecraftServer;
private ConcurrentHashMap<UUID, CompletableFuture<?>> tasks;
private Map<String, Boolean> permissions;
private Set<SavedUser> savedUsers;
private Settings settings;
@@ -123,7 +120,6 @@ public class FabricHuskHomes implements DedicatedServerModInitializer, HuskHomes
instance = this;
// Get plugin version from mod container
this.tasks = new ConcurrentHashMap<>();
this.permissions = new HashMap<>();
this.savedUsers = new HashSet<>();
this.globalPlayerList = new HashMap<>();
@@ -151,6 +147,13 @@ public class FabricHuskHomes implements DedicatedServerModInitializer, HuskHomes
// Create adventure audience
this.audiences = FabricServerAudiences.of(minecraftServer);
// Temporarily log about sounds being disabled - todo: Remove when adventure-platform-fabric is updated
if (getSettings().doPlaySoundEffects()) {
log(Level.WARNING, "Sound effects are currently disabled for HuskHomes v" +
getVersion() + " on Fabric servers running Minecraft " +
getMinecraftServer().getVersion());
}
// Initialize the database
initialize(getSettings().getDatabaseType().getDisplayName() + " database connection", (plugin) -> {
this.database = switch (getSettings().getDatabaseType()) {
@@ -209,7 +212,7 @@ public class FabricHuskHomes implements DedicatedServerModInitializer, HuskHomes
audiences.close();
audiences = null;
}
cancelAllTasks();
cancelTasks();
}
@Override
@@ -479,12 +482,6 @@ public class FabricHuskHomes implements DedicatedServerModInitializer, HuskHomes
return minecraftServer;
}
@Override
@NotNull
public ConcurrentHashMap<UUID, CompletableFuture<?>> getTasks() {
return tasks;
}
@Override
@NotNull
public FabricHuskHomes getPlugin() {
@@ -120,9 +120,15 @@ public class FabricUser extends OnlineUser {
return player;
}
@Override
public void playSound(@NotNull String soundEffect) throws IllegalArgumentException {
// Do nothing - todo: Fix sounds when adventure-platform-fabric is updated.
}
@Override
public void teleportLocally(@NotNull Location location, boolean asynchronous) throws TeleportationException {
final MinecraftServer server = player.getServer();
assert server != null : "Server is null";
final Identifier worldId = Identifier.tryParse(location.getWorld().getName());
player.teleport(
server.getWorld(server.getWorldRegistryKeys().stream()
@@ -0,0 +1,142 @@
/*
* This file is part of HuskHomes, licensed under the Apache License 2.0.
*
* Copyright (c) William278 <[email protected]>
* Copyright (c) contributors
*
* 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
*
* http://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.
*/
package net.william278.huskhomes.util;
import net.william278.huskhomes.FabricHuskHomes;
import net.william278.huskhomes.HuskHomes;
import org.jetbrains.annotations.NotNull;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
public interface FabricTask extends Task {
class Sync extends Task.Sync implements FabricTask {
protected Sync(@NotNull HuskHomes plugin, @NotNull Runnable runnable, long delayTicks) {
super(plugin, runnable, delayTicks);
}
@Override
public void cancel() {
super.cancel();
}
@Override
public void run() {
if (!cancelled) {
if (delayTicks > 0) {
CompletableFuture.runAsync(() -> {
try {
Thread.sleep(delayTicks * 50);
} catch (InterruptedException e) {
e.printStackTrace();
}
((FabricHuskHomes) getPlugin()).getMinecraftServer().executeSync(runnable);
}, ((FabricHuskHomes) getPlugin()).getMinecraftServer());
} else {
((FabricHuskHomes) getPlugin()).getMinecraftServer().executeSync(runnable);
}
}
}
}
class Async extends Task.Async implements FabricTask {
private CompletableFuture<Void> task;
protected Async(@NotNull HuskHomes plugin, @NotNull Runnable runnable) {
super(plugin, runnable);
}
@Override
public void cancel() {
if (task != null && !cancelled) {
task.cancel(true);
}
super.cancel();
}
@Override
public void run() {
if (!cancelled) {
this.task = CompletableFuture.runAsync(runnable, ((FabricHuskHomes) getPlugin()).getMinecraftServer());
}
}
}
class Repeating extends Task.Repeating implements FabricTask {
private ScheduledFuture<?> task;
protected Repeating(@NotNull HuskHomes plugin, @NotNull Runnable runnable, long repeatingTicks) {
super(plugin, runnable, repeatingTicks);
}
@Override
public void cancel() {
if (task != null && !cancelled) {
task.cancel(true);
}
super.cancel();
}
@Override
public void run() {
if (!cancelled) {
this.task = Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(
runnable, 0, repeatingTicks * 50, TimeUnit.MILLISECONDS
);
}
}
}
interface Supplier extends Task.Supplier {
@NotNull
@Override
default Task.Sync getSyncTask(@NotNull Runnable runnable, long delayTicks) {
return new Sync(getPlugin(), runnable, delayTicks);
}
@NotNull
@Override
default Task.Async getAsyncTask(@NotNull Runnable runnable) {
return new Async(getPlugin(), runnable);
}
@NotNull
@Override
default Task.Repeating getRepeatingTask(@NotNull Runnable runnable, long repeatingTicks) {
return new Repeating(getPlugin(), runnable, repeatingTicks);
}
@Override
default void cancelTasks() {
// Do nothing
}
}
}
@@ -1,101 +0,0 @@
/*
* This file is part of HuskHomes, licensed under the Apache License 2.0.
*
* Copyright (c) William278 <[email protected]>
* Copyright (c) contributors
*
* 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
*
* http://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.
*/
package net.william278.huskhomes.util;
import net.william278.huskhomes.FabricHuskHomes;
import org.jetbrains.annotations.NotNull;
import java.util.UUID;
import java.util.concurrent.*;
import java.util.function.Supplier;
public interface FabricTaskRunner extends TaskRunner {
@Override
default void runAsync(@NotNull Runnable runnable) {
CompletableFuture.runAsync(runnable, getPlugin().getMinecraftServer());
}
@Override
default <T> CompletableFuture<T> supplyAsync(@NotNull Supplier<T> supplier) {
return CompletableFuture.supplyAsync(supplier, getPlugin().getMinecraftServer());
}
@Override
default void runSync(@NotNull Runnable runnable) {
getPlugin().getMinecraftServer().executeSync(runnable);
}
@NotNull
@Override
default UUID runAsyncRepeating(@NotNull Runnable runnable, long delay) {
final UUID taskId = UUID.randomUUID();
final CompletableFuture<?> future = new CompletableFuture<>();
final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
executor.scheduleAtFixedRate(() -> {
if (future.isCancelled()) {
executor.shutdown();
return;
}
runnable.run();
}, 0, delay * 50, TimeUnit.MILLISECONDS);
getTasks().put(taskId, future);
return taskId;
}
@Override
default void runLater(@NotNull Runnable runnable, long delay) {
CompletableFuture.runAsync(() -> {
try {
Thread.sleep(delay * 50);
} catch (InterruptedException e) {
e.printStackTrace();
return;
}
runnable.run();
}, getPlugin().getMinecraftServer());
}
@Override
default void cancelTask(@NotNull UUID taskId) {
getTasks().computeIfPresent(taskId, (uuid, completableFuture) -> {
completableFuture.cancel(true);
return null;
});
getTasks().remove(taskId);
}
@Override
default void cancelAllTasks() {
getTasks().values().forEach(task -> task.cancel(true));
getTasks().clear();
}
@NotNull
@Override
ConcurrentHashMap<UUID, CompletableFuture<?>> getTasks();
@Override
@NotNull
FabricHuskHomes getPlugin();
}
+2 -2
View File
@@ -27,8 +27,8 @@
]
},
"depends": {
"fabricloader": ">=0.14.21",
"minecraft": ">=1.20",
"fabricloader": ">=${fabric_loader_version}",
"minecraft": ">=${fabric_minecraft_version}",
"fabric-api": "*"
},
"custom": {
+7 -2
View File
@@ -5,8 +5,13 @@ org.gradle.daemon=true
plugin_version=4.3.3
plugin_archive=huskhomes
plugin_description=The powerful and intuitive set homes, warps, and teleports plugin/mod
plugin_description=The powerful and intuitive homes, warps, and teleports plugin/mod
jedis_version=4.4.2
sqlite_driver_version=3.42.0.0
mysql_driver_version=8.0.33
mysql_driver_version=8.0.33
fabric_minecraft_version=1.20.1
fabric_loader_version=0.14.21
fabric_yarn_mappings=1.20.1+build.2
fabric_api_version=0.83.1+1.20.1
+1 -1
View File
@@ -47,6 +47,6 @@ shadowJar {
tasks {
runServer {
minecraftVersion('1.20')
minecraftVersion('1.20.1')
}
}
@@ -48,7 +48,7 @@ import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.user.SavedUser;
import net.william278.huskhomes.user.SpongeUser;
import net.william278.huskhomes.util.SpongeSafetyResolver;
import net.william278.huskhomes.util.SpongeTaskRunner;
import net.william278.huskhomes.util.SpongeTask;
import net.william278.huskhomes.util.UnsafeBlocks;
import net.william278.huskhomes.util.Validator;
import org.bstats.charts.SimplePie;
@@ -80,12 +80,12 @@ import java.lang.reflect.InvocationTargetException;
import java.net.URI;
import java.nio.file.Path;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.stream.Collectors;
@Plugin("huskhomes")
public class SpongeHuskHomes implements HuskHomes, SpongeTaskRunner, SpongeSafetyResolver, SpongeEventDispatcher, RawPlayDataHandler<EngineConnection> {
public class SpongeHuskHomes implements HuskHomes, SpongeTask.Supplier, SpongeSafetyResolver, SpongeEventDispatcher,
RawPlayDataHandler<EngineConnection> {
/**
* Metrics ID for <a href="https://bstats.org/plugin/sponge/HuskHomes/18423">HuskHomes on Sponge</a>.
@@ -110,7 +110,6 @@ public class SpongeHuskHomes implements HuskHomes, SpongeTaskRunner, SpongeSafet
@Inject
private Metrics.Factory metricsFactory;
private ConcurrentHashMap<UUID, CancellableRunnable> tasks;
private Set<SavedUser> savedUsers;
private Settings settings;
private Locales locales;
@@ -134,7 +133,6 @@ public class SpongeHuskHomes implements HuskHomes, SpongeTaskRunner, SpongeSafet
instance = this;
// Get plugin version from mod container
this.tasks = new ConcurrentHashMap<>();
this.savedUsers = new HashSet<>();
this.globalPlayerList = new HashMap<>();
this.currentlyOnWarmup = new HashSet<>();
@@ -210,7 +208,7 @@ public class SpongeHuskHomes implements HuskHomes, SpongeTaskRunner, SpongeSafet
if (broker != null) {
broker.close();
}
cancelAllTasks();
cancelTasks();
}
@Listener
@@ -516,12 +514,6 @@ public class SpongeHuskHomes implements HuskHomes, SpongeTaskRunner, SpongeSafet
return channel;
}
@NotNull
@Override
public ConcurrentHashMap<UUID, CancellableRunnable> getTasks() {
return tasks;
}
@NotNull
@Override
public SpongeHuskHomes getPlugin() {
@@ -0,0 +1,145 @@
/*
* This file is part of HuskHomes, licensed under the Apache License 2.0.
*
* Copyright (c) William278 <[email protected]>
* Copyright (c) contributors
*
* 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
*
* http://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.
*/
package net.william278.huskhomes.util;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.SpongeHuskHomes;
import org.jetbrains.annotations.NotNull;
import org.spongepowered.api.scheduler.ScheduledTask;
import org.spongepowered.api.util.Ticks;
import static org.spongepowered.api.scheduler.Task.builder;
public interface SpongeTask extends Task {
class Sync extends Task.Sync implements SpongeTask {
private ScheduledTask task;
protected Sync(@NotNull HuskHomes plugin, @NotNull Runnable runnable, long delayTicks) {
super(plugin, runnable, delayTicks);
}
@Override
public void cancel() {
if (task != null && !cancelled) {
task.cancel();
}
super.cancel();
}
@Override
public void run() {
if (!cancelled) {
final SpongeHuskHomes plugin = ((SpongeHuskHomes) getPlugin());
this.task = plugin.getGame().server().scheduler().submit(builder()
.plugin(plugin.getPluginContainer())
.delay(Ticks.of(delayTicks))
.execute(runnable)
.build());
}
}
}
class Async extends Task.Async implements SpongeTask {
private ScheduledTask task;
protected Async(@NotNull HuskHomes plugin, @NotNull Runnable runnable) {
super(plugin, runnable);
}
@Override
public void cancel() {
if (task != null && !cancelled) {
task.cancel();
}
super.cancel();
}
@Override
public void run() {
if (!cancelled) {
final SpongeHuskHomes plugin = ((SpongeHuskHomes) getPlugin());
this.task = plugin.getGame().asyncScheduler().submit(builder()
.plugin(plugin.getPluginContainer())
.execute(runnable)
.build());
}
}
}
class Repeating extends Task.Repeating implements SpongeTask {
private ScheduledTask task;
protected Repeating(@NotNull HuskHomes plugin, @NotNull Runnable runnable, long repeatingTicks) {
super(plugin, runnable, repeatingTicks);
}
@Override
public void cancel() {
if (task != null && !cancelled) {
task.cancel();
}
super.cancel();
}
@Override
public void run() {
if (!cancelled) {
final SpongeHuskHomes plugin = ((SpongeHuskHomes) getPlugin());
this.task = plugin.getGame().asyncScheduler().submit(builder()
.plugin(plugin.getPluginContainer())
.interval(Ticks.of(repeatingTicks))
.execute(runnable)
.build());
}
}
}
interface Supplier extends Task.Supplier {
@NotNull
@Override
default Task.Sync getSyncTask(@NotNull Runnable runnable, long delayTicks) {
return new Sync(getPlugin(), runnable, delayTicks);
}
@NotNull
@Override
default Task.Async getAsyncTask(@NotNull Runnable runnable) {
return new Async(getPlugin(), runnable);
}
@NotNull
@Override
default Task.Repeating getRepeatingTask(@NotNull Runnable runnable, long repeatingTicks) {
return new Repeating(getPlugin(), runnable, repeatingTicks);
}
@Override
default void cancelTasks() {
// Do nothing
}
}
}
@@ -1,142 +0,0 @@
/*
* This file is part of HuskHomes, licensed under the Apache License 2.0.
*
* Copyright (c) William278 <[email protected]>
* Copyright (c) contributors
*
* 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
*
* http://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.
*/
package net.william278.huskhomes.util;
import net.william278.huskhomes.SpongeHuskHomes;
import org.jetbrains.annotations.NotNull;
import org.spongepowered.api.scheduler.Task;
import org.spongepowered.api.util.Ticks;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Supplier;
public interface SpongeTaskRunner extends TaskRunner {
@Override
default void runAsync(@NotNull Runnable runnable) {
getPlugin().getGame().asyncScheduler()
.submit(Task.builder()
.plugin(getPlugin().getPluginContainer())
.execute(wrap(runnable))
.build());
}
@Override
default <T> CompletableFuture<T> supplyAsync(@NotNull Supplier<T> supplier) {
final CompletableFuture<T> future = new CompletableFuture<>();
getPlugin().getGame().asyncScheduler()
.submit(Task.builder()
.plugin(getPlugin().getPluginContainer())
.execute(() -> future.complete(supplier.get()))
.build());
return future;
}
@Override
default void runSync(@NotNull Runnable runnable) {
getPlugin().getGame().server().scheduler()
.submit(Task.builder()
.plugin(getPlugin().getPluginContainer())
.execute(runnable)
.build());
}
@NotNull
@Override
default UUID runAsyncRepeating(@NotNull Runnable runnable, long delay) {
final UUID taskId = UUID.randomUUID();
final CancellableRunnable task = wrap(runnable);
getTasks().put(taskId, task);
getPlugin().getGame().asyncScheduler()
.submit(Task.builder()
.plugin(getPlugin().getPluginContainer())
.execute(task)
.interval(Ticks.of(delay))
.build());
return taskId;
}
@Override
default void runLater(@NotNull Runnable runnable, long delay) {
getPlugin().getGame().server().scheduler()
.submit(Task.builder()
.plugin(getPlugin().getPluginContainer())
.execute(runnable)
.delay(Ticks.of(delay))
.build());
}
@Override
default void cancelTask(@NotNull UUID taskId) {
getTasks().computeIfPresent(taskId, (id, task) -> {
task.cancel();
return null;
});
getTasks().remove(taskId);
}
@Override
default void cancelAllTasks() {
getTasks().values().forEach(CancellableRunnable::cancel);
getTasks().clear();
}
@NotNull
private CancellableRunnable wrap(@NotNull Runnable runnable) {
return new CancellableRunnable(runnable);
}
@NotNull
@Override
ConcurrentHashMap<UUID, CancellableRunnable> getTasks();
@NotNull
@Override
SpongeHuskHomes getPlugin();
/**
* A wrapper for a {@link Runnable} that can be canceled
*/
class CancellableRunnable implements Runnable {
private final Runnable runnable;
private boolean cancelled = false;
CancellableRunnable(@NotNull Runnable runnable) {
this.runnable = runnable;
}
@Override
public void run() {
if (cancelled) {
return;
}
runnable.run();
}
public void cancel() {
cancelled = true;
}
}
}