Skip to content

Commit

Permalink
refactor: removed unnecessary save/load method duplicates, use Comple…
Browse files Browse the repository at this point in the history
…tableFuture<LocalGame> on loading, add missing Locale.ROOT param to toLower/UpperCase() method invocations
  • Loading branch information
Misat11 committed Jul 3, 2024
1 parent 6d1e980 commit 84ee0bc
Show file tree
Hide file tree
Showing 19 changed files with 75 additions and 76 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -405,13 +405,6 @@ default boolean isActivated() {
*/
boolean isInEditMode();

/**
* This methods allows you to save the arena to config (useful when using custom config options)
*
* @since 0.3.0
*/
void saveToConfig();

/**
* Gets file with this game
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,32 +23,37 @@
import org.jetbrains.annotations.Nullable;

import java.io.File;
import java.util.concurrent.CompletableFuture;

/**
* LocalGameLoader API to load or save a game to or from a file.
*
* @author ScreamingSandals
* @since 0.3.0
*/
public interface LocalGameLoader {

/**
* NOTE: The plugin may postpone the game loading to the next tick if it cannot locate the world on the first try.
* This operation runs synchronized with the game global thread, so do not try to invoke {@link CompletableFuture#get()} from that thread!
*
* @param file a file containing the game data
* @return a game instance populated from the given file, null otherwise
* @return a completable future returning game instance populated from the given file or null
*/
@Nullable
default LocalGame loadGame(File file) {
default @NotNull CompletableFuture<? extends @Nullable LocalGame> loadGame(@NotNull File file) {
return loadGame(file, true);
}

/**
* NOTE: The plugin may postpone the game loading to the next tick if it cannot locate the world on the first try.
* This operation runs synchronized with the game global thread, so do not try to invoke {@link CompletableFuture#get()} from that thread!
* If the parameter {@code firstAttempt} is {@code false}, the plugin will not try to postpone the loading and will instead return already completed future.
*
* @param file a file containing the game data
* @param firstAttempt provide true to attempt a sequential load after a failed one as a fix for world loading.
* @return a loaded game instance from the provided file, null otherwise
* @return a completable future returning loaded game instance from the provided file or null
*/
@Nullable
LocalGame loadGame(File file, boolean firstAttempt);
@NotNull CompletableFuture<? extends @Nullable LocalGame> loadGame(@NotNull File file, boolean firstAttempt);

/**
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ public void accept(@NotNull TaskBase taskBase) {
// TODO: slib?
@Override
public void spawnEffect(@NotNull org.screamingsandals.lib.world.Location location, @NotNull String value) {
var particle = Effect.valueOf(value.toUpperCase());
var particle = Effect.valueOf(value.toUpperCase(Locale.ROOT));
var bukkitLoc = location.as(Location.class);
bukkitLoc.getWorld().playEffect(bukkitLoc, particle, 1);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.stream.Collectors;

Expand Down Expand Up @@ -272,7 +273,7 @@ public void load() {

@OnEnable
public void enable() {
var snapshot = VersionInfo.VERSION.toLowerCase().contains("pre") || VersionInfo.VERSION.toLowerCase().contains("snapshot");
var snapshot = VersionInfo.VERSION.toLowerCase(Locale.ROOT).contains("pre") || VersionInfo.VERSION.toLowerCase(Locale.ROOT).contains("snapshot");

Debug.init(pluginDescription.name());
Debug.setDebug(MainConfig.getInstance().node("debug").getBoolean());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@

import java.util.LinkedList;
import java.util.List;
import java.util.Locale;

@Getter
public class BossBarImpl implements org.screamingsandals.bedwars.api.boss.BossBar {
Expand Down Expand Up @@ -123,7 +124,7 @@ public void setColor(@NotNull Object color) {
if (color instanceof BossBarColor) {
boss.color((BossBarColor) color);
} else {
boss.color(BossBarColor.valueOf(color.toString().toUpperCase()));
boss.color(BossBarColor.valueOf(color.toString().toUpperCase(Locale.ROOT)));
}
}

Expand All @@ -137,7 +138,7 @@ public void setStyle(@NotNull Object division) {
if (division instanceof BossBarDivision) {
boss.division((BossBarDivision) division);
} else {
var ov = division.toString().toUpperCase();
var ov = division.toString().toUpperCase(Locale.ROOT);
if (ov.equals("SOLID") || ov.equals("PROGRESS")) {
ov = "NO_DIVISION";
} else if (ov.startsWith("SEGMENTED_")) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.stream.Collectors;
Expand All @@ -74,7 +75,7 @@ public void construct() {
.withSuggestionsProvider((c, s) -> makeSuggestion(c, true, ConfigurationContainerImpl::getJoinedRegisteredKeysForConfigCommand))
)
.handler(commandContext -> handleCommand(commandContext, true, (sender, container, configuredComponentName) -> { // Allow this without edit mode
var keyString = commandContext.<String>get("key").toLowerCase();
var keyString = commandContext.<String>get("key").toLowerCase(Locale.ROOT);
var keys = List.of(keyString.split("\\."));

var keyOpt = container.getRegisteredKeys()
Expand Down Expand Up @@ -200,7 +201,7 @@ public void construct() {
.withSuggestionsProvider((c, s) -> makeSuggestion(c, false, ConfigurationContainerImpl::getJoinedRegisteredKeysForConfigCommand))
)
.handler(commandContext -> handleCommand(commandContext, false, (sender, container) -> {
var keyString = commandContext.<String>get("key").toLowerCase();
var keyString = commandContext.<String>get("key").toLowerCase(Locale.ROOT);
var keys = List.of(keyString.split("\\."));

var keyOpt = container.getRegisteredKeys()
Expand Down Expand Up @@ -244,7 +245,7 @@ public void construct() {
argumentName -> StringArgument.<CommandSender>newBuilder(argumentName)
.greedy()
.withSuggestionsProvider((commandContext, sender) -> makeSuggestion(commandContext, false, container -> {
var keys = List.of(commandContext.<String>get("key").toLowerCase().split("\\."));
var keys = List.of(commandContext.<String>get("key").toLowerCase(Locale.ROOT).split("\\."));

var key = container.getRegisteredKeys()
.stream()
Expand Down Expand Up @@ -348,7 +349,7 @@ public void construct() {
)
.argument(StringArgument.<CommandSender>newBuilder("value")
.withSuggestionsProvider((commandContext, sender) -> makeSuggestion(commandContext, false, container -> {
var keys = List.of(commandContext.<String>get("key").toLowerCase().split("\\."));
var keys = List.of(commandContext.<String>get("key").toLowerCase(Locale.ROOT).split("\\."));

var key = container.getRegisteredKeys()
.stream()
Expand All @@ -367,7 +368,7 @@ public void construct() {
)
.handler(commandContext -> handleCommand(commandContext, false, (sender, container) -> {
String keyString = commandContext.get("key");
var keys = List.of(keyString.toLowerCase().split("\\."));
var keys = List.of(keyString.toLowerCase(Locale.ROOT).split("\\."));
String value = commandContext.get("value");

var keyOpt = container.getRegisteredKeys()
Expand All @@ -386,7 +387,7 @@ public void construct() {
} catch (Throwable ignored) {
try {
//noinspection unchecked
enumValue = Enum.valueOf((Class) key.getType(), value.toUpperCase());
enumValue = Enum.valueOf((Class) key.getType(), value.toUpperCase(Locale.ROOT));
} catch (Throwable ignored2) {
Message.of(LangKeys.ADMIN_ARENA_EDIT_ERRORS_INVALID_CONSTANT_ENUM_VALUE)
.placeholder("value", value)
Expand Down Expand Up @@ -434,7 +435,7 @@ private <T> void generateCommands(
)
.argument(argumentBuilder.apply("value"))
.handler(commandContext -> handleCommand(commandContext, false, (sender, container) -> {
var keyString = commandContext.<String>get("key").toLowerCase();
var keyString = commandContext.<String>get("key").toLowerCase(Locale.ROOT);
var keys = List.of(keyString.split("\\."));
var value = commandContext.get("value");

Expand Down Expand Up @@ -471,7 +472,7 @@ private <T> void generateCommands(
.argument(argumentListBuilder.apply("value"))
.handler(commandContext -> handleCommand(commandContext, false, (sender, container) -> {
String keyString = commandContext.get("key");
var keys = List.of(keyString.toLowerCase().split("\\."));
var keys = List.of(keyString.toLowerCase(Locale.ROOT).split("\\."));
var value = commandContext.get("value");

var keyOpt = container.getRegisteredListKeys()
Expand Down Expand Up @@ -512,7 +513,7 @@ private <T> void generateCommands(
.argument(argumentListBuilder.apply("value"))
.handler(commandContext -> handleCommand(commandContext, false, (sender, container) -> {
String keyString = commandContext.get("key");
var keys = List.of(keyString.toLowerCase().split("\\."));
var keys = List.of(keyString.toLowerCase(Locale.ROOT).split("\\."));
int position = commandContext.get("position");
var value = commandContext.get("value");

Expand Down Expand Up @@ -573,7 +574,7 @@ private <T> void generateCommands(
.argument(IntegerArgument.of("position"))
.handler(commandContext -> handleCommand(commandContext, false, (sender, container) -> {
String keyString = commandContext.get("key");
var keys = List.of(keyString.toLowerCase().split("\\."));
var keys = List.of(keyString.toLowerCase(Locale.ROOT).split("\\."));
int position = commandContext.get("position");

@SuppressWarnings("unchecked")
Expand Down Expand Up @@ -619,7 +620,7 @@ private <T> void generateCommands(
.literal("clear", "c")
.handler(commandContext -> handleCommand(commandContext, false, (sender, container) -> {
String keyString = commandContext.get("key");
var keys = List.of(keyString.toLowerCase().split("\\."));
var keys = List.of(keyString.toLowerCase(Locale.ROOT).split("\\."));

var keyOpt = container.getRegisteredListKeys()
.stream()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
import org.jetbrains.annotations.NotNull;
import org.screamingsandals.bedwars.commands.AdminCommand;
import org.screamingsandals.bedwars.game.GameManagerImpl;
import org.screamingsandals.bedwars.game.LocalGameLoaderImpl;
import org.screamingsandals.bedwars.lang.LangKeys;
import org.screamingsandals.lib.lang.Message;
import org.screamingsandals.lib.sender.CommandSender;
Expand Down Expand Up @@ -94,7 +95,7 @@ private void save(@NotNull CommandContext<CommandSender> commandContext) {
}

if (warnings.isEmpty()) {
game.saveToConfig();
LocalGameLoaderImpl.getInstance().saveGame(game);
GameManagerImpl.getInstance().addGame(game);
game.start();
sender.sendMessage(Message.of(LangKeys.ADMIN_ARENA_EDIT_SUCCESS_SAVED_AND_STARTED).placeholderRaw("game", game.getName()).defaultPrefix());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -548,7 +548,7 @@ public void construct(CommandManager<CommandSender> manager, Command.Builder<Com
manager.command(
commandSenderWrapperBuilder
.literal("target")
.literal("countdown")
.literal("expirable")
.argument(teamNameArgument)
.argument(IntegerArgument.<CommandSender>newBuilder("countdown").withMin(1))
.handler(commandContext -> editMode(commandContext, (sender, game) -> {
Expand Down Expand Up @@ -584,7 +584,7 @@ public void construct(CommandManager<CommandSender> manager, Command.Builder<Com
manager.command(
commandSenderWrapperBuilder
.literal("target")
.literal("block-countdown")
.literal("block-expirable")
.argument(teamNameArgument)
.argument(IntegerArgument.<CommandSender>newBuilder("countdown").withMin(1))
.argument(EnumArgument.optional(TargetBlockSetModes.class, "mode", TargetBlockSetModes.LOOKING_AT))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -177,14 +177,6 @@ public class GameImpl implements LocalGame {
@Setter(AccessLevel.PROTECTED)
private boolean preparing = false;

public static GameImpl loadGame(File file) {
return loadGame(file, true);
}

public static GameImpl loadGame(File file, boolean firstAttempt) {
return LocalGameLoaderImpl.getInstance().loadGame(file, firstAttempt);
}

public void removeEntity(Entity e) {
if (ArenaUtils.isInArea(e.getLocation(), pos1, pos2)) {
final var chunk = e.getLocation().getChunk();
Expand Down Expand Up @@ -761,11 +753,6 @@ public void internalLeavePlayer(BedWarsPlayer gamePlayer) {
}
}

@SneakyThrows
public void saveToConfig() {
LocalGameLoaderImpl.getInstance().saveGame(this);
}

public void start() {
if (status == GameStatus.DISABLED) {
preparing = true;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -140,11 +140,12 @@ public void onPostEnable() {
logger.debug("No arenas have been found!");
} else {
results.forEach(file -> {
if (file.exists() && file.isFile() && !file.getName().toLowerCase().endsWith(".disabled")) {
var game = GameImpl.loadGame(file);
if (game != null) {
games.add(game);
}
if (file.exists() && file.isFile() && !file.getName().toLowerCase(Locale.ROOT).endsWith(".disabled")) {
LocalGameLoaderImpl.getInstance().loadGame(file, true).thenAccept(game -> {
if (game != null) {
games.add(game);
}
});
}
});
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
import org.spongepowered.configurate.ConfigurationNode;

import java.util.Arrays;
import java.util.Locale;
import java.util.Objects;

@AllArgsConstructor
Expand Down Expand Up @@ -78,7 +79,7 @@ public ItemStack getItem(int amount) {
}

public static ItemSpawnerTypeImpl deserialize(String spawnerKey, ConfigurationNode node) {
spawnerKey = spawnerKey.toLowerCase();
spawnerKey = spawnerKey.toLowerCase(Locale.ROOT);

var name = node.node("name").getString();
var translate = node.node("translate").getString();
Expand All @@ -94,7 +95,7 @@ public static ItemSpawnerTypeImpl deserialize(String spawnerKey, ConfigurationNo
if (split.length == 2) {
try {
var longValue = Long.parseLong(split[0]);
var unitName = split[1].toUpperCase().trim();
var unitName = split[1].toUpperCase(Locale.ROOT).trim();
if (!unitName.endsWith("S")) {
unitName += "S";
}
Expand Down
Loading

0 comments on commit 84ee0bc

Please sign in to comment.